用带有元帅和类型的 kwargs 重建 python 方法?

reconstruct python method with kwargs with marshal and types?

我正在使用 marshal 模块序列化一些 Python 方法,并使用类型模块 (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 功能的函数的替代方法感兴趣。

经过更多搜索后,我发现了 dill 包,它允许您腌制比 cPickle 更多的东西(我使用 marshal 的原因)。当你直接重构一个序列化函数(不使用 func_code)时,你就避免了我遇到的这个关键字问题。