Graceful handling of first line

Alex Martelli aleaxit at yahoo.com
Fri Oct 8 19:01:47 CEST 2004


Peter Otten <__peter__ at web.de> wrote:
   ...
> Looking at it from another angle, the initial for-loop ist just a peculiar
> way to deal with an empty iterable. So the best (i. e. clear, robust and
> general) approach is probably
> 
> items = iter(...)
> try:
>     first = items.next()
> except StopIteration:
>     # deal with empty iterator, e. g.:
>     raise ValueError("need at least one item")
> else:
>     # process remaining data

I think it can't be optimal, as coded, because it's more nested than it
needs to be (and "flat is better than nested"): since the exception
handler doesn't fall through, I would omit the try statement's else
clause and outdent the "process remaining data" part.  The else clause
would be needed if the except clause could fall through, though.


Alex



More information about the Python-list mailing list