Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't serialise objects with numpy elements #32

Open
brianbienvenu opened this issue Nov 12, 2018 · 1 comment
Open

Can't serialise objects with numpy elements #32

brianbienvenu opened this issue Nov 12, 2018 · 1 comment

Comments

@brianbienvenu
Copy link

Trying to write out an object with a numpy element (ndarray) throws this:

  File "/usr/local/lib/python3.7/dist-packages/cbor2/encoder.py", line 428, in dump
    CBOREncoder(fp, **kwargs).encode(obj)
  File "/usr/local/lib/python3.7/dist-packages/cbor2/encoder.py", line 386, in encode
    encoder(self, obj)
  File "/usr/local/lib/python3.7/dist-packages/cbor2/encoder.py", line 49, in wrapper
    func(encoder, value, *args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/cbor2/encoder.py", line 107, in encode_array
    encoder.encode(item)
  File "/usr/local/lib/python3.7/dist-packages/cbor2/encoder.py", line 386, in encode
    encoder(self, obj)
  File "/usr/local/lib/python3.7/dist-packages/cbor2/encoder.py", line 49, in wrapper
    func(encoder, value, *args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/cbor2/encoder.py", line 115, in encode_map
    encoder.encode(val)
  File "/usr/local/lib/python3.7/dist-packages/cbor2/encoder.py", line 384, in encode
    raise CBOREncodeError('cannot serialize type %s' % obj_type.__name__)
cbor2.encoder.CBOREncodeError: cannot serialize type ndarray

Can this be handled better?

@Sekenre
Copy link
Collaborator

Sekenre commented Nov 12, 2018

Hi @brianbienvenu have a look at https://cbor2.readthedocs.io/en/latest/customizing.html#using-the-cbor-tags-for-custom-types and https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.dumps.html#numpy.ndarray.dumps

Unfortunately ndarrays are wrappers around multi-dimensional buffers of C-types so it might be easiest for you to pickle them and save the resulting bytes as a single tagged item than encode them in CBOR.

Alternatively you could serialize them item-by-item as lists of lists of integers. This will be slow on both encode and decode. ndarrays also come with a bunch of metadata that needs to be saved and recreated.

Sekenre added a commit to Sekenre/cbor2 that referenced this issue Sep 28, 2020
Fix for agronholm#32
Does not require Numpy, can't handle 128bit floating point.
@Sekenre Sekenre added this to the RFC8746 Typed Arrays milestone Sep 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants