I'd like to assign a variable to the scope of a lambda that is called several times. Each time with a new instance of the variable. How do I do that?
f = lambda x: x + var.x - var.y
# Code needed here to prepare f with a new var
result = f(10)
In this case it's var I'd like to replace for each invocation without making it a second argument.
Variables undefined in the scope of a lambda
are resolved from the calling scope at the point where it's called.
A slightly simpler example...
>>> y = 1
>>> f = lambda x: x + y
>>> f(1)
2
>>> y = 2
>>> f(1)
3
...so you just need to set var
in the calling scope before calling your lambda
, although this is more commonly used in cases where y
is 'constant'.
A disassembly of that function reveals...
>>> import dis
>>> dis.dis(f)
1 0 LOAD_FAST 0 (x)
3 LOAD_GLOBAL 0 (y)
6 BINARY_ADD
7 RETURN_VALUE
If you want to bind y
to an object at the point of defining the lambda
(i.e. creating a closure), it's common to see this idiom...
>>> y = 1
>>> f = lambda x, y=y: x + y
>>> f(1)
2
>>> y = 2
>>> f(1)
2
...whereby changes to y
after defining the lambda
have no effect.
A disassembly of that function reveals...
>>> import dis
>>> dis.dis(f)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 BINARY_ADD
7 RETURN_VALUE
f = functools.partial(lambda var, x: x + var.x - var.y, var)
will give you a function (f
) of one parameter (x
) with var
fixed at the value it was at the point of definition.
You cannot use the assignment statement in lambda expression, so you'll have to use a regular named function:
def f(x):
global var
var = x
Note the use of the "global" keyword. Without it, Python will assume you want to create a new "var" variable in the local scope of the function.
Make it another parameter:
f = lambda x,var: x + var.x - var.y
result = f(10, var)
Lambda or regular function, the only way you can change a variable in the scope of a function is via an argument.