I have a function
def x(whatever):
....
I want to assign
y = x(whatever)
So that I can pass around y to a wrapper which then calls the method that y refers to. The problem is that each type of function x can have variable arguments. Is it possible to do this in python, assigning y = x(whatever) and then pass around y as a parameter.
I tried y = x(whatever) and passed around y to the wrapper which then did
ret = y() # dict object is not callable
Thanks!
1 Answer 1
I think you are looking for functools.partial():
from functools import partial
y = partial(x, whatever)
When y is called, x(whatever) is called.
You can achieve the same with a lambda:
y = lambda: x(whatever)
but a partial() accepts additional arguments, which will be passed on to the wrapped callable.
2 Comments
partial fixes the argument to the value of whatever at that time. The callable returned by lambda uses the current value of whatever when it is called.x. You can use lambda x=x, w=whatever: x(w) to bind both to the lambda.