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

Georg Brandl g.brandl at gmx.net
Fri Sep 16 06:15:19 CEST 2011


Am 15.09.2011 21:40, schrieb Terry Reedy:
> 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 
> 'chain(dropwhile(_not,iterable),[default]'
> 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):
>    try:
>      return next(dropwhile(_not, iterable))
>    except StopIteration:
>      return default

This is spelled

    next(dropwhile(_not, iterable), default)

Georg




More information about the Python-ideas mailing list