[Python-ideas] Serializable method

Steven D'Aprano steve at pearwood.info
Sat Mar 10 00:22:57 CET 2012

On Fri, Mar 09, 2012 at 05:05:51PM +0000, Jakob Bowyer wrote:

> I think that object should provide an __serializable__ method which in-turn
> allows the user to define in it how the object is to be serialized, 

I don't think this is a sensible approach. In general, you don't 
serialise a single object, you serialise a bunch of them. Suppose you 
serialise three objects spam, ham, and eggs to a single file. 
Unfortunately, spam uses pickle, ham uses JSON, and eggs uses plist. How 
would you read the data back later? How do you know which de-serialiser 
you should use for each object? What happens if you end up with 
ambiguous content?

You would need some sort of meta-serialiser, that not just recorded each 
serialised string, but also the format of that string.

I don't think that it is helpful to ask objects to serialise themselves, 
giving them the choice of what serialisation scheme to use. While 
freedom of choice is good, it should be the *caller* who chooses the 
scheme, not the individual objects.

So at the very least, for this idea to have legs, you would have to 
mandate a serialisation scheme which well-behaved objects ought to 
support. But Python already has that: pickle. If you want to mandate a 
second scheme, to overcome the known deficiencies of pickle, that's a 
separate issue.

> the
> default operation should be something along the lines of  return
> self.__dict__ but that is just semantics. 

Returning __dict__ can't work, because not all objects have a 
self.__dict__, and for those that do, it is not a string but a dict.

[Aside: I don't understand why people say "that is just semantics" to 
dismiss something as trivial. Semantics is the *meaning* of something. 
It is the most fundamental, critical property of language. Without 
semantics, if I say "I got in the car and drove to work" you would not 
know if I actually got in the car and drove to work, or stayed home to 
watch television.]


More information about the Python-ideas mailing list