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
# 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?
No, they’re not all equivalent — in particular, a
lambdacannot be pickled and afunctools.partialcan, 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). Neither can functions defined inside of other functions (neither in 2.6 nor 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. A definition (def) cannot appear in the middle of an expression such asAlso, 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 alambdaand arbitrary statements in a definition.I suggest you go with
partialunless you have a reason not to use it.[And indeed, the list is not exhaustive. The first alternative that comes to mind is a callable object:
but those are heavy-weights for such a simple problem.]