【发布时间】:2015-09-04 13:53:49
【问题描述】:
我正在使用 marshal 模块序列化一些 Python 方法,并使用 types 模块 (Is there an easy way to pickle a python function (or otherwise serialize its code)?) 重构它们。我无法让它与可选的 kwargs 一起工作。例如
import marshal
import types
def test_func(x, y, kw='asdf'):
return x, y, kw
serialized_code_string = marshal.dumps(test_func.func_code)
# In real code there is a bunch of file I/O here instead
unserialized_code_string = marshal.load(code_string)
new_func = types.FunctionType(code, globals(), "deserialized_function")
当我运行 new_func(1,2) 时,我得到了 new_func() 正好需要 3 个参数(给定 2 个)的错误,即使 kwarg 是可选的。我认为问题出现在从 func_code 重建函数时,但我不知道如何解决这个问题。如果没有办法,我会对重建保留 kwarg 功能的函数的替代方法感兴趣。
【问题讨论】:
标签: python serialization deserialization marshalling unmarshalling