Sub topic 6
Short-circuiting and the values and/or return
This chapter assumes you know how truthiness works (which values count as true or false) and how and, or, and not combine conditions. Here you will see that and and or return one of their operands, not always True or False, and that they sometimes skip evaluating the right-hand side.
What and and or actually return
and and or do not convert their result to bool. They return whichever operand decided the outcome.
a or breturnsaifais truthy. Otherwise it returnsb.a and breturnsaifais falsy. Otherwise it returnsb.
print(0 or "default") # default
print("a" and "b") # b
print([] and 1) # []
name = ""
print(name or "anonymous") # anonymousIn 0 or "default", the left operand is falsy, so or moves on and returns the right operand. In [] and 1, the left operand is falsy, so and stops and returns [] itself.
In an if statement the returned value is tested for truthiness, so you rarely notice the difference. It matters when you store the result in a variable or print it.
Short-circuit evaluation
Python evaluates the right operand only when the left one has not already settled the result.
andstops at the first falsy operand.orstops at the first truthy operand.
The function below prints a message each time it runs, which makes skipped evaluations visible.
def check(label, value):
print("checking", label)
return value
print(check("A", False) and check("B", True))
print(check("C", True) or check("D", False))The output is:
checking A
False
checking C
TrueB and D never run. If the right-hand side has side effects (printing, writing, calling an API), those side effects are skipped too.
For and the flow is the mirror image. A falsy a is returned immediately, and a truthy a leads to evaluating and returning b.
Practical uses
Guarding an access
Because the right side is skipped, you can put a safety check on the left.
config = {}
print(config and config["debug"]) # {}
config = {"debug": True}
print(config and config["debug"]) # TrueWith an empty dict, config["debug"] would raise KeyError. Short-circuiting prevents that evaluation. Note that the result is {}, not False. That is the returned-operand rule at work.
Fallback values
The or idiom supplies a default when the left value is falsy:
username = ""
display = username or "anonymous"
print(display) # anonymousChains
Chains return the first operand that decides the result. or returns the first truthy value, or the last operand if none are truthy. and returns the first falsy value, or the last operand if all are truthy.
print(None or 0 or "" or "last") # last
print(1 and "x" and []) # []
print(None or 0 or "") # (empty string)The falsy-fallback trap
x or default replaces every falsy value, not only missing ones. A legitimate 0 or empty string gets overwritten.
port = 0
print(port or 8080) # 8080, probably not what you wanted
print(port if port is not None else 8080) # 0When 0, "", or [] are valid inputs, test for None explicitly. Use or only when every falsy value really should be replaced.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Expecting `a and b` to return `True` or `False` | You get `a` or `b` as they are | Wrap in `bool(...)` if you need a real boolean |
| Putting a required side effect on the right side | It is silently skipped | Call it on its own line |
| Using `or` for defaults when `0` is valid | Valid `0` is replaced | Use `if x is None` |
| Writing `x == 1 or 2` | Always truthy, because `2` is truthy | Write `x == 1 or x == 2`, or `x in (1, 2)` |
Exercise
What does each expression print? (a) print("" or [] or "ok") (b) print(3 and 0 and 5) (c) print(check("X", 1) or check("Y", 2)), where check prints "checking <label>" and returns its value.
Show answer
(a) ok, because "" and [] are falsy and the last operand is returned. (b) 0, because 0 is the first falsy operand and evaluation stops there. (c) It prints "checking X" and then 1. check("Y", 2) is never called, because 1 is truthy and settles the or.
Exercise
Rewrite timeout = settings_timeout or 30 so that a configured timeout of 0 is kept and only None falls back to 30.
Show answer
timeout = settingstimeout if settingstimeout is not None else 30