Conditional Expressions in Python

Historically, python didn’t have a special operator for a conditional expressions. The (condition ? true-value : false-value) expression is concise and convenient, and has been missed for years by many python programmers, especially those coming from programming backgrounds that support the conditional expression such as C/C++, Java, Perl, PHP, and friends.

Starting with python 2.5, python programmers worldwide rejoice as now we can compress the the following if-else statement:

into the following one-line expression:

But what’s with the ugly syntax? Seriously? Why would the condition go in the middle whereas in all other languages the condition always go in the front?

The answer to the ugliness question is given in PEP 308:

The decision was checked by applying the new syntax to the modules in the standard library and seeing how the resulting code read. In many cases where a conditional expression is used, one value seems to be the ‘common case’ and one value is an ‘exceptional case’, used only on rarer occasions when the condition isn’t met.

Now, how many python programmers in the world are working on the python’s standard library? And the rest of us have to endure this ugliness … NO!

Not all hope is lost. Even without explicit support for a conditional expression, python’s awesomeness comes to the rescue:

Now that is just plain elegance and beauty. And guess what? It works even in python prior to 2.5 so you don’t need worry about your code breaking on legacy systems (that is, if you’re unfortunate enough to work with python prior to 2.6).

As Daniel pointed out in the comments, there is a gotcha to this elegance: the true_value must not evaluate to False. More specifically, the expression will always return the false_value if the true_value is one of:

  • None
  • False
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, ”, (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

Which syntax of the three options do you prefer? Why? Share your insights in the comments.

2 thoughts on “Conditional Expressions in Python

  1. Daniel Sokolowski

    Innovative and thanks for sharing Tony, I still prefer the formal way just because I am used to it now and the ‘and’ reads odd to me; I do agree they should have stuck to the more established condition ? true-value : false-value order.

    I thought about it longer and here is a Pythons comparison gotcha wrecking your clean approach:

    >>> True and 0 or ‘Failed’
    ‘Failed’
    >>> 0 if True else ‘Failed’
    0

    We might not like PHP but we could use their identical ‘===’ comparisons – but that is another discussion all together :).

Leave a Reply

Your email address will not be published. Required fields are marked *