Graceful handling of first line

Peter Otten __peter__ at web.de
Fri Oct 8 09:09:13 EDT 2004


Gerrit wrote:

>>>> first = lines.next()

[as opposed to 'for first in lines: break']

> Would hurt less feeling I presume.
 
>>> iter("").next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration

I feel a little uneasy with that ...unless I'm sure I want to deal with the
StopIteration elsewhere. 
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
    
part of which is indeed your suggestion.

Peter





More information about the Python-list mailing list