Tim Peters <t...@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue38933>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to