I've recently seen on this website that you can use the syntax
var = cond and value1 or value2
Instead of the conventional ternary syntax
var = value1 if cond else value2
I've since failed to find the user that said it or any articles online related to this topic, but after trying it in my code it seems to work as expected. Can someone please clarify if this syntax is actually valid or if this is just a fluke?
CodePudding user response:
is this a fluke?
No. As you can see, it works. It works because the return value of
a and b
is b
if True, or False
.
When to use
Now that we have the ternary, x = a and b or c
is as long or short as x = b if a else c
, and, I claim, harder to read. But this is shorter:
def x(mut = None):
mut = mut or {}
and simpler than the horrible:
def x(mut = None):
mut = mut if mut else {}
and still cleaner than:
def x(mut=None):
if not mut:
mut = {}
Which puts a couple of short indented lines at the beginning of a function just where my eye doesn't want them.
Note that in this case we are using the (parallel) fact that or
returns the first true element or False
.
CodePudding user response:
It doesn't always work. For example,
True and False or None
returns None, while
False if True else None
returns False.
I recommend reading the language spec, on boolean operators, which says:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression
s or 'foo'
yields the desired value.