5

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.

2
  • Python not Json? what are you talking about? Commented Dec 23, 2010 at 19:29
  • 'obj = json.loads(%r)' % json.dumps(some_dict)? ☃ Commented Dec 23, 2010 at 20:51

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

PrettyPrinter looks like exactly what I was looking for. The objects I'm trying to serialize are very simple-- a dictionary whose values are either literals or lists of literals. Thanks!
2

repr(d) where d is your dictionary could be a start (doesn't address all the issues that you mention though).

3 Comments

Will repr() handle nesting, as long as the nested values are lists whose elements can be properly emitted by repr()?
also use import ast; ast.literal_eval(s) to read the dict back
@Spike Nice, thanks for pointing out ast.literal_eval. I didn't know about it.
0

You can use yaml

http://pyyaml.org/

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.