1

Suppose I have a function def foo(A, B).

Now I have another function bar(func), where func is a function that takes only one variable. I want to pass in foo as func, but with the second variable B always fixed to 300. How can I do that?

1
  • Search for "partial application". Commented Feb 21, 2013 at 4:20

2 Answers 2

3

You use lambda:

bar(lambda x: foo(x,300))

basically,

func = lambda x: x*x

is more or less equivalent to:

def func(x):
   return x*x

So in this case, we use something that's more or less equivalent to:

def new_func(x):
    return foo(x,300)

and then we pass the equivalent of new_func to bar.

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

Comments

2

Lambda is easiest, but you could also use functools.partial for more complex cases:

import functools

bar(functools.partial(foo, B=300))

Comments

Your Answer

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.