9

Consider the following:

>>> a=2
>>> f=lambda x: x**a
>>> f(3)
9
>>> a=4
>>> f(3)
81

I would like for f not to change when a is changed. What is the nicest way to do this?

Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
asked Nov 27, 2013 at 13:46

2 Answers 2

13

You need to bind a to a keyword argument when defining the lambda:

f = lambda x, a=a: x**a

Now a is a local (bound as an argument) instead of a global name.

Demo:

>>> a = 2
>>> f = lambda x, a=a: x**a
>>> f(3)
9
>>> a = 4
>>> f(3)
9
answered Nov 27, 2013 at 13:47
Sign up to request clarification or add additional context in comments.

Comments

6

Another option is to create a closure:

>>> a=2
>>> f = (lambda a: lambda x: x**a)(a)
>>> f(3)
9
>>> a=4
>>> f(3)
9

This is especially useful when you have more than one argument:

 f = (lambda a, b, c: lambda x: a + b * c - x)(a, b, c)

or even

 f = (lambda a, b, c, **rest: lambda x: a + b * c - x)(**locals())
answered Nov 27, 2013 at 14:31

Comments

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.