Question about exausted iterators

Christophe chris.cavalaria at free.fr
Thu May 18 10:45:15 EDT 2006


Diez B. Roggisch a écrit :
> Christophe wrote:
> 
> 
>>Fredrik Lundh a écrit :
>>
>>>Christophe wrote:
>>>
>>>
>>>>Because I'm still waiting for a valid answer to my question. The
>>>>answer "Because it has been coded like that" or is not a valid one.
>>>
>>>
>>>it's been coded like that because that's what the specification says:
>>>
>>>    http://www.python.org/dev/peps/pep-0234/
>>
>>I didn't though I had to mention that "Because the spec has been writen
>>like that" wasn't a valid answer either.
> 
> 
> The important thing is: it _is_ specified. And what about code like this:
> 
> 
> iterable = produce_some_iterable()
> 
> for item in iterable:
>     if some_condition(item)
>        break
>     do_something()
> 
> for item in iterable:
>     do_something_with_the_rest()
> 
> 
> If it weren't for StopIteration raised if the iterable was exhausted, you'd
> have to clutter that code with something like
> 
> try:
>    for item in iterable:
>       do_something_with_the_rest()
> except IteratorExhausted:
>    pass

It would be ugly but you could do that instead :

iterable = produce_some_iterable()

for item in iterable:
     if some_condition(item)
         break
     do_something()
else:
     iterable = []

for item in iterable:
     do_something_with_the_rest()

I'll admit that the else clause in for/while loops isn't the most common 
and so some people might be a little troubled by that.

There's also that :

iterable = produce_some_iterable()

for item in iterable:
     if some_condition(item)
         for item in iterable:
             do_something_with_the_rest()
         break
     do_something()

> What makes you say that this is better than the above? Just because _you_
> had some cornercases that others seems not to have (at least that
> frequently, I personally can't remember I've ever bitten by it) isn't a
> valid reason to _not_ do it as python does.

Maybe I've used more iterables than most of you. Maybe I've been doing 
that wrong. But I'd like to think that if I've made those mistakes, 
others will make it too and would benefit for some help in debugging 
that from the interpreter :)

> Besides that: it would be a major change of semantics of iterators that I
> seriously doubt it would make it into anything before P3K. So - somewhat a
> moot point to discuss here I'd say.

It wouldn't be such a big semantic change I think. You could add that 
easily[1] as deprecation warning at first and later on switch to a full 
blown error.

[1] "Easily" provided you can easily code what I ask itself ;)



More information about the Python-list mailing list