Reputation: 46683
I have a python dictionary that I'd like to serialize into python source code required to initialize that dictionary's keys and values.
I'm looking for something like json.dumps()
, but the output format should be Python not JSON.
My object is very simple: it's a dictionary whose values are one of the following:
I know I can build one myself, but I suspect there are corner cases involving nested objects, keyword escaping, etc. so I'd prefer to use an existing library with those kinks already worked out.
Upvotes: 5
Views: 1446
Reputation: 127467
In the most general case, it's not possible to dump an arbitrary Python object into Python source code. E.g. if the object is a socket, recreating the very same socket in a new object cannot work.
As aix explains, for the simple case, repr
is explicitly designed to make reproducable source representations. As a slight generalization, the pprint module allows selective customization through the PrettyPrinter class.
If you want it even more general, and if your only requirement is that you get executable Python source code, I recommend to pickle the object into a string, and then generate the source code
obj = pickle.loads(%s)
where %s
gets substituted with repr(pickle.dumps(obj))
.
Upvotes: 3
Reputation: 48577
You can use yaml
YAML doesn't serialise EXACTLY to python source code. But the yaml module can directly serialise and deserialise python objects. It's a superset of JSON.
What exactly are you trying to do?
Upvotes: 0
Reputation: 500437
repr(d)
where d
is your dictionary could be a start (doesn't address all the issues that you mention though).
Upvotes: 2