[Python-Dev] iterator API in Py3.0

Terry Reedy tjreedy at udel.edu
Tue Mar 7 08:06:26 CET 2006


"Michael Hoffman" <hoffman at ebi.ac.uk> wrote in message 
news:Pine.LNX.4.64.0603061844140.21386 at qnzvnan.rov.np.hx...
> Another nice thing about having a next() built-in is that it makes
> getting the first item of a generator expression a lot more elegant,
> I think this:
> next(item for item in items if item > 3)
> is a lot clearer than this:
> (item for item in items if item > 3).next()
> or alternatives that would break this into multiple statements.
> [inspired by a recent python-list question]

Yuck.  This bug-prone one-liner was an answer to the question: how do I 
(the OP) get just the first item of items meeting a conditiion instead of 
all, as with filter, with a one-line expression instead of the obvious for 
loop.  Bad question; bad answer.  As I pointed out, this 'solution' raises 
StopIteration if there is no first valid item.  That in turn crashes the 
program unless one adds more lines to deal with the possible exception.  In 
the same post, I also suggested the OP first define his desired no-item 
behavior (not answered that I have seen).

To me, one-liner-itis can entertain, but also distract from complete, 
correct coding.

Terry Jan Reedy






More information about the Python-Dev mailing list