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?
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())