How to stop iteration with __iter__() ?

MRAB google at mrabarnett.plus.com
Wed Aug 20 09:16:17 EDT 2008


On Aug 20, 11:27 am, John Machin <sjmac... at lexicon.net> wrote:
> On Aug 20, 7:56 pm, MRAB <goo... at mrabarnett.plus.com> wrote:
>
>
>
> > On Aug 20, 12:11 am, John Machin <sjmac... at lexicon.net> wrote:
>
> > > or, perhaps, for completeness/paranoia/whatever:
>
> > > it = iter(iterable)
> > > try:
> > >    headings = it.next() # < 2.5
> > > except StopIteration:
> > >    # code to handle empty <iterable>
> > > for item etc etc
>
> > I think it needs to be:
>
> > it = iter(iterable)
> > try:
> >     headings = it.next() # < 2.5
> > except StopIteration:
> >     # code to handle empty <iterable>
> > else:
> >     for item etc etc
>
> > because you don't want to iterate over the remainder if it has already
> > stopped yielding! :-)
>
> If it has stopped yielding, the remainder is nothing/null/empty, isn't
> it?
> In any case "code to handle empty <iterable>" is likely to end with a
> raise or return statement.
>
So it's defined behaviour that an exhausted iterable will always raise
StopIteration no matter how many times it's asked for the next value?



More information about the Python-list mailing list