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.

示例

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

  1. >>> import copyreg, copy, pickle
  2. >>> class C:
  3. ... def __init__(self, a):
  4. ... self.a = a
  5. ...
  6. >>> def pickle_c(c):
  7. ... print("pickling a C instance...")
  8. ... return C, (c.a,)
  9. ...
  10. >>> copyreg.pickle(C, pickle_c)
  11. >>> c = C(1)
  12. >>> d = copy.copy(c)
  13. pickling a C instance...
  14. >>> p = pickle.dumps(c)
  15. pickling a C instance...