if the else short form

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Wed Sep 29 14:58:16 CEST 2010


On 29 sep, 13:38, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> Tracubik <affdfsdfds... at b.com> writes:
>
> > button = gtk.Button(("False,", "True,")[fill==True])

(snip)

> BTW adding "==True" to a boolean value is redundant and can even break
> for logically true values that don't compare equal to True (such as the
> number 10 or the string "foo").

Note that if fill is actually an int outside the (0, 1) domain, it
will break too. The correct test would be:

 ("False,", "True,")[bool(fill)])


>>> ['a', 'b'][bool(10)]
'b'
>>> ['a', 'b'][bool('')]
'a'
>>> ['a', 'b'][bool("yes")]
'b'
>>> ['a', 'b'][bool([])]
'a'
>>> ['a', 'b'][bool([42, 24])]
'b'
>>> ['a', 'b'][bool(None)]
'a'
>>>



More information about the Python-list mailing list