In Python, suppose I have a function f
that I want to pass around with some secondary arguments (assume for simplicity that it's just the first argument that remains variable).
What are the differences between doing it these two ways (if any)?
# Assume secondary_args and secondary_kwargs have been defined
import functools
g1 = functools.partial(f, *secondary_args, **secondary_kwargs)
g2 = lambda x: f(x, *secondary_args, **secondary_kwargs)
In the doc page for partial
, for example, there is this quote:
partial
objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up.
Will the lambda-method suffer from this if used to make a class method from arguments supplied to the class (either in the constructor or through a function later on)?
A lambda function has the same type as a standard function, so it will behave like an instance method.
The partial
object in your example can be called like this:
g1(x, y, z)
leading to this call (not valid Python syntax, but you get the idea):
f(*secondary_args, x, y, z, **secondary_kwargs)
The lambda only accepts a single argument and uses a different argument order. (Of course both of these differences can be overcome – I'm just answering what the differences between the two versions you gave are.)
Execution of the partial
object is slightly faster than execution of the equivalent lambda
.