1

I would to serialize my object ancd encode() decode() it for manage byte/string format. I try creating this class:

class test(object):
    def __init__(self,uid):
        self.uid.uid

at this point instantiate the objest and serialize it:

inst_a = test(1)
pickle.dumps(inst_a)

return

b'\x80\x04\x95$\x00\x00\x00\x00\x00\x00\x00\x8c\x08__main__\x94\x8c\x04test\x94\x93\x94)\x81\x94}\x94\x8c\x03uid\x94K\x01sb.'

all done. Now i would transform from byte to string but when i do:

pickle.dumps(ins_a).decode()

i get

Traceback (most recent call last): File "<pyshell#11>", line 1, in pickle.dumps(a).decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

why thi appen? how can i decode/encode my serialized object for transform it from byte to string and vice versa?

So many thanks indeed

Manuel Santi
  • 1,106
  • 17
  • 46
  • Try decoding it as `encoding="latin1"` in which all byte values are valid. Might have to encode it, too. See the **Portablity to Python 3** section of this [answer](https://stackoverflow.com/a/18561055/355230) of mine for an example of doing this and more details. – martineau Sep 25 '20 at 04:24

1 Answers1

1

pickle.dumps creates a byte array object (denoted by b'...') which do not have to be a valid Unicode string therefore decode method on such a byte array can fail as it failed for you.

In general, the byte array from pickle.dumps should not ever be interpreted as string. It is an internal representation of pickle module and there is no guarantee to be a valid string in any encoding (and a Unicode one in particular).

If your intention is to transform the picked object back to an original object then use pickle.loads method on the result from pickle.dumps. You can of course write it to a file / read it to a file in between (as is the typical use case).

sophros
  • 14,672
  • 11
  • 46
  • 75