Python safe serialization?
Are there any libraries for serialization and safe deserialization of Python objects?
By "safe" I mean that the objects will come from an untrusted source (over the network). I know Python comes with pickle and marshal, but neither of those provides any safety for deserializing untrusted objects.
I have a set of classes that I would like to serialize/deserialize, and they all inherit from a common base class. Ideally the library would be able to deserialize an instance to its original subclass (and refuse to deserialize objects that are not instances of the base class). All of the member variables of the classes contain either instances of Python built-in types, or instances of another serializable class from the same set (but there are no reference cycles or other funny business). Finally, it would be nice if the library serializes to JSON but it is not a hard requirement.
Are there any libraries that can do the above securely, and if so, what would you recommend?
Posted Jun 27, 2011, 5:23 PM UTC
Use YAML (a superset of JSON) as your serialization format with PyYAML.
Features of YAML include object type tagging, support for references (it handles reference cycles just fine), and when using PyYAML's "safe" dumper/loader, the ability to define which of your classes should be considered safe.
Thanks, that looks like exactly what I need! I'll be sure to check it out.
PyYAML, since it is so flexible and human readable, is easy to debug. Coding for custom classes is quite straightforward.