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...
...so you just need to set
var
in the calling scope before calling yourlambda
, although this is more commonly used in cases wherey
is 'constant'.A disassembly of that function reveals...
If you want to bind
y
to an object at the point of defining thelambda
(i.e. creating a closure), it's common to see this idiom......whereby changes to
y
after defining thelambda
have no effect.A disassembly of that function reveals...
f = functools.partial(lambda var, x: x + var.x - var.y, var)
will give you a function (f
) of one parameter (x
) withvar
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:
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:
Lambda or regular function, the only way you can change a variable in the scope of a function is via an argument.