In the most general case, it is not possible to unload an arbitrary Python object into the Python source code. For instance. if the object is a socket, re-creating the same socket in the new object cannot work.
As aix explains, for a simple case, repr explicitly intended to create reproducible representations of sources. As a small generalization, the pprint module allows customization through the PrettyPrinter class.
If you want it to be even more general, and if your only requirement is to get executable Python source code, I recommend that you sort the object into a string and then generate the source code
obj = pickle.loads(%s)
where %s is replaced by repr(pickle.dumps(obj)) .
source share