Idioms combining 'next(items)' and 'for item in items:'

Ian Kelly ian.g.kelly at gmail.com
Sun Sep 11 00:01:02 EDT 2011


On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> The statement containing the explicit next(items) call can optionally be
> wrapped to explicitly handle the case of an empty iterable in whatever
> manner is desired.
>
> try:
>    <set up with next(items)>
> except StopIteration:
>    raise ValueError("iterable cannot be empty")

The only time that's optional is when you're writing an iterator and
the try-except would end up looking like this:

try:
    # do stuff with next(items)
except StopIteration:
    raise StopIteration

And even then, it's probably a good idea to clearly document that
you're allowing a StopIteration from one iterator to propagate up as a
StopIteration for another.

Apart from that case, whenever you call next() you should always be
prepared to catch a StopIteration.  Letting a StopIteration propagate
up the stack to parts unknown is bad juju because it's a flow control
exception, not an error-signaling exception.  If it happens to
propagate up to another for loop, then it will break out of the for
loop, and the exception will simply be swallowed.

Cheers,
Ian



More information about the Python-list mailing list