Python Mystery Theatre -- Episode 2: Así Fue

Raymond Hettinger vze4rx4y at
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

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

>>> changebase(20)
>>> base = oct
>>> changebase(20)

It's a feature!

Raymond Hettinger


More information about the Python-list mailing list