blob: 18306c7f99f08dc13aa9bdccc36e1b92fee585b7 [file] [log] [blame]
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001:mod:`copyreg` --- Register :mod:`pickle` support functions
Georg Brandl71515ca2009-05-17 12:29:12 +00002===========================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00004.. module:: copyreg
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: Register pickle support functions.
6
7
8.. index::
9 module: pickle
Georg Brandl116aa622007-08-15 14:28:22 +000010 module: copy
11
Zachary Ware56dee1e2015-02-19 22:30:15 -060012The :mod:`copyreg` module offers a way to define functions used while pickling
Ezio Melotti78b18d42012-11-08 11:04:57 +020013specific objects. The :mod:`pickle` and :mod:`copy` modules use those functions
14when pickling/copying those objects. The module provides configuration
15information about object constructors which are not classes.
Benjamin Petersonb5314c62009-12-13 21:04:16 +000016Such constructors may be factory functions or class instances.
Georg Brandl116aa622007-08-15 14:28:22 +000017
18
19.. function:: constructor(object)
20
21 Declares *object* to be a valid constructor. If *object* is not callable (and
22 hence not valid as a constructor), raises :exc:`TypeError`.
23
24
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000025.. function:: pickle(type, function, constructor=None)
Georg Brandl116aa622007-08-15 14:28:22 +000026
Georg Brandl23e8db52008-04-07 19:17:06 +000027 Declares that *function* should be used as a "reduction" function for objects
28 of type *type*. *function* should return either a string or a tuple
29 containing two or three elements.
Georg Brandl116aa622007-08-15 14:28:22 +000030
31 The optional *constructor* parameter, if provided, is a callable object which
32 can be used to reconstruct the object when called with the tuple of arguments
33 returned by *function* at pickling time. :exc:`TypeError` will be raised if
34 *object* is a class or *constructor* is not callable.
35
Antoine Pitrou8d3c2902012-03-04 18:31:48 +010036 See the :mod:`pickle` module for more details on the interface
37 expected of *function* and *constructor*. Note that the
38 :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.
Ezio Melotti78b18d42012-11-08 11:04:57 +020041
42Example
43-------
44
45The example below would like to show how to register a pickle function and how
46it will be used:
47
48 >>> import copyreg, copy, pickle
49 >>> class C(object):
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)
60 pickling a C instance...
61 >>> p = pickle.dumps(c)
62 pickling a C instance...