Python Mystery Theatre -- Episode 2: Así Fue

Raymond Hettinger vze4rx4y at verizon.net
Tue Jul 15 21:19:56 CEST 2003


[Chris Reedy]
> The fix is easy:
>
> flam = [lambda x, fn=f: fn(x) for f in funcs]
>
> which creates a new local binding which captures the correct value at
> each iteration. This is the kind of problem which makes me wonder
> whether we ought to re-think about binding of variables for loops.


Hmm, I put too many distractors in this one.
It's not about lambda and loops.  And though it touches
on nested scopes and list comprehensions, the crux is
just plain old bound / unbound variables inside a function
definition:

>>> base = hex
>>> def changebase(x):
...     return base(x)

>>> changebase(20)
'0x14'
>>> base = oct
>>> changebase(20)
'024'

It's a feature!



Raymond Hettinger




>






More information about the Python-list mailing list