【发布时间】:2019-02-21 08:17:34
【问题描述】:
Python 2 doc 说:
2.3 版后已弃用:改用 function(*args, **keywords) 的 apply(function, args, keywords)(请参阅拆包参数列表)。
Pickle 模块需要以下语法来定义__reduce__ 方法来转储对象:
def __reduce__():
return (<A callable object>, <A tuple of arguments for the callable object.>)
(我知道从 这意味着无法将关键字参数传递给可调用对象。在 Python 2 中,我有以下解决方法: 但是,__reduce__ 返回的元组长度可以>2,但需要
def __reduce__():
return (apply, (<A callable object>, ((<args>,), <kwargs>))
builtins.apply 已在 Python 3 中删除。在 Python 3 中实现我自己的builtins.apply 版本还有其他替代方法吗?
【问题讨论】:
-
你试过*吗?
return the_callable(*args, **kwargs)参考:portingguide.readthedocs.io/en/latest/… -
def apply(func, args, kwargs): return func(*args, **kwargs)把它放在utils.py中。或者,只需包装您的函数,以便它可以根据需要获取 te 参数:def wrapper(func): return lambda args, kwargs: func(*args, **kwargs)然后而不是传递可调用的 passwrapper(callable)。 -
@ferrix 执行
return the_callable(*args, **kwargs)将调用将失败的函数,因为 reduce 返回类型应为(callable, args)。 -
啊,对,我的错。然后@GiacomoAlzetta 的解决方案将起作用。
-
@GiacomoAlzetta 定义应用在
utils.py或其他地方解决了这个问题。但是,我想知道是否存在任何其他解决方法 - 无论是通过像six这样的第三方库。另外,请您详细说明包装方法;可能有一个工作示例作为答案而不是 cmets?
标签: python python-3.x python-2.7 pickle