Sub topic 10
Short-circuit evaluation and returned operands
This chapter assumes you know basic Python syntax, the built-in types int, float, str, bool, list and dict, and how truthiness works (empty and zero values are false, most other values are true).
The working model
Python's and and or do not always produce True or False. They return one of their operands. They also stop evaluating as soon as the result is known. This is called short-circuit evaluation.
a or bevaluatesa. Ifais truthy, the result isaandbis never evaluated. Otherwise the result isb.a and bevaluatesa. Ifais falsy, the result isaandbis never evaluated. Otherwise the result isb.
Returned operands in practice
name = ""
display = name or "anonymous"
print(display)
print(0 and 1 / 0)The first print shows anonymous, because the empty string is falsy and or returns the right operand. The second prints 0. The left operand is falsy, so and returns it and 1 / 0 never runs. Without short-circuiting, that line would raise ZeroDivisionError.
The result is the operand itself, not a converted boolean. Only not always returns a bool.
print("a" and "b")
print("" or [])
print(not "a")This prints b, [] and False.
Using short-circuiting as a guard
Put the cheap or safe check on the left, so it protects the right side.
items = []
if items and items[0] > 10:
print("big first item")
else:
print("nothing to check")When items is empty, items[0] is never evaluated, so no IndexError occurs.
Common errors
- Falsy values that are valid.
count or 10replaces a legitimate0with10. If0is a real value, test explicitly:10 if count is None else count. - Assuming a boolean result.
x = a and bmay store a string, list or number. Wrap inbool(...)when you need a real boolean. - Side effects on the right. In
check() or log(),log()may never run. Do not rely on a right-hand call happening. - Mixing
andandorwithout parentheses.andbinds tighter thanor, soa or b and cmeansa or (b and c).
Choosing a form
| Goal | Prefer |
|---|---|
| Default for empty or missing value | `value or default` |
| Default only for `None` | `default if value is None else value` |
| Guard a risky operation | `safe_check and risky_check` |
| Force a boolean | `bool(a and b)` |
Exercise
What do print(0 or "" or [] or "end") and print(1 and 2 and 0 and 3) print, and which operands are never evaluated?
Show answer
The first prints end: or skips the falsy 0, "" and [], then returns the last operand. The second prints 0: and returns the first falsy operand it meets, so 3 is never evaluated.
Exercise
A function sets retries = retries or 3. A caller passes retries=0 to disable retries. What goes wrong, and how do you fix it?
Show answer
0 is falsy, so or replaces it with 3 and retries stay enabled. Fix it with retries = 3 if retries is None else retries.