Sub topic 10
Short-circuit evaluation and returned operands
This chapter assumes you know which values Python treats as true or false (truthiness) and that you have used and, or and not in if conditions. Here you will learn two facts about and and or that many people miss. They return one of their operands, not necessarily True or False. They also skip the right operand when the left one already settles the result.
The rule for `or` and `and`
or and and examine the left operand first and decide whether to look at the right one.
a or breturnsaifais truthy. Otherwise it returnsb.a and breturnsaifais falsy. Otherwise it returnsb.
The returned value is the operand object itself. Python does not convert it to a bool. Only not always produces a bool.
| Expression | Left operand | Result | Right operand evaluated? |
|---|---|---|---|
| `"x" or "y"` | truthy | `"x"` | No |
| `"" or "y"` | falsy | `"y"` | Yes |
| `"x" and "y"` | truthy | `"y"` | Yes |
| `"" and "y"` | falsy | `""` | No |
| `not ""` | any | `True` | Not applicable |
print(0 or "default")
print("" or [] or None)
print("a" and "b")
print(repr("" and "b"))
print(not "")The output is default, None, b, '' and True. In the second line every operand is falsy, so or runs to the end and returns the last one, None.
What short-circuiting means
Short-circuit evaluation means Python stops as soon as the result is known. When the right operand is skipped, no code in it runs. That includes function calls, indexing and division.
name = ""
display = name or "anonymous"
print(display)
print(0 and 1 / 0)The second line prints 0. The expression 1 / 0 would raise ZeroDivisionError, but it never runs because 0 is falsy.
You can see the evaluation order by adding side effects:
def check(label, result):
print(f"checking {label}")
return result
print(check("first", False) and check("second", True))
print(check("first", True) or check("second", False))
print(check("a", 0) or check("b", 5))The output is:
checking first
False
checking first
True
checking a
checking b
5The first two statements call check only once each. The third calls it twice, because 0 is falsy and or needs the right operand.
Chains
Both operators are left-associative, so a chain is evaluated one pair at a time from the left.
a or b or creturns the first truthy operand, or the last operand if none is truthy.a and b and creturns the first falsy operand, or the last operand if all are truthy.
This makes a fallback chain easy to write:
import os
cli_value = ""
env_value = os.environ.get("APP_MODE", "")
mode = cli_value or env_value or "production"
print(mode)If APP_MODE is unset or empty, this prints production.
Using short-circuiting as a guard
The most common use is to put a safety check on the left of and. The right side then runs only when it is safe to do so.
def first_is_big(items):
return bool(items) and items[0] > 10
print(first_is_big([]))
print(first_is_big([42]))This prints False and then True. Without the guard, items[0] on an empty list would raise IndexError.
The bool(items) wrapper is deliberate. Without it, first_is_big([]) would return [], which is falsy but is not False. That matters if the caller checks the result with is False or stores it in a typed field. Wrap the left operand in bool() when the result must be a real bool.
The main pitfall: valid falsy values
x or default replaces every falsy x, not only a missing one. The values 0, 0.0, "", [] and False are often legitimate input.
def port_or_default(port):
return port or 8080
def port_or_default_safe(port):
return 8080 if port is None else port
print(port_or_default(0))
print(port_or_default_safe(0))The first call returns 8080, so it silently discards the caller's 0. The second returns 0. Use or only when every falsy value really should be replaced. If you mean "missing", test with is None (the identity test from the earlier chapter).
Operators that do not short-circuit
Short-circuiting belongs only to and, or, and conditional expressions (which evaluate just one branch). The bitwise operators & and | always evaluate both sides, and so do the arithmetic and comparison operators.
def noisy(value):
print("evaluated", value)
return value
print(noisy(False) & noisy(True))
print(noisy(False) and noisy(True))The first statement prints evaluated False, evaluated True and then False. The second prints evaluated False and then False. Using & where you meant and is a real bug if the right side has side effects or can raise an exception.
The built-in functions any() and all() also stop early. any stops at the first truthy item and all stops at the first falsy one. When you pass them a generator expression, the remaining items are never produced.
Common mistakes
- Expecting a bool.
"a" and "b"is"b", notTrue. Compare with==or callbool()if you need a bool. - Relying on side effects in the right operand.
log_ok() or write_audit()may skipwrite_audit(). Put required work in its own statement. - Mixing
andandorwithout parentheses.andbinds tighter thanor, soa or b and cmeansa or (b and c). Add parentheses to show your intent. - Treating
x and y or zas a ternary. It gives the wrong answer whenyis falsy. Usey if x else zinstead.
Exercise
What do print(0 or [] or "x"), print(3 and 0 and 1 / 0) and print(not [] and "ok") print? Explain why the second does not raise an error.
Show answer
They print x, 0 and ok. In the first, 0 and [] are falsy, so or returns the last operand, "x". In the second, 3 is truthy so and moves on, then 0 is falsy so and returns 0 and never evaluates 1 / 0. In the third, not [] is True, which is truthy, so and returns the right operand, "ok".
Exercise
A function takes timeout=None and should use 30 seconds when the caller passes nothing, but a caller passing 0 must get 0. Why does timeout or 30 fail, and what should you write?
Show answer
0 is falsy, so timeout or 30 replaces a deliberate 0 with 30. Write timeout = 30 if timeout is None else timeout, which replaces only None.