Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ternary order of operations

[on_true] if [expression] else [on_false]

If expression is False, does [on_true] still get evaluated?

Reason I ask is because I have a django ORM query as the [on_true] and will write this another way if it evaluates every time this line is run.

like image 787
Sam Creamer Avatar asked Apr 08 '19 20:04

Sam Creamer


1 Answers

After the truthiness of the condition is checked, only one side of the conditional expression will be evaluated. This is guaranteed and documented in the language reference: https://docs.python.org/3/reference/expressions.html#conditional-expressions

You can put whatever garbage expression there to convince yourself of the fact:

>>> wtf.errorerror - error + 1/0 if False else "potato"
'potato'
like image 54
wim Avatar answered Nov 13 '22 07:11

wim