if the else short form

Antoon Pardon Antoon.Pardon at rece.vub.ac.be
Fri Oct 1 12:07:13 CEST 2010

On Wed, Sep 29, 2010 at 01:38:48PM +0200, Hrvoje Niksic wrote:
> Tracubik <affdfsdfdsfsd 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").

But leaving it out can also break things. If for some reason a variable
can have a boolean or a numeric value, that doesn't mean the coder wants
to treat 0 the same as False or any non-zero number the same as True.

Antoon Pardon

More information about the Python-list mailing list