the PHP ternary operator equivalent on Python

bonono at bonono at
Sat Nov 19 00:41:23 CET 2005

The cleanest(IMO) is this :

a = (predicate and [if_true_expr] or [if_false_expr])[0]

This would give you the necessary "short circuit" behaviour no matter

a = predicate and if_true_expr or if_false_expr

works most of the time but should if_true_expr turns out to be 0 or
something like that(python False equvialent), the if_false_expr will
still be executed, that becomes a logic error. an example :
a = int_str is None and None or int(int_str)

a = [if_false_expr, if_true_expr][predicate]

This doesn't have the "short circuit" feature and the order is
reversed(harder to read for people familiar with ternary operator).
Cannot be used in some case. like this :

a = [0, int(int_str)][int_str is not None]

here int(int_str) may cause exception if None is a valid value.

The lambda form suggested by others is another variant of the first one
above where you get the short circuit feature but too complex to read.

I don't understand why people are so aganst ternary operator. It is a
must for list comprehension/generator expression(and I believe the
reason it has finally been approved), if/else block or try/except just
don't work in these situations.

Daniel Crespo wrote:
> Hi!
> 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}
> Any suggestions?
> Thanks
> Daniel

More information about the Python-list mailing list