[issue38933] unusual behaviour on list of dependable lambdas
Tim Peters
report at bugs.python.org
Thu Nov 28 14:04:45 EST 2019
Tim Peters <tim at python.org> added the comment:
This behavior is intended and expected, so I'm closing this.
As has been explained, in any kind of function (whether 'lambda' or 'def'), a non-local variable name resolves to its value at the time the function is evaluated, not the value it _had_ at the time the function was defined.
If you need to use bindings in effect at the time the function is defined, then you need to do something to force that to happen. A common way is to abuse Python's default-argument mechanism to initialize a local argument to the value of a non-local variable at function definition time. In practice, e.g., this means changing the
lambda a:
in your first example to
lambda a, i=i:
Then, when the lambda is defined ('lambda' and 'def' are executable statements in Python! not just declarations), the then-current binding of non-local variable 'i' is captured and saved away as the default value of the local argument name 'i'.
----------
nosy: +tim.peters
resolution: -> not a bug
stage: -> resolved
status: open -> closed
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38933>
_______________________________________
More information about the Python-bugs-list
mailing list