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=None)

Declares thatfunction should be used as a “reduction” function for objectsof typetype.function should return either a string or a tuplecontaining two or three elements.

The optionalconstructor parameter, if provided, is a callable object whichcan be used to reconstruct the object when called with the tuple of argumentsreturned byfunction at pickling time. ATypeError is raised if theconstructor is not callable.

See thepickle module for more details on the interfaceexpected offunction andconstructor. 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...