Python3 unpickle a string representation of bytes object
pickle, python, python-3.x
Solution
For a safety concern you can use `ast.literal_eval` instead of `eval`:
>>> import ast
>>> pickle.loads(ast.literal_eval(string_of_bytes_obj))
{'b': 2222, 'a': 1111}
Problem
Is there a good way to load a bytes object that is represented as a string, so it can be unpickled? Basic Example Here is a dumb example: ``` import pickle mydict = { 'a': 1111, 'b': 2222 } string_of_bytes_obj = str(pickle.dumps(mydict)) # Deliberate string representation for this quick example. unpickled_dict = pickle.loads(string_of_bytes_obj) # ERROR! Loads takes bytes-like object and not string. ``` Attempt at a Solution One solution is of course to `eval` the string: ``` unpickled_dict = pickle.loads(eval(string_of_bytes_obj)) ``` But, seems wrong to `eval`, especially when the strings might be coming over a network or from a file. ... Any suggestions for a better solution? Thanks!