2

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

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

One other difference: the callable returned by 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.
@chepner: That is true; the same applies to x. You can use lambda x=x, w=whatever: x(w) to bind both to the lambda.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.