Sub topic 8
Short-circuit evaluation
This chapter assumes you can write an if/else statement and know which values are truthy and falsy. It also assumes you know and, or, and not. Here you will learn that Python does not always evaluate every part of a condition, and how to use that on purpose.
What short-circuit evaluation means
Python evaluates and and or from left to right and stops as soon as the result is known.
- In
A and B, ifAis falsy, the whole expression cannot be truthy. Python skipsB. - In
A or B, ifAis truthy, the whole expression is already decided. Python skipsB.
You can see this with a helper function that announces when it runs.
def check(name, value):
print('checking', name)
return value
if check('a', False) and check('b', True):
print('both true')
print('---')
if check('c', True) or check('d', True):
print('at least one true')The output is:
checking a
---
checking c
at least one truecheck('b', True) and check('d', True) never run. Their function bodies are skipped entirely, so any side effects inside them (printing, writing a file, a network call) do not happen either.
The result is an operand, not always True or False
Short-circuiting has a second consequence. and and or return one of their operands, not a new boolean. They return whichever operand decided the outcome.
print(0 and 5)
print(3 and 5)
print('' or 'default')
print('hi' or 'default')
print([] or None)
print(not [])The output is:
0
5
default
hi
None
TrueThe rules are:
A and BreturnsAifAis falsy. Otherwise it returnsB.A or BreturnsAifAis truthy. Otherwise it returnsB.not Ais the exception. It always returnsTrueorFalse.
An if statement only asks whether the result is truthy, so the difference rarely matters in conditions. It matters when you use the result as a value, as in the next sections.
With more than two operands the same rules apply. a or b or c returns the first truthy operand, or the last operand if none is truthy. a and b and c returns the first falsy operand, or the last operand if all are truthy.
Using order as a safety check
The most common use is protecting an expression that would fail if an earlier check did not pass. Put the cheap, safe test on the left and the risky test on the right.
items = []
if items and items[0] > 10:
print('first item is large')
else:
print('nothing to check')When items is empty, items is falsy, so items[0] is never evaluated and no IndexError is raised. Swap the order and the same code crashes on an empty list.
Here are more guards of the same kind:
total = 100
count = 0
if count != 0 and total / count > 20:
print('high average')
else:
print('no data or low average')
user = None
if user is not None and user.get('active'):
print('active user')
else:
print('no active user')The first guard avoids a ZeroDivisionError. The second avoids an AttributeError, because None has no .get method.
Ordering by cost
When neither operand is a safety guard, you can still choose an order for speed. Python stops early, so put the check that is cheap or most likely to decide the result first.
def expensive_check(text):
print('running expensive check')
return 'error' in text.lower()
line = ''
if line and expensive_check(line):
print('found an error line')
else:
print('skipped')The empty string is falsy, so expensive_check is never called. This only works if the operands have no side effects you rely on. See the pitfalls below.
Using `or` for default values
Because or returns the first truthy operand, it is often used to supply a fallback.
user_name = ''
display_name = user_name or 'guest'
print(display_name)This prints guest. The pattern is compact and common, but it replaces every falsy value, not just a missing one.
count = 0
limit = count or 10
print(limit)This prints 10, even though 0 may have been a deliberate, valid choice. When zero, an empty string, or an empty list is legitimate input, test for None explicitly instead.
count = 0
limit = 10 if count is None else count
print(limit)This prints 0. It uses a conditional expression, which a later chapter covers in full.
Pitfalls
Side effects that silently do not run
A skipped operand does not run at all. If the right side does something you need, such as incrementing a counter or saving data, short-circuiting can skip it.
saved = []
def save(record):
saved.append(record)
return True
record = 'draft'
is_valid = False
if is_valid and save(record):
print('saved')
print(saved)The output is []. Hiding actions inside conditions also makes code hard to read. Prefer running the action in a separate statement and testing its result.
`&` and `|` do not short-circuit
The bitwise operators & and | always evaluate both sides. On booleans they give the same value as and and or, but they lose the safety behavior.
def check(name, value):
print('checking', name)
return value
print(check('a', False) and check('b', True))
print(check('c', False) & check('d', True))The second line prints both checking c and checking d. In real code, (x != 0) & (10 / x > 1) raises ZeroDivisionError when x is 0, while x != 0 and 10 / x > 1 does not. Use and, or, and not for conditions.
Mixing `and` and `or` without parentheses
and binds more tightly than or, so A or B and C means A or (B and C). Short-circuiting follows that grouping.
def f(x):
print('f', x)
return x
result = f(0) or f(2) and f(3)
print('result', result)The output is:
f 0
f 2
f 3
result 3Adding parentheses even when they are not required makes the intent clear to readers.
Assuming the result is a boolean
If you need a real True or False, for example when returning from a function or storing a flag, wrap the expression in bool().
items = ['a']
flag = bool(items and items[0] == 'a')
print(flag)Without bool(), an empty items would give [] rather than False.
Short-circuiting beyond `and` and `or`
Two built-in functions follow the same idea. any(iterable) stops at the first truthy item, and all(iterable) stops at the first falsy item. With a generator expression, the remaining items are never computed.
numbers = [3, 8, 12, 5]
if any(n > 10 for n in numbers):
print('at least one number above 10')
if all(n > 0 for n in numbers):
print('all numbers are positive')Conditional expressions (x if cond else y) also evaluate only the branch they select.
Summary of the rules
| Expression | Evaluates right side when | Returns |
|---|---|---|
| `A and B` | `A` is truthy | `A` if falsy, otherwise `B` |
| `A or B` | `A` is falsy | `A` if truthy, otherwise `B` |
| `not A` | Always evaluates `A` | `True` or `False` |
| `A & B` | Always | Bitwise result, no short-circuit |
Exercise
What does this code print, and which calls to f run?
def f(x):
print('f', x)
return x
result = f(0) or f(2) and f(3)
print('result', result)
Then rewrite limit = count or 10 so that a count of 0 is kept.
Show answer
It prints "f 0", "f 2", "f 3", and "result 3". Since and binds tighter, the expression is f(0) or (f(2) and f(3)). f(0) returns 0, which is falsy, so or evaluates its right side. There f(2) returns 2, which is truthy, so and evaluates f(3) and returns 3. The fix for the default is limit = 10 if count is None else count, which replaces only a missing value and keeps 0.