1

This is a simple question but I cannot seem to figure it out. I want to take the bytes outputted from a pickle.dumps() and convert it str and be able to convert it back to bytes compatible such that pickle.loads(string_thing) can recover the original object.

encoded = pickle.dumps(None)
string_encoded = to_string(encoded)
decoded = pickle.loads(safe_decoder(string_encoded))

I know one of the objections are going to be, "why do you need to do this?" Restrictions on allowed types.

2
  • What, specifically, is wrong with the posted code? Commented May 30, 2019 at 12:48
  • 3
    Base64 encode/decode it…? Commented May 30, 2019 at 12:52

1 Answer 1

2

@deceze gives a good idea: use the module base64 with its functions .b64encode() and .b64decode().

Here is an example:

>>> 'Álñó@'
'Álñó@'
>>> 'Álñó@'.encode()
b'\xc3\x81l\xc3\xb1\xc3\xb3@'
>>> base64.b64encode('Álñó@'.encode())
b'w4Fsw7HDs0A='
>>> base64.b64encode('Álñó@'.encode()).decode()
'w4Fsw7HDs0A='

Now you have a string in base64. For the reverse process:

>>> base64.b64encode('Álñó@'.encode()).decode().encode()
b'w4Fsw7HDs0A='
>>> base64.b64decode(base64.b64encode('Álñó@'.encode()).decode().encode())
b'\xc3\x81l\xc3\xb1\xc3\xb3@'
>>> base64.b64decode(base64.b64encode('Álñó@'.encode()).decode().encode()).decode()
'Álñó@'

Would that work for you?


Example using pickle:

>>> original_obj = 456.5
>>> original_obj
456.5
>>> type(original_obj)
<class 'float'>
>>> intermediate_str = base64.b64encode(pickle.dumps(original_obj)).decode()
>>> intermediate_str
'gANHQHyIAAAAAAAu'

>>> new_obj = pickle.loads(base64.b64decode(intermediate_str.encode()))
>>> new_obj
456.5
>>> type(new_obj)
<class 'float'>

>>> original_obj == new_obj
True
Sign up to request clarification or add additional context in comments.

1 Comment

@deceze I completely forgot about the base64 module! Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.