【问题标题】:reconstruct python method with kwargs with marshal and types?用元帅和类型的kwargs重建python方法?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 2013-05-13
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多