the PHP ternary operator equivalent on Python

David Wahler dwahler at gmail.com
Fri Nov 18 14:17:17 EST 2005


Daniel Crespo wrote:
> I would like to know how can I do the PHP ternary operator/statement
> (... ? ... : ...) in Python...
>
> I want to something like:
>
> a = {'Huge': (quantity>90) ? True : False}

Well, in your example the '>' operator already returns a boolean value
so you can just use it directly. Hoewver, I agree that there are
situations in which a ternary operator would be nice. Unfortunately,
Python doesn't support this directly; the closest approximation I've
found is:

>>> (value_if_false, value_if_true)[boolean_value]

This exploits the fact that False and True are converted to integers as
zero and one, respectively. The downside is that it's really ugly.
Also, it doesn't use minimal evaluation; in other words, if you try an
expression like:

>>> (None, func())[callable(func)]

You might think this would return the value of func() if it's callable,
and None otherwise. Unfortunately, func() is evaluated no matter what,
even if the condition is false.

Of course, you can always get around this by doing really cryptic stuff
with lambdas:

>>> (lambda: None, lambda: func())[callable(func)]()

... but by that point, you're better off just using an if/then/else.

-- David




More information about the Python-list mailing list