Serializing a python object for python source code

I have a python dictionary that I would like to serialize into the python source code needed to initialize these keys and dictionary values.

I am looking for something like json.dumps() , but the output format should be Python, not JSON.

My object is very simple: it is a dictionary whose values ​​are one of the following:

  • built-in literal types (strings, ints, etc.)
  • lists of literals

I know that I can create it myself, but I suspect that there are angular cases related to nested objects, dropping keywords, etc., so I would prefer to use the existing library with already developed kinks.

+4
source share
3 answers

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)) .

+3
source

repr(d) where d - your dictionary may begin (does not affect all the problems you mention).

+2
source

You can use yaml

http://pyyaml.org/

YAML does not serialize EXACTLY to the python source code. But yaml module can directly serialize and deserialize python objects. This is a superset of JSON.

What exactly are you trying to do?

0
source

Source: https://habr.com/ru/post/1333231/


All Articles