subtle side effect of generator/generator expression

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Oct 16 12:13:49 EDT 2005


On Sun, 16 Oct 2005 15:52:54 +0200, Fredrik Lundh wrote:

> bonono at gmail.com wrote:
> 
>> I initially thought that generator/generator expression is cool (sort of
>> like the lazy evaluation in Haskell) until I notice this side effect.
>>
>> >>>a=(x for x in range(2))
>> >>>list(a)
>> [1,2]
>> >>>list(a)
>> []
>>
>> Would this make generator/generator expression's usage pretty limited ?
> 
> nope.

In fairness, it is a pretty big Gotcha.



>> As when the program/system goes beyond a single module, this behaviour
>> can cause subtle bugs ?
> 
> sure, in the same way as
> 
>     >>> f = open(filename)
>     >>> f.read()
>     'hello world\n'
>     >>> f.read() # oops!
>     ''
> 
> causes subtle bugs (that is, almost never)

Are you saying that the bugs it causes aren't subtle? *wink*


-- 
Steven




More information about the Python-list mailing list