3.14.5.2 Pickling and unpickling extension types

When the Pickler encounters an object of a type it knows nothing about -- such as an extension type -- it looks in two places for a hint of how to pickle it. One alternative is for the object to implement a __reduce__() method. If provided, at pickling time __reduce__() will be called with no arguments, and it must return either a string or a tuple.

If a string is returned, it names a global variable whose contents are pickled as normal. When a tuple is returned, it must be of length two or three, with the following semantics:

Upon unpickling, the callable will be called (provided that it meets the above criteria), passing in the tuple of arguments; it should return the unpickled object.

If the second item was None, then instead of calling the callable directly, its __basicnew__() method is called without arguments. It should also return the unpickled object.

Deprecated since release 2.3. Use the tuple of arguments instead

An alternative to implementing a __reduce__() method on the object to be pickled, is to register the callable with the copy_reg module. This module provides a way for programs to register ``reduction functions'' and constructors for user-defined types. Reduction functions have the same semantics and interface as the __reduce__() method described above, except that they are called with a single argument, the object to be pickled.

The registered constructor is deemed a ``safe constructor'' for purposes of unpickling as described above.

See About this document... for information on suggesting changes.