~dkuhlman/python-training-materials/Materials

« back to all changes in this revision

Viewing changes to python-3.5.1-docs-html/_sources/library/copyreg.txt

  • Committer: Dave Kuhlman
  • Date: 2017-04-15 16:24:56 UTC
  • Revision ID: dkuhlman@davekuhlman.org-20170415162456-iav9vozzg4iwqwv3
Updated docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
:mod:`copyreg` --- Register :mod:`pickle` support functions
2
 
===========================================================
3
 
 
4
 
.. module:: copyreg
5
 
   :synopsis: Register pickle support functions.
6
 
 
7
 
 
8
 
.. index::
9
 
   module: pickle
10
 
   module: copy
11
 
 
12
 
The :mod:`copyreg` module offers a way to define functions used while pickling
13
 
specific objects.  The :mod:`pickle` and :mod:`copy` modules use those functions
14
 
when pickling/copying those objects.  The module provides configuration
15
 
information about object constructors which are not classes.
16
 
Such constructors may be factory functions or class instances.
17
 
 
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
 
 
25
 
.. function:: pickle(type, function, constructor=None)
26
 
 
27
 
   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.
30
 
 
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
 
 
36
 
   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.
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(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...