Repository navigation
Closed
Description
Currently if you try to use np.save and np.load with a new-style dtype, you'll get this error:
from stringdtype import StringDType
import numpy as np
arr = np.array(["hello", "world"], dtype=StringDType)
np.savez("arr.npz", arr)
with np.load("arr.npz") as data:
larr = data['arr_0']
print(larr)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/format.py:661, in _read_array_header(fp, version, max_header_size)
660 try:
--> 661 dtype = descr_to_dtype(d['descr'])
662 except TypeError as e:
File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/format.py:306, in descr_to_dtype(descr)
304 if isinstance(descr, str):
305 # No padding removal needed
--> 306 return numpy.dtype(descr)
307 elif isinstance(descr, tuple):
308 # subtype, will always have a shape descr[1]
TypeError: data type '|\x0016' not understood
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
Cell In[10], line 7
5 np.savez("arr.npz", arr)
6 with np.load("arr.npz") as data:
----> 7 larr = data['arr_0']
8 print(larr)
File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/npyio.py:253, in NpzFile.__getitem__(self, key)
251 if magic == format.MAGIC_PREFIX:
252 bytes = self.zip.open(key)
--> 253 return format.read_array(bytes,
254 allow_pickle=self.allow_pickle,
255 pickle_kwargs=self.pickle_kwargs,
256 max_header_size=self.max_header_size)
257 else:
258 return self.zip.read(key)
File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/format.py:786, in read_array(fp, allow_pickle, pickle_kwargs, max_header_size)
784 version = read_magic(fp)
785 _check_version(version)
--> 786 shape, fortran_order, dtype = _read_array_header(
787 fp, version, max_header_size=max_header_size)
788 if len(shape) == 0:
789 count = 1
File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/format.py:664, in _read_array_header(fp, version, max_header_size)
662 except TypeError as e:
663 msg = "descr is not a valid dtype descriptor: {!r}"
--> 664 raise ValueError(msg.format(d['descr'])) from e
666 return d['shape'], d['fortran_order'], dtype
ValueError: descr is not a valid dtype descriptor: '|\x0016'
So at a minimum we need to update these functions to save the correct descriptor metadata to allow reconstructing the descriptor in np.load.
For stringdtype we need sidecar storage, which might need a new revision to the npy file format spec to add extra metadata for the sidecar storage. However as a first pass we could just re-use the flag that's already in the file format spec that indicate the array data are stored in an inline pickle file.
Activity
ngoldbaum commentedon Jul 6, 2023
np.saveconstructs the header for an array in theheader_data_from_array_1_0function. There's a bit of indirection, but all non-legacy dtypes will end up being saved using thedtype.strtypestring from the__array_interface__protocol. This is a problem, because non-legacy dtypes don't yet have a typestring following that protocol.I could save some kind of ad-hoc string. I could save the descriptor as a pickle (although that won't help if
allow_pickleis False). A more complete fix would be to implement #23500 and extend whatever we come up with there to the__array_interface__protocol.rkern commentedon Jul 6, 2023
Truly supporting this probably really does require a NEP for a major revision of the NPY format, for which the time is probably right. Looking up the third-party dtype, possibly importing modules new to the process, is a significant change that needs discussion. The NPY format was initially designed to be very minimalistic. Extending it to be a container for fairly arbitrary contents (like the sidecar data) is an expansion of scope that needs to be weighed. There are also a lot of innovations in the ecosystem (more efficient pickle formats, Arrow, etc.) that are now worth weighing.
In the short term, I do think that we can detect these custom dtypes and default to the pickle escape hatch, just as if we had an
objectdtype.ngoldbaum commentedon Jul 6, 2023
One wrinkle is the dtype class needs to be reconstructed as well, so we'd either need to pickle the descriptor (ugly and breaks the data format, since the
descrfield in the header contains inline data) or add support in NumPy for loading custom data types from a string. Both approaches require an import of the extension defining the custom dtype, which you seemed dubious about.Would you be OK with something like the
_dtype_from_buffer_fmtfunction in @seberg's comment here, which might import an arbitrary python module depending on the content of the format code?rkern commentedon Jul 6, 2023
Hmm, right. NEP time, then, if not PEP time.
rkern commentedon Jul 6, 2023
One hack, that's still probably NEP-worthy, is to detect these dtypes and just write out the
descras if it were adtype=objectarray. This would be a lie, on paper, but that information won't actually be used in the reconstructed array sincenp.load()would just unpickle the data there and return the unpickled object.ENH: Allow NEP 42 dtypes to use np.save and np.load (#24142)