11.3. copy_reg — Register pickle support functions¶
Note
The copy_reg module has been renamed to copyreg in Python 3.
The 2to3 tool will automatically adapt imports when converting your
sources to Python 3.
The copy_reg module offers a way to define functions used while pickling
specific objects. The pickle, cPickle, and copy modules
use those functions 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.
-
copy_reg.constructor(object)¶ Déclare object comme étant un constructeur valide. Si object n’est pas appelable (et n’est donc pas un constructeur valide), l’erreur
TypeErrorest levée.
-
copy_reg.pickle(type, function[, constructor])¶ Declares that function should be used as a « reduction » function for objects of type type; type must not be a « classic » class object. (Classic classes are handled differently; see the documentation for the
picklemodule for details.) function should return either a string or a tuple containing two or three elements.Le paramètre optionnel contructor, s’il est donné, est un objet appelable qui peux être utilisé pour reconstruire l’objet lorsqu’il est appelé avec un tuple d’arguments retournés par function durant la sérialisation avec pickle. Une exception
TypeErrorsera levée si object est une classe ou si constructor n’est pas appelable.See the
picklemodule for more details on the interface expected of function and constructor.
11.3.1. Exemple¶
L’exemple si-dessous essaye de démontrer comment enregistrer une fonction pickle et comment elle sera utilisée :
>>> import copy_reg, 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,)
...
>>> copy_reg.pickle(C, pickle_c)
>>> c = C(1)
>>> d = copy.copy(c)
pickling a C instance...
>>> p = pickle.dumps(c)
pickling a C instance...
