MCPcopy Index your code
hub / github.com/python/cpython / cast_items

Function cast_items

Lib/test/test_buffer.py:665–696  ·  view source on GitHub ↗

Interpret the raw memory of 'exporter' as a list of items with size 'itemsize'. If shape=None, the new structure is assumed to be 1-D with n * itemsize = bytelen. If shape is given, the usual constraint for contiguous arrays prod(shape) * itemsize = bytelen applies. On su

(exporter, fmt, itemsize, shape=None)

Source from the content-addressed store, hash-verified

663# ======================================================================
664
665def cast_items(exporter, fmt, itemsize, shape=None):
666 """Interpret the raw memory of 'exporter' as a list of items with
667 size 'itemsize'. If shape=None, the new structure is assumed to
668 be 1-D with n * itemsize = bytelen. If shape is given, the usual
669 constraint for contiguous arrays prod(shape) * itemsize = bytelen
670 applies. On success, return (items, shape). If the constraints
671 cannot be met, return (None, None). If a chunk of bytes is interpreted
672 as NaN as a result of float conversion, return ('nan', None)."""
673 bytelen = exporter.nbytes
674 if shape:
675 if prod(shape) * itemsize != bytelen:
676 return None, shape
677 elif shape == []:
678 if exporter.ndim == 0 or itemsize != bytelen:
679 return None, shape
680 else:
681 n, r = divmod(bytelen, itemsize)
682 shape = [n]
683 if r != 0:
684 return None, shape
685
686 mem = exporter.tobytes()
687 byteitems = [mem[i:i+itemsize] for i in range(0, len(mem), itemsize)]
688
689 items = []
690 for v in byteitems:
691 item = struct.unpack(fmt, v)[0]
692 if item != item:
693 return 'nan', shape
694 items.append(item)
695
696 return (items, shape) if shape != [] else (items[0], shape)
697
698def gencastshapes():
699 """Generate shapes to test casting."""

Callers 2

test_memoryview_castMethod · 0.85

Calls 3

unpackMethod · 0.80
prodFunction · 0.70
appendMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…