[英]python 3.x: bind arguments to given values
In Python, for a simple function foo(x, y)
there are at least 3 ways that i know to bind the argument y
to some value 在Python中,对于一个简单的函数
foo(x, y)
,我知道至少有3种方法将y
绑定到某个值
# defining a nested function:
def foobar(x):
return foo(x, y=yval)
# using lambda
foobar = lambda x: foo(x, y=yval)
# using functools
from functools import partial
foobar = partial(foo, y=yval)
while i am doubtful that the list above is exhaustive, i also wonder which one should i go with? 尽管我怀疑上面的列表是否详尽无遗,但我也想知道应该选择哪一个? are they all equivalent in terms of performance, safety and namespace handling?
它们在性能,安全性和名称空间处理方面是否都等效? or are there extra overheads and caveats with each method?
还是每种方法都有额外的开销和警告? why should
functools
define partial
when the other methods are already there? 当其他方法已经存在时,为什么
functools
应该定义partial
的?
No, they're not all equivalent -- in particular, a lambda
cannot be pickled and a functools.partial
can, IIRC, be pickled only in recent Python versions (I can't find which exact version in the docs; it doesn't work in 2.6, but it does in 3.1). 不,它们并不完全相同-特别是不能腌制
lambda
和functools.partial
(IIRC)只能在最近的Python版本中腌制(我无法在文档中找到哪个确切版本;它没有不能在2.6中使用,但在3.1中可以使用。 Neither can functions defined inside of other functions (neither in 2.6 nor 3.1). 不能在其他函数中定义函数(在2.6和3.1中都不能定义)。
The reason for partial
's appearance in the library is that it gives you an explicit idiom to partially apply a function inline. 在库中出现
partial
的原因是,它为您提供了一个明确的习惯用法,可以部分地内联应用函数。 A definition ( def
) cannot appear in the middle of an expression such as 定义(
def
)不能出现在表达式的中间,例如
map(partial(foo, y=yval), xs)
Also, from a definition or lambda
, it's not immediately clear that partial application is what's going on, since you can put an arbitrary expression in a lambda
and arbitrary statements in a definition. 另外,从定义或
lambda
来看,尚不完全清楚部分应用是怎么回事,因为您可以在lambda
放置任意表达式,在定义中放置任意语句。
I suggest you go with partial
unless you have a reason not to use it. 我建议您选择
partial
除非您有理由不使用它。
[And indeed, the list is not exhaustive. [的确,清单并不详尽。 The first alternative that comes to mind is a callable object:
我想到的第一个选择是可调用对象:
class foobar:
def __init__(self, yval):
self.__yval = yval
def __call__(self, x):
return foo(x, self.__yval)
but those are heavy-weights for such a simple problem.] 但是对于这样一个简单的问题,这些都是沉重的负担。]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.