Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Python
the PHP ternary operator equivalent on Python
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="bonono, post: 1849314"] 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 what. 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. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
the PHP ternary operator equivalent on Python
Top