1:mod:`copyreg` --- Register :mod:`pickle` support functions 2=========================================================== 3 4.. module:: copyreg 5 :synopsis: Register pickle support functions. 6 7**Source code:** :source:`Lib/copyreg.py` 8 9.. index:: 10 module: pickle 11 module: copy 12 13-------------- 14 15The :mod:`copyreg` module offers a way to define functions used while pickling 16specific objects. The :mod:`pickle` and :mod:`copy` modules use those functions 17when pickling/copying those objects. The module provides configuration 18information about object constructors which are not classes. 19Such constructors may be factory functions or class instances. 20 21 22.. function:: constructor(object) 23 24 Declares *object* to be a valid constructor. If *object* is not callable (and 25 hence not valid as a constructor), raises :exc:`TypeError`. 26 27 28.. function:: pickle(type, function, constructor=None) 29 30 Declares that *function* should be used as a "reduction" function for objects 31 of type *type*. *function* should return either a string or a tuple 32 containing two or three elements. 33 34 The optional *constructor* parameter, if provided, is a callable object which 35 can be used to reconstruct the object when called with the tuple of arguments 36 returned by *function* at pickling time. :exc:`TypeError` will be raised if 37 *object* is a class or *constructor* is not callable. 38 39 See the :mod:`pickle` module for more details on the interface 40 expected of *function* and *constructor*. Note that the 41 :attr:`~pickle.Pickler.dispatch_table` attribute of a pickler 42 object or subclass of :class:`pickle.Pickler` can also be used for 43 declaring reduction functions. 44 45Example 46------- 47 48The example below would like to show how to register a pickle function and how 49it will be used: 50 51 >>> import copyreg, copy, pickle 52 >>> class C: 53 ... def __init__(self, a): 54 ... self.a = a 55 ... 56 >>> def pickle_c(c): 57 ... print("pickling a C instance...") 58 ... return C, (c.a,) 59 ... 60 >>> copyreg.pickle(C, pickle_c) 61 >>> c = C(1) 62 >>> d = copy.copy(c) # doctest: +SKIP 63 pickling a C instance... 64 >>> p = pickle.dumps(c) # doctest: +SKIP 65 pickling a C instance... 66