waka-waka-waka
waka-waka-waka

Reputation: 1045

python function with arguments assigned to a variable

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!

Upvotes: 2

Views: 1474

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121366

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.

Upvotes: 6

Related Questions