Nested generator caveat

Dieter Maurer dieter at
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,
0 0
1 1
2 2
>>> for i,g in list(gen0()): print i,
0 2
1 2
2 2

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 mailing list