copyreg --- 注册配合 pickle 模块使用的函数

源代码: Lib/copyreg.py


copyreg 模块提供了可在封存特定对象时使用的一种定义函数方式。 picklecopy 模块会在封存/拷贝特定对象时使用这些函数。 此模块提供了非类对象构造器的相关配置信息。 这样的构造器可以是工厂函数或类实例。

copyreg.constructor(object)

object 声明为一个有效的构造器。 如果 object 是不可调用的(因而不是一个有效的构造器)则会引发 TypeError

copyreg.pickle(type, function, constructor_ob=None)

Declares that function should be used as a "reduction" function for objects of type type. function should return either a string or a tuple containing two or three elements. See the dispatch_table for more details on the interface of function.

The constructor_ob parameter is a legacy feature and is now ignored, but if passed it must be a callable.

Note that the dispatch_table attribute of a pickler object or subclass of pickle.Pickler can also be used for declaring reduction functions.

示例

以下示例将会显示如何注册一个封存函数,以及如何来使用它:

>>> import copyreg, copy, pickle
>>> class C:
...     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...