spdl.io.load_npy

load_npy(data: bytes | bytearray | memoryview[bytes], *, copy: bool = False) → NDArray[source]

Load NumPy NDArray from bytes.

This function loads NumPy NDArray from memory. It is equivalent to numpy.load(io.BytesIO(data)), but it is more efficient.

Note

This function does not support object, structured, or record dtypes.

Example

>>> ref = np.arange(20)
>>> buffer = BytesIO()
>>> np.save(buffer, ref)
>>> buffer.seek(0)
>>> data = buffer.getvalue()
>>> restore = spdl.io.load_npy(data)
>>> assert np.array_equal(restore, ref)
Parameters:
  • data – The data generated by numpy.save() function. (Note that it is different from numpy.ndarray.tobytes(), which does not contain shape and dtype.)

  • copy – Whether to copy data. With the default False, the returned array is a view and inherits the source buffer’s writability. Passing True returns an independent, writable array.

Returns:

The restored array data.

Changed in version 0.7.0: Zero-copy arrays now retain their source buffer and are read-only when that source is read-only. A resizable source cannot be resized while a returned zero-copy array is alive. Pass copy=True when a writable, independently resizable array is required. Fortran-contiguous arrays now expose their column-major strides correctly. Malformed shape or dtype metadata and truncated payloads are now rejected instead of constructing an invalid array view.

See also

Note

There is a branch in _read_array function where the execution can call some faster implementation. However, BytesIO does not meet the condition. (isfileobj() returns False for io.BytesIO. [source]) Even if the execution takes the faster numpy.fromfile() path, it creates a new array.