简体   繁体   English

酸洗 Python 3 中的关键字参数

[英]Pickling keyword arguments in Python 3

Python 2 doc says: Python 2文档说:

Deprecated since version 2.3: Use function(*args, **keywords) instead of apply(function, args, keywords) (see Unpacking Argument Lists). 2.3 版后已弃用:使用 function(*args, **keywords) 而不是 apply(function, args, keyword)(请参阅解包参数列表)。

Pickle module requires the following syntax to define __reduce__ method to dump an object: Pickle模块需要以下语法来定义__reduce__方法来转储对象:

def __reduce__():
     return (<A callable object>, <A tuple of arguments for the callable object.>) 

(I know that the length of tuple returned from __reduce__ can be >2 but needs to be <=5. Considering the case of length 2 in the context of current question.) (我知道从__reduce__返回的元__reduce__可以 >2,但需要 <=5。在当前问题的上下文中考虑长度 2 的情况。)

This means it is not possible to pass keyword arguments to the callable object.这意味着无法将关键字参数传递给可调用对象。 In Python 2, I have the following work-around:在 Python 2 中,我有以下解决方法:

def __reduce__():
     return (apply, (<A callable object>, ((<args>,), <kwargs>))

However, builtins.apply has been removed in Python 3 .但是, builtins.apply已在Python 3 中删除。 Is there any other alternative to implementing my own version of builtins.apply in Python 3 ?Python 3 中实现我自己的builtins.apply版本还有其他选择吗?

You can use functools.partial for this:您可以为此使用functools.partial

from functools import partial

def __reduce__():
     return (partial(<A callable object>, <kwargs>), ())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM