[Python-ideas] Break the dominance of boolean values in boolean context

Terry Reedy tjreedy at udel.edu
Thu Sep 15 21:40:02 CEST 2011

On 9/15/2011 8:40 AM, Sven Marnach wrote:
> Terry Reedy schrieb am Mi, 14. Sep 2011, um 22:52:47 -0400:
>> That is what itertool is designed for. I believe
>> chain(dropwhile(...), [default]) will add a default.
> ... unless the default is falsy.

Out of context nonsense. In

    from itertools import dropwhile
    def _not(x): return not x

    def first(iterable):
        return next(dropwhile(_not, iterable))

replacing 'dropwhile(_not, iterable)' with 
will *always* return default if dropwhile is empty
*and* guarantee that there is a first to be returned
instead of raising StopIteration, which should otherwise be trapped, as 
StopIteration should only be passed out by iterators.
Actually, I would probably not bother with chain and instead write

def first(iterable,default):
     return next(dropwhile(_not, iterable))
   except StopIteration:
     return default

Terry Jan Reedy

More information about the Python-ideas mailing list