Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing python object to python source code

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:

  1. built-in type literals (strings, ints, etc.)
  2. lists of literals

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.

like image 248
Justin Grant Avatar asked Dec 23 '10 19:12

Justin Grant


People also ask

What is serializing an object in Python?

Serialization refers to the process of converting a data object (e.g., Python objects, Tensorflow models) into a format that allows us to store or transmit the data and then recreate the object when needed using the reverse process of deserialization.

Can you pickle an object Python?

Python comes with a built-in package, known as pickle , that can be used to perform pickling and unpickling operations. Pickling and unpickling in Python is the process that is used to describe the conversion of objects into byte streams and vice versa - serialization and deserialization, using Python's pickle module.


1 Answers

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

like image 180
Martin v. Löwis Avatar answered Sep 24 '22 05:09

Martin v. Löwis