23 Jun 2009

Pickling Complex Classes

If you’ve got a particularly complicated python class that you need to pickle, you might find that it’s a little unusual when it comes out the other side. This could be because by default __init__ and __new__ aren’t called on objects when they’re unpickled.

If you need your init/new behaviour to be called at unpickle time, you can define __getinitargs__ or __getnewargs__ to request the methods you want to be run. These methods should return tuples containing the variables you’d like to call the method of your choice with. They’re called at pickle time and the tuple that they generate is stored with the object.

More detailed information can be found in this useful guide.