copyreg模块是否正确使用?

2024-04-27 16:20:59 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能告诉我为什么我的代码和函数序列化处理程序不能在下面工作吗?我对copyreg模块相当陌生,不清楚下面的代码是否正确编写。在

>>> import pickle, copyreg, types, marshal
>>> def average(*args):
    return sum(args) / len(args)

>>> average_dump = pickle.dumps(average)
>>> del average
>>> average = pickle.loads(average_dump)
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    average = pickle.loads(average_dump)
AttributeError: 'module' object has no attribute 'average'
>>> copyreg.pickle(types.CodeType,
           lambda code: (marshal.loads, (marshal.dumps(code),)),
           marshal.loads)
>>> up = lambda co, ns, de, cl: types.FunctionType(co, globals(), na, de, cl)
>>> copyreg.pickle(types.FunctionType,
           lambda function: (up, (function.__code__,
                      function.__name__,
                      function.__defaults__,
                      function.__closure__)),
           up)
>>> def average(*args):
    return sum(args) / len(args)

>>> average_dump
b'\x80\x03c__main__\naverage\nq\x00.'
>>> pickle.dumps(average)
b'\x80\x03c__main__\naverage\nq\x00.'
>>> del average; average = pickle.loads(average_dump)
Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    del average; average = pickle.loads(average_dump)
AttributeError: 'module' object has no attribute 'average'

我的期望是,如果注册的函数正常工作,那么代码和函数对象都将被序列化。如果这像预期的那样工作,取消拾取功能也将成为可能。在


编辑:按照this answer中的建议,将^{cd2>}子类化。似乎也无济于事。示例中的函数仍按名称序列化,而不是按copyreg模块中的处理程序进行序列化。在

^{pr2}$

Tags: 函数代码序列化argsfunctiondumppicklemarshal
2条回答

如果要序列化函数,请运行以下命令:

pip install dill

一旦完成,您就可以import dill并使用它来代替pickle模块。在

如果您正在运行Python3并希望轻松访问pip,请在Windows目录中放入一个名为pip.bat的批处理文件,并将以下行放入其中(假设您有一个代理干扰SSL):

^{pr2}$

函数不能按值pickle:

Note that functions (built-in and user-defined) are pickled by “fully qualified” name reference, not by value. This means that only the function name is pickled, along with the name of the module the function is defined in. Neither the function’s code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised.

http://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled

相关问题 更多 >