Debian Codegraph @

Doc/library/copyreg.rst

raw
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 pair: module; pickle
11 pair: module; copy
12
13 --------------
14
15 The :mod:`!copyreg` module offers a way to define functions used while pickling
16 specific objects. The :mod:`pickle` and :mod:`copy` modules use those functions
17 when pickling/copying those objects. The module provides configuration
18 information about object constructors which are not classes.
19 Such 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_ob=None)
29
30 Declares that *function* should be used as a "reduction" function for objects
31 of type *type*. *function* must return either a string or a tuple
32 containing between two and six elements. See the :attr:`~pickle.Pickler.dispatch_table`
33 for more details on the interface of *function*.
34
35 The *constructor_ob* parameter is a legacy feature and is now ignored, but if
36 passed it must be a callable.
37
38 Note that the :attr:`~pickle.Pickler.dispatch_table` attribute of a pickler
39 object or subclass of :class:`pickle.Pickler` can also be used for
40 declaring reduction functions.
41
42 Example
43 -------
44
45 The example below would like to show how to register a pickle function and how
46 it will be used:
47
48 >>> import copyreg, copy, pickle
49 >>> class C:
50 ... def __init__(self, a):
51 ... self.a = a
52 ...
53 >>> def pickle_c(c):
54 ... print("pickling a C instance...")
55 ... return C, (c.a,)
56 ...
57 >>> copyreg.pickle(C, pickle_c)
58 >>> c = C(1)
59 >>> d = copy.copy(c) # doctest: +SKIP
60 pickling a C instance...
61 >>> p = pickle.dumps(c) # doctest: +SKIP
62 pickling a C instance...