copyreg — Registerpickle support functions

Source code:Lib/copyreg.py


Thecopyreg module offers a way to define functions used while picklingspecific objects. Thepickle andcopy modules use those functionswhen pickling/copying those objects. The module provides configurationinformation about object constructors which are not classes.Such constructors may be factory functions or class instances.

copyreg.constructor(object)

Declaresobject to be a valid constructor. Ifobject is not callable (andhence not valid as a constructor), raisesTypeError.

copyreg.pickle(type,function,constructor_ob=None)

Declares thatfunction should be used as a “reduction” function for objectsof typetype.function must return either a string or a tuplecontaining between two and six elements. See thedispatch_tablefor more details on the interface offunction.

Theconstructor_ob parameter is a legacy feature and is now ignored, but ifpassed it must be a callable.

Note that thedispatch_table attribute of a picklerobject or subclass ofpickle.Pickler can also be used fordeclaring reduction functions.

Example

The example below would like to show how to register a pickle function and howit will be used:

>>>importcopyreg,copy,pickle>>>classC:...def__init__(self,a):...self.a=a...>>>defpickle_c(c):...print("pickling a C instance...")...returnC,(c.a,)...>>>copyreg.pickle(C,pickle_c)>>>c=C(1)>>>d=copy.copy(c)pickling a C instance...>>>p=pickle.dumps(c)pickling a C instance...