Dangerous behavior of list(generator)

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Dec 13 15:18:47 EST 2009


On Sun, 13 Dec 2009 14:35:21 +0000, exarkun wrote:

>>StopIteration is intended to be used only within the .__next__ method of
>>iterators. The devs know that other 'off-label' use results in the
>>inconsistency you noted, but their and my view is 'don't do that'.
> 
> Which is unfortunate, because it's not that hard to get StopIteration
> without explicitly raising it yourself and this behavior makes it
> difficult to debug such situations.

I can't think of any way to get StopIteration without explicitly raising 
it yourself. It's not like built-ins or common data structures routinely 
raise StopIteration. I don't think I've *ever* seen a StopIteration that 
I didn't raise myself.


> What's with this view, exactly?  Is it just that it's hard to implement
> the more desirable behavior?

What is that "more desirable behaviour"? That StopIteration is used to 
signal that Python should stop iterating except when you want it to be 
ignored? Unfortunately, yes, it's quite hard to implement "do what the 
caller actually wants, not what he asked for" behaviour -- and even if it 
were possible, it goes against the grain of the Zen of Python.

If you've ever had to debug faulty "Do What I Mean" software, you'd see 
this as a good thing.



-- 
Steven



More information about the Python-list mailing list