#11481: update copyreg docs and add example.

This commit is contained in:
Ezio Melotti 2012-11-08 11:04:57 +02:00
parent 44dbd07a51
commit 78b18d4b4c
2 changed files with 28 additions and 5 deletions

View File

@ -67,8 +67,8 @@ of lists by assigning a slice of the entire list, for example,
Classes can use the same interfaces to control copying that they use to control Classes can use the same interfaces to control copying that they use to control
pickling. See the description of module :mod:`pickle` for information on these pickling. See the description of module :mod:`pickle` for information on these
methods. The :mod:`copy` module does not use the :mod:`copyreg` registration methods. In fact, :mod:`copy` module uses the registered pickle functions from
module. :mod:`copyreg` module.
.. index:: .. index::
single: __copy__() (copy protocol) single: __copy__() (copy protocol)

View File

@ -9,9 +9,10 @@
module: pickle module: pickle
module: copy module: copy
The :mod:`copyreg` module provides support for the :mod:`pickle` module. The The :mod:`copyreg` module offers a way to define fuctions used while pickling
:mod:`copy` module is likely to use this in the future as well. It provides specific objects. The :mod:`pickle` and :mod:`copy` modules use those functions
configuration information about object constructors which are not classes. when pickling/copying those objects. The module provides configuration
information about object constructors which are not classes.
Such constructors may be factory functions or class instances. Such constructors may be factory functions or class instances.
@ -35,3 +36,25 @@ Such constructors may be factory functions or class instances.
See the :mod:`pickle` module for more details on the interface expected of See the :mod:`pickle` module for more details on the interface expected of
*function* and *constructor*. *function* and *constructor*.
Example
-------
The example below would like to show how to register a pickle function and how
it will be used:
>>> import copyreg, copy, pickle
>>> class C(object):
... def __init__(self, a):
... self.a = a
...
>>> def pickle_c(c):
... print("pickling a C instance...")
... return C, (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...