How to stop iteration with __iter__() ?
John Machin
sjmachin at lexicon.net
Wed Aug 20 06:27:33 EDT 2008
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.
Cheers,
John
More information about the Python-list
mailing list