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!

chepner
538k77 gold badges596 silver badges747 bronze badges
asked Mar 12, 2014 at 17:13

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.

answered Mar 12, 2014 at 17:14
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.