3.14.5.1 Pickling and unpickling normal class instances

Python 2.2

3.14.5.1 Pickling and unpickling normal class instances

When a pickled class instance is unpickled, its __init__() method is normally not invoked. If it is desirable that the __init__() method be called on unpickling, an old-style class can define a method __getinitargs__(), which should return a tuple containing the arguments to be passed to the class constructor (i.e. __init__()). The __getinitargs__() method is called at pickle time; the tuple it returns is incorporated in the pickle for the instance.

New-style types can provide a __getnewargs__() method that is used for protocol 2. Implementing this method is needed if the type establishes some internal invariants when the instance is created, or if the memory allocation is affected by the values passed to the __new__() method for the type (as it is for tuples and strings). Instances of a new-style type C are created using


 obj = C.__new__(C, *args)
 

where args is the result of calling __getnewargs__() on the original object; if there is no __getnewargs__(), an empty tuple is assumed.

Classes can further influence how their instances are pickled; if the class defines the method __getstate__(), it is called and the return state is pickled as the contents for the instance, instead of the contents of the instance's dictionary. If there is no __getstate__() method, the instance's __dict__ is pickled.

Upon unpickling, if the class also defines the method __setstate__(), it is called with the unpickled state.3.6 If there is no __setstate__() method, the pickled state must be a dictionary and its items are assigned to the new instance's dictionary. If a class defines both __getstate__() and __setstate__(), the state object needn't be a dictionary and these methods can do what they want.3.7

Warning: For new-style classes, if __getstate__() returns a false value, the __setstate__() method will not be called.


Footnotes

These methods can also be used to implement copying class instances.
This protocol is also used by the shallow and deep copying operations defined in the copy module.
See About this document... for information on suggesting changes.