lambda - Assign variable to local scope of function in Python -
i'd assign variable scope of lambda called several times. each time new instance of variable. how do that?
f = lambda x: x + var.x - var.y # code needed here prepare f new var result = f(10) in case it's var i'd replace each invocation without making second argument.
variables undefined in scope of lambda resolved calling scope @ point it's called.
a simpler example...
>>> y = 1 >>> f = lambda x: x + y >>> f(1) 2 >>> y = 2 >>> f(1) 3 ...so need set var in calling scope before calling lambda, although more commonly used in cases y 'constant'.
a disassembly of 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 want bind y object @ point of defining lambda (i.e. creating closure), it's common see idiom...
>>> y = 1 >>> f = lambda x, y=y: x + y >>> f(1) 2 >>> y = 2 >>> f(1) 2 ...whereby changes y after defining lambda have no effect.
a disassembly of function reveals...
>>> import dis >>> dis.dis(f) 1 0 load_fast 0 (x) 3 load_fast 1 (y) 6 binary_add 7 return_value
Comments
Post a Comment