Odd closure issue for generators

Brian Quinlan brian at sweetapp.com
Thu Jun 4 23:40:07 CEST 2009


This is from Python built from the py3k branch:
 >>> c = (lambda : i for i in range(11, 16))
 >>> for q in c:
... 	print(q())
...
11
12
13
14
15
 >>> # This is expected
 >>> c = (lambda : i for i in range(11, 16))
 >>> d = list(c)
 >>> for q in d:
... 	print(q())
...
15
15
15
15
15
 >>> # I was very surprised

Looking at the implementation, I see why this happens:
 >>> c = (lambda : i for i in range(11, 16))
 >>> for q in c:
... 	print(id(q.__closure__[0]))
...
3847792
3847792
3847792
3847792
3847792
 >>> # The same closure is used by every lambda

But it seems very odd to me and it can lead to some problems that are a 
real pain in the ass to debug.

Cheers,
Brian



More information about the Python-list mailing list