hynek / first

The function you always missed in Python: return the first true value of an iterable.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Replace the snark with an explanation of the alternatives

ncoghlan opened this issue · comments

If you're going to make the case for inclusion in itertools, it's better to include a "compare-and-contrast" with the existing alternatives than it is to include snarky comments (although the comment about 3.4 being a long way away is a valid one)

The main competitors are:

next(filter(None, seq))
next(filter(bool, seq))
next (x for x in seq if x)

All of these have several problems:

  1. They're not particularly obvious (especially the filter-with-no-predicate trick)
  2. The don't deal gracefully with the "empty iterable" case (they throw StopIteration)
  3. next() is only available on 2.6+

The genexp version also repeats the iteration variable name 3 times!

Oh, I wasn’t intending to be snarky in any way? And I intended to include this in a eventual request for inclusion.

I just didn’t think it’s necessary to do it in the package already, but you’re right because people pointed several alternatives to me already and all of them had some of the drawbacks. So maybe it’ll make it more compelling; I’ll look into it.

I realised point 2 is actually false, since next does accept a "default" parameter. However, it doesn't accept it in keyword form, so you can't be explicit about the meaning of the extra value, you have to just write something like:

next(filter(None, seq), None)
next(filter(bool, seq), None)
next ((x for x in seq if x), None)

Fixed in 8263b5c, thanks for your help!