Skip to content

ENH: improve StringDType error in from buffer results #26893

Open

Description

@flying-sheep

Describe the issue:

See title: serializing a string array to a buffer and trying to deserialize it fails.

No matter if if the problem is generic or about using None as na_object, the error message is wrong:
I’m not trying to create an object array.

Reproduce the code example:

import numpy as np

string_dtype = np.dtypes.StringDType(na_object=None)

buf = np.array([[None], ["bcdef"]], dtype=dtype).tobytes()
np.frombuffer(buf, dtype=string_dtype)

Error message:

ValueError
----> 6 np.frombuffer(buf, dtype=string_dtype)
ValueError: cannot create an OBJECT array from memory buffer

Python and NumPy Versions:

2.0.0
3.12.4 (main, Jun 7 2024, 06:33:07) [GCC 14.1.1 20240522]

Runtime Environment:

[{'numpy_version': '2.0.0',
  'python': '3.12.4 (main, Jun  7 2024, 06:33:07) [GCC 14.1.1 20240522]',
  'uname': uname_result(system='Linux', node='gnosis', release='6.9.8-zen1-1-zen', version='#1 ZEN SMP PREEMPT_DYNAMIC Fri, 05 Jul 2024 22:11:01 +0000', machine='x86_64')},
 {'simd_extensions': {'baseline': ['SSE', 'SSE2', 'SSE3'],
                      'found': ['SSSE3',
                                'SSE41',
                                'POPCNT',
                                'SSE42',
                                'AVX',
                                'F16C',
                                'FMA3',
                                'AVX2'],
                      'not_found': ['AVX512F',
                                    'AVX512CD',
                                    'AVX512_KNL',
                                    'AVX512_KNM',
                                    'AVX512_SKX',
                                    'AVX512_CLX',
                                    'AVX512_CNL',
                                    'AVX512_ICL',
                                    'AVX512_SPR']}},
 {'architecture': 'Zen',
  'filepath': '/usr/lib/libopenblas.so.0.3',
  'internal_api': 'openblas',
  'num_threads': 16,
  'prefix': 'libopenblas',
  'threading_layer': 'openmp',
  'user_api': 'blas',
  'version': '0.3.27'},
 {'filepath': '/usr/lib/libgomp.so.1.0.0',
  'internal_api': 'openmp',
  'num_threads': 16,
  'prefix': 'libgomp',
  'user_api': 'openmp',
  'version': None}]

Context for the issue:

No response

