If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Absolutely, and it is incredibly easy to understand.
Yes. From the grammar file:
The part of interest is:
So, a ternary conditional operation is of the form:
expression3
will be lazily evaluated (that is, evaluated only ifexpression2
is false in a boolean context). And because of the recursive definition, you can chain them indefinitely (though it may considered bad style.)A note on usage:
Note that every
if
must be followed with anelse
. People learning list comprehensions and generator expressions may find this to be a difficult lesson to learn - the following will not work, as Python expects a third expression for an else:which raises a
SyntaxError: invalid syntax
. So the above is either an incomplete piece of logic (perhaps the user expects a no-op in the false condition) or what may be intended is to use expression2 as a filter - notes that the following is legal Python:expression2
works as a filter for the list comprehension, and is not a ternary conditional operator.Alternative syntax for a more narrow case:
You may find it somewhat painful to write the following:
expression1
will have to be evaluated twice with the above usage. It can limit redundancy if it is simply a local variable. However, a common and performant Pythonic idiom for this use-case is to useor
's shortcutting behavior:which is equivalent in semantics. Note that some style-guides may limit this usage on the grounds of clarity - it does pack a lot of meaning into very little syntax.
Syntax: The Ternary operator will be given as:
e.g
if variable is defined and you want to check if it has value you can just
a or b
will output
More a tip than an answer (don't need to repeat the obvious for the hundreth time), but I sometimes use it as a oneliner shortcut in such constructs:
, becomes:
Some (many :) may frown upon it as unpythonic (even, ruby-ish :), but I personally find it more natural - i.e. how you'd express it normally, plus a bit more visually appealing in large blocks of code.
Just memorize this pyramid if you have trouble remembering: