if the else short form

Alex Willmer alex at moreati.org.uk
Wed Sep 29 14:59:51 CEST 2010

On Sep 29, 12:38 pm, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> Tracubik <affdfsdfds... at b.com> writes:
> > Hi all,
> > I'm studying PyGTK tutorial and i've found this strange form:
> > button = gtk.Button(("False,", "True,")[fill==True])
> > the label of button is True if fill==True, is False otherwise.
> The tutorial likely predates if/else expression syntax introduced in
> 2.5, which would be spelled as:
> button = gtk.Button("True" if fill else "False")
> 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").

Totally agreed with one nit. If one chooses to fake

x = true_val if expr else false_val

prior to Python 2.5, with

x = (false_val, true_val)[expr]

then one should ensure that expr evaluates to either 0, 1 or a bool.
If expr evaluates to "fred" or 42 a TypeError or IndexError will
occur. So better to use (in original line)

 button = gtk.Button(("False,", "True,")[bool(fill)])

but still best for readability, to use a full if-else block

More information about the Python-list mailing list