Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #13109 > unrolled thread

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

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2011-09-10 22:01 -0600
Last post2011-09-10 22:01 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Idioms combining 'next(items)' and 'for item in items:' Ian Kelly <ian.g.kelly@gmail.com> - 2011-09-10 22:01 -0600

#13109 — Re: Idioms combining 'next(items)' and 'for item in items:'

FromIan Kelly <ian.g.kelly@gmail.com>
Date2011-09-10 22:01 -0600
SubjectRe: Idioms combining 'next(items)' and 'for item in items:'
Message-ID<mailman.969.1315713693.27778.python-list@python.org>
On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy <tjreedy@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web