1

In the following code:

>>> import pickle
>>>
>>> class Thing:
    def __init__(self):
        self.name = "stackoverflow"
        self.age = 11

>>> a = pickle.dumps(Thing())
>>> a
b'\x80\x03c__main__\nThing\nq\x00)\x81q\x01}q\x02(X\x04\x00\x00\x00nameq\x03X\r\x00\x00\x00stackoverflowq\x04X\x03\x00\x00\x00ageq\x05K\x0bub.'
>>> str(a)
"b'\\x80\\x03c__main__\\nThing\\nq\\x00)\\x81q\\x01}q\\x02(X\\x04\\x00\\x00\\x00nameq\\x03X\\r\\x00\\x00\\x00stackoverflowq\\x04X\\x03\\x00\\x00\\x00ageq\\x05K\\x0bub.'"

My question is, how do I convert str(a) back to a, since once that conversion happens I can easily decode using pickle.loads()

The reason that I am converting to string is that I wish to add str(a) string to another string that will be further "pickled." Most of the other posts I have seen assume that the bytes are already an encoding of a string or string to byte conversion, none of which this is.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Just keep `a` around and don't assign anything else to it then you can use it later. – wwii Mar 10 '19 at 22:04
  • 2
    You probably can't add another string to a pickled object string safely. What are you trying to achieve here? – roganjosh Mar 10 '19 at 22:14

1 Answers1

0

The following seems to work because arbitrary binary strings are valid latin1 which can always be decoded to Unicode and then encoded back to the original string again (as pointed out in this answer by Sven Marnach).

import pickle

class Thing:
    def __init__(self):
        self.name = "stackoverflow"
        self.age = 11

a = pickle.dumps(Thing())
str_a = a.decode('latin1')    
b = str_a.encode('latin1')

assert a == b
martineau
  • 119,623
  • 25
  • 170
  • 301