Activity

  1. seberg commented on Jul 9, 2024

    @seberg
    Member

    The error is correct, you can't dump objects to bytes reasonably (yes, it does it, but the result is raw pointers). And you can even less read a StringDType from it, since it contains references (to the dtype side storage).

    The only odd thing here is that it prints OBJECT when it should say "that contain references" (and of course the first part should maybe fail already).

  2. changed the title [-]BUG: trying to read StringDType array from buffer results in “cannot create an OBJECT array from memory buffer”[/-] [+]DOC: improve StringDType error in from buffer results[/+] on Jul 9, 2024
  3. changed the title [-]DOC: improve StringDType error in from buffer results[/-] [+]ENH: improve StringDType error in from buffer results[/+] on Jul 9, 2024
  4. flying-sheep commented on Jul 9, 2024

    @flying-sheep
    ContributorAuthor

    So numpy tries to serialize the na_object or what?

  5. seberg commented on Jul 9, 2024

    @seberg
    Member

    Right but StringDType is the same here, in that it cannot be dumped since the array contains references and you get the references only.

  6. flying-sheep commented on Jul 9, 2024

    @flying-sheep
    ContributorAuthor

    Hm, so apparently quite some of my assumptions were wrong. I assumed

    1. StringDType arrays contain no external references, just offsets: one internal array for offsets, the other for string data, similar to csr_matrix or so.
    2. The StringDType (and therefore the na_object) isn’t stored in the buffer. Why would it be: frombuffer has a dtype parameter that isn’t None by default, therefore there is no way to tell frombuffer to get dtype from the data, therefore I assumed it’s not in there.

    Are both of these wrong?

    /edit: I found this now https://numpy.org/neps/nep-0055-string_dtype.html#serialization

    Since string data are stored outside the array buffer, serialization to the npy format would requires a format revision to support storing variable-width sidecare data. Rather than doing this as part of this effort, we do not plan on supporting serialization to the npy or npz format without specifying allow_pickle=True.

    This is a continuation of the current situation with object string arrays, which can only be saved to an npy file using the allow_pickle=True option.

    In the future we may decide to add support for this, but care should be taken to not break parsers outside of NumPy that may not be maintained.

  7. seberg commented on Jul 9, 2024

    @seberg
    Member

    Are both of these wrong?

    They are both partially right, but your assumption about what tobytes() does is very wrong. It refers only the main array buffer which is the offsets in your view (but it's not actually plain offsets).

  8. flying-sheep commented on Jul 9, 2024

    @flying-sheep
    ContributorAuthor

    I see, thank you. So I guess I'll also file thr feature request predicted as

    In the future we may decide to add support for this

    in NEP55

  9. ngoldbaum commented on Jul 9, 2024

    @ngoldbaum
    Member

    Yeah, unfortunately this would require a format update for the npy file format and I didn't want to take that on just to ship StringDType. See #24110, #25374, and #25498 for all the discussion we had about this when I realized it would require a change to the npy file format.

  10. mullenkamp commented on Jul 29, 2025

    @mullenkamp

    Hi,

    So just to be clear, there's no way to serialize a StringDType array (to bytes) in a way that can be parsed back into a new StringDType array (aside from pickle)?

  11. ngoldbaum commented on Jul 29, 2025

    @ngoldbaum
    Member

    Nope and me and others are very aware this is an issue. See #29229 for our latest take on this. @seberg and I are also looking at if we can update the buffer protocol to allow e.g. cython to parse numpy buffers. See https://discuss.python.org/t/buffer-protocol-and-arbitrary-data-types/26256/13 and da-woods/cython#5 for the latest on that.

  12. ngoldbaum commented on Jul 29, 2025

    @ngoldbaum
    Member

    Can you share a little more what you're trying to do? Are you limited to only using Python APIs or can you use the numpy C API too?

  13. mullenkamp commented on Jul 29, 2025

    @mullenkamp

    Thank you very much for your quick reply with those links. I have to admit, some of those technical details are currently beyond my knowledge...
    My use case is that I'm converting numpy arrays to bytes (which is then compressed using zstandard) then stored on disk or on S3. These bytes (representing a single array) will either be appended on a single file or stored separately. I then retrieve those arrays as needed for my processing and analysis.
    I'm sure I can use a fancier/more complicated python package to do this, but I like to make things simple.
    Unfortunately, I've never written any C code, so I'm limited to python in this case.
    The variable length strings are handy, because you don't have to know the bit length ahead of time (if more data is appended later).

  14. flying-sheep commented on Jul 30, 2025

    @flying-sheep
    ContributorAuthor

    OK, so basically all this means that you still can’t store string arrays using nothing but numpy’s codecs. If you use numpy’s save and load, you still need to have allow_pickle=True set.

    I think pickles are pretty stable these days, but if you want rock-solid future-proof storage, you’re still going to need to use something like hdf5, zarr or arrow(/parquet).

    TBF, using one of these codecs is simpler than what numpy does, because Python pickles are much more complex than a well-specified codec that can’t hold basically arbitrary objects defined by an interpreted language.

    (@team please correct me if I’m being inaccurate in any detail here)

  15. ngoldbaum commented on Jul 30, 2025

    @ngoldbaum
    Member

    You can store a pickle as bytes too:

    In [1]: arr = np.array(['hello', 'world', None], dtype='T')
    
    In [2]: import pickle
    
    In [3]: pickle.dumps(arr)
    Out[3]: b'\x80\x05\x95\xb2\x00\x00\x00\x00\x00\x00\x00\x8c\x16numpy._core.multiarray\x94\x8c\x0c_reconstruct\x94\x93\x94\x8c\x05numpy\x94\x8c\x07ndarray\x94\x93\x94K\x00\x85\x94C\x01b\x94\x87\x94R\x94(K\x01K\x03\x85\x94\x8c\x15numpy._core._internal\x94\x8c\x1e_convert_to_stringdtype_kwargs\x94\x93\x94K\x01\x85\x94R\x94\x89]\x94(\x8c\x05hello\x94\x8c\x05world\x94\x8c\x04None\x94et\x94b.'
    

    Both h5py and zarr have support for StringDType in recent versions and I would look at those for any "real" data storage.

    I think the fact that tobytes() doesn't consider references is probably a bug? This is probably not what anyone wants:

    In [2]: arr = np.array(['hello'*25, 'world', None], dtype='O')
    
    In [3]: arr.tobytes()
    Out[3]: b'\xb0\xd0\xc9\x08\x01\x00\x00\x000\xc9\xce\x08\x01\x00\x00\x00\x881/\x05\x01\x00\x00\x00'
    
    In [4]: del arr
    
    In [5]: arr = np.array(['hello'*25, 'world', None], dtype='O')
    
    In [6]: arr.tobytes()
    Out[6]: b'\xf0\xae\x01\x0c\x01\x00\x00\x000my\n\x01\x00\x00\x00\x881/\x05\x01\x00\x00\x00'
    

    Note how the output is different for the first two items. This is because the strings aren't immortal, and a new PyObject instance is allocated every time you create a python string containing that data. tobytes() for object arrays just prints out the value of the PyObject pointer, which can change if an object is deallocated and then reallocated, for example.

    (incidentally None is immortal so the last item is the same in both serializations)

    Both StringDType and object arrays are arrays of references and we need better support for them in NumPy in general. We have an opportunity to solve this for all new DTypes we might ever want to add to NumPy in the future, which might include other arrays of references. I'd prefer to work on that instead of one-off fixes for StringDType.

    I think the work @MaanasArora is spearheading the first step - we need to define what exactly is needed for producers and consumers of ndarray buffers and we need to make sure parsers fail gracefully if they're handed data they don't understand. Once that is all well-defined we can then write serializers and deserializers that conform to the spec. At that point it may also make sense to update the npy file format or just say more advanced uses that are currently unsupported require other solutions like zarr or h5py. We should also make the npy format work with dtypes where it makes sense right now, like bfloat16 or a quad precision dtype.

  16. mullenkamp commented on Jul 30, 2025

    @mullenkamp

    Thank you very much @ngoldbaum (and @flying-sheep) for your detailed reply. I 100% agree with your assessment and proposed approach.

    I had assumed that the tobytes() method should return the bytes directly associated with the data in the array rather than pointers to some other object. And that tobytes() should raise an exception if it cannot serialize the data to bytes (e.g. object dtype). But this is coming from the perspective that np.frombuffer should be able to parse any output from tobytes(). This is definitely implied in the docs for both functions (hence the "Inverse of this operation" reference).

    I recognize that this is purely my opinion, and you all should follow through with what you think is appropriate from the overall numpy scope.

    Thanks again!

  17. seberg commented on Jul 31, 2025

    @seberg
    Member

    I would be fine to deprecate or warn that tobytes() is pretty useless if a dtype has references. In practice it doesn't round-trip anyway, since frombytes() will correctly reject it.
    Not sure if there are users who want it to just work (mostly) for some dtype with references for some weird reason.

    For round-tripping, it seems not too worrying to me, since it fails later pretty clearly (sure could say "references" rather than "object" (or the actual dtype), but I guess someone may use tobytes() for something else (hashing?) and not realize that it isn't reliable; unless they actually don't care that it isn't reliable...

    (If we change things here, then we should probably keep it in synch with buffer-protocol export without a format/dtype.)

  18. MaanasArora commented on Aug 4, 2025

    @MaanasArora
    Contributor

    Yes, the error could be clearer, but I think it makes sense that getting bytes from the buffer protocol (tobytes) maybe wouldn't be expected to work correctly when dtypes start using in-memory references - if we change things we would have to consider all the different ways that the references are put into place and perhaps tobytes isn't the best place for that (given it is synced with the buffer protocol as @seberg mentioned).

    As @ngoldbaum mentioned we've been working on starting to define a schema that acts as a contract for the data needed to read and write for array serialization (in #29229), so maybe that's a better place to make sure we have the correct data / bytes; and tools like Zarr will probably be better specialized to handle serialization than any changes we do in these NumPy methods itself right now.

    I still think there's something nice about keeping tobytes working; I'm just wondering how we can do it minimally, and I think the answer could be clearer when we have some of the new serialization in place! So improving the error message for now could be a good short-term solution.

  19. added
    sustain-2026
    on Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    01 - Enhancementsustain-2026

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions