Sub topic 6
Short-circuiting and the values and/or return
This chapter assumes you know Python's truthiness rules (which values count as true or false) and that comparisons produce True or False. It also assumes you can read basic if statements and function definitions. Here you will see that and and or are not just "boolean operators". They pick one of their operands and return it, and they sometimes skip evaluating the second one.
What `and` and `or` actually return
Many languages define a || b as a boolean result. Python does not. Both and and or return one of the two operand objects, unchanged.
| Expression | Rule | Result |
|---|---|---|
| `x or y` | If `x` is truthy, return `x`. Otherwise return `y`. | One of the operands |
| `x and y` | If `x` is falsy, return `x`. Otherwise return `y`. | One of the operands |
| `not x` | Evaluate the truth value of `x` and invert it. | Always `True` or `False` |
The two rules are mirror images. or stops at the first truthy value. and stops at the first falsy value. If neither stops early, the result is the last operand.
print(0 or "default") # default
print("a" and "b") # b
print([] and 1) # []
print("" or 0 or []) # []
print(1 and 2 and 3) # 3
print(1 and 0 and 3) # 0Trace the fourth line. "" is falsy, so or moves on. 0 is falsy, so it moves on again. [] is the last operand, so it is returned even though it is falsy. The final result is [], not False.
The returned object is the same object, not a converted copy. x or y gives you back x itself, so (x or y) is x holds whenever x is truthy.
Because the result is an operand, an and/or expression is not necessarily a bool. In an if statement this does not matter, since the condition is tested for truthiness anyway. It matters when you store or print the result.
result = [1, 2] and {"k": 1}
print(result) # {'k': 1}
print(type(result)) # <class 'dict'>
print(bool(result)) # Truenot is different. It always produces a real boolean, because there is no operand that would make sense to return.
print(not [], not "x") # True FalseShort-circuit evaluation
Python evaluates the left operand first. If that operand already determines the outcome, Python does not evaluate the right operand at all. This is called short-circuit evaluation.
x or y: ifxis truthy, the result isx, soyis never evaluated.x and y: ifxis falsy, the result isx, soyis never evaluated.
You can see this by giving the operands side effects.
def check(label, value):
print("evaluating", label)
return value
print(check("left", 0) and check("right", 1))
print(check("left", 1) or check("right", 2))
print(check("left", 0) or check("right", 2))The output is:
evaluating left
0
evaluating left
1
evaluating left
evaluating right
2In the first two statements, the right-hand call never runs. In the third, the left value is falsy, so or must look at the right operand and return it. Each print shows the evaluation messages first because the arguments are computed before print runs.
Short-circuiting as a guard
The most important practical use is protecting an expression that would fail if the first test were false. The right side only runs when the left side has already confirmed it is safe.
def ratio_over_one(total, count):
return count != 0 and total / count > 1
print(ratio_over_one(10, 2)) # True
print(ratio_over_one(10, 0)) # FalseWhen count is 0, the expression count != 0 is False. The division is skipped, so there is no ZeroDivisionError. The same pattern protects attribute access and indexing.
settings = None
print(settings and settings.get("theme")) # None
settings = {"theme": "dark"}
print(settings and settings.get("theme")) # darkIn the first case the whole expression is None, which is the falsy left operand. Be aware that this returns the left operand, so the caller sees None rather than False. That is usually what you want here, but it is worth knowing.
Order matters. Reversing the operands in a guard defeats it.
def unsafe(total, count):
return total / count > 1 and count != 0
try:
unsafe(10, 0)
except ZeroDivisionError:
print("guard in the wrong place") # guard in the wrong placeUsing `or` for default values
Because x or y returns y when x is falsy, it is a compact way to supply a fallback.
name = ""
print(name or "anonymous") # anonymous
user_input = " "
print(user_input.strip() or "n/a") # n/aYou can chain several fallbacks. The first truthy value wins.
import os
host = os.environ.get("APP_HOST") or "localhost"
print(host) # localhost (if APP_HOST is unset or empty)An empty environment variable is falsy, so or replaces it just like a missing one. That is often the behavior you want.
The falsy-value trap
The weakness of or defaults is that it replaces every falsy value, not just the missing one. If 0, "", or [] are legitimate inputs, or silently overwrites them.
def connect(host, retries=None):
retries = retries or 3
return host, retries
print(connect("db", 0)) # ('db', 3) the caller asked for 0 retriesThe caller explicitly asked for zero retries, and the function replaced it with 3. The fix is to test for None specifically, which is the subject of a later chapter.
def connect_fixed(host, retries=None):
if retries is None:
retries = 3
return host, retries
print(connect_fixed("db", 0)) # ('db', 0)
print(connect_fixed("db")) # ('db', 3)A good rule: use x or default when every falsy value should be treated as "not provided". Use is None when falsy values such as 0 or "" are meaningful.
The `cond and a or b` trap
Before Python had the conditional expression, people wrote cond and a or b as a ternary. It breaks whenever a is falsy.
flag = True
value = flag and "" or "fallback"
print(value) # fallbackflag and "" evaluates to "", which is falsy, so or moves on to "fallback". The intended answer was "". Use the conditional expression instead, which only looks at the condition.
flag = True
value = "" if flag else "fallback"
print(repr(value)) # ''Precedence
Python gives not higher precedence than and, and and higher precedence than or. All three bind more loosely than comparisons.
print(True or False and False) # True
print((True or False) and False) # False
print(not 0 == 1) # TrueThe first line parses as True or (False and False). The third parses as not (0 == 1), because == binds tighter than not. When an expression mixes and with or, add parentheses even where they are not required. Readers should not have to remember the precedence table.
`and`/`or` versus `&`/`|`
The bitwise operators & and | look similar but behave differently. They are ordinary operators, so both operands are always evaluated, and they do not return operands by the truthiness rules.
def noisy(v):
print("called", v)
return v
print(noisy(False) & noisy(True))
# called False
# called True
# False
print(1 and 2) # 2
print(1 & 2) # 0With bool operands, & and | return a bool, which is why they sometimes appear in combined conditions. With other types they work on bits. Use and and or for logic. Reserve & and | for bit manipulation, and for libraries such as NumPy and pandas that define them for element-wise array logic.
Common mistakes
- Treating the result of
and/oras abool. Wrap it inbool(...)if you needTrueorFalseexactly. - Using
x or defaultwhen0,"", or[]are valid values. - Putting the risky test before the guard in an
andexpression. - Relying on a side effect in the right operand, such as a function call that must always run. It will not run if the left side decides the result.
- Writing
a == 1 or 2and expecting it to test both values. It parses as(a == 1) or 2, which is always truthy whenais not1. Writea in (1, 2)instead.
Exercise
Predict the output of each line, and say whether the right-hand function is called. def f(tag, v): print("f", tag) return v print(f("a", 0) or f("b", "x")) print(f("c", "y") or f("d", "z")) print(f("e", []) and f("g", 1))
Show answer
Line 1 prints "f a", then "f b", then "x". The left value 0 is falsy, so or evaluates and returns the right operand. Line 2 prints "f c", then "y". The left value "y" is truthy, so f("d", "z") is never called. Line 3 prints "f e", then "[]". The left value [] is falsy, so and returns it and skips f("g", 1).
Exercise
The function below should return the configured timeout, using 30 when none is configured. A timeout of 0 means "no timeout" and must be preserved. Explain the bug and write a corrected version. def get_timeout(config): return config.get("timeout") or 30
Show answer
The or operator replaces every falsy value, so a configured timeout of 0 becomes 30. Test for None explicitly: def get_timeout(config): timeout = config.get("timeout") if timeout is None: return 30 return timeout Alternatively, use config.get("timeout", 30), which only supplies 30 when the key is absent. That version would still return None if the key exists with the value None.
Exercise
Rewrite the expression ok and "yes" or "no" so that it still works when the positive branch is an empty string. What does the original return if ok is True and the positive branch is ""?
Show answer
With ok True and "" as the positive branch, the original ok and "" or "no" evaluates ok and "" to "", which is falsy, so it returns "no". The correct form is the conditional expression: "" if ok else "no", which returns "" when ok is True.