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