Nested generator caveat
dieter at handshake.de
Fri Jul 4 06:20:13 CEST 2008
I met the following surprising behaviour
>>> def gen0():
... for i in range(3):
... def gen1():
... yield i
... yield i, gen1()
>>> for i,g in gen0(): print i, g.next()
>>> for i,g in list(gen0()): print i, g.next()
If this is not a bug, it is at least quite confusing.
The apparent reason is that the free variables in
nested generator definitions are not bound (to a value) at invocation
time but only at access time.
Almost surely, the same applies to all locally defined functions
with free variables.
This would mean that locally defined functions with free
variables are very risky in generators.
More information about the Python-list