Are the following uses of logical expressions Pythonic / pep8 compliant?
This:
x = a or b
instead of:
if not a:
x = b
else:
x = a
This:
x = a and b
instead of:
if not a:
x = a
else:
x = b
(The curve-ball?) This:
x = x or y
instead of:
if not x:
x = y
PEP 8 has nothing to do with the way you use your logical operators.
Assuming the motivation for using the logic operators instead of the conditionals is brevity, then it is better accomplished with the ternary operator:
x = a if a else b
instead of x = a or b
x = b if a else a
instead of x = a and b
x = x if x else y
or just if not x: x = y
instead of x = x or y
But nobody forbids you to use the other versions too. It's all a meter of personal opinion. The motivation behind introduction of the ternary operator was to avoid the error-prone attempts to achieve the same effect using the and
and or
operators (see PEP 308). They also enable fancy stuff in list comprehensions, and a few more things.
They are not introduced to replace complex if statements, but as a pythonic ternary operator: x if condition else y
.
Unlike C and Java, Python's logical operators don't return booleans. I can't imagine another use case for that language feature besides the one in your question, so unless the language designers are adding features thoughtlessly, it's Pythonic (except for #3).
There are many cases where the short-circuiting logical OR can be used to your advantage. Here's a simple one from the source code of Requests:
cookies = request.cookies or {}
It's immediately obvious what the outcome of this code should be, as it reads like a sentence. Now that's not to say that the verbose versions aren't readable:
cookies = request.cookies if request.cookies else {}
And:
cookies = {}
if request.cookies:
cookies = request.cookies
But they're redundant. Python uses the same syntax for dictionaries to prevent the same sort of redundancy:
d.get('key', 'fallback')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With