Sub topic 8
Short-circuit evaluation
This chapter assumes you can write an if statement, know which values are truthy or falsy, and have used and, or, and not. Here you will learn that Python stops evaluating a condition as soon as the result is known, and how to use that behavior safely.
What short-circuiting means
Python evaluates and and or from left to right. It stops as soon as the answer is certain.
A and B: ifAis falsy, the result isA. Python never looks atB.A or B: ifAis truthy, the result isA. Python never looks atB.
Otherwise, Python evaluates B and returns it.
Guarding a risky lookup
The most common use is to put a safety check on the left of and. If the check fails, the risky expression on the right never runs.
settings = {}
if settings and settings['debug']:
print('debug on')
else:
print('debug off')An empty dict is falsy, so and stops at once. Python never evaluates settings['debug'], so no KeyError is raised. The program prints debug off.
If you swap the order, the code fails:
settings = {}
if settings['debug'] and settings:
print('debug on')This raises KeyError: 'debug', because the lookup runs first. Put the guard on the left.
Seeing the skipped side
A function with a visible side effect shows exactly what runs.
def check(name, value):
print('checking', name)
return value
if check('first', False) and check('second', True):
print('both true')
print('---')
if check('third', True) or check('fourth', False):
print('at least one true')The output is:
checking first
---
checking third
at least one trueThe functions check('second', ...) and check('fourth', ...) are never called.
The result is an operand, not always a bool
Because and and or return one of their operands, the result may not be True or False. This is useful for defaults:
name = ''
display = name or 'anonymous'
print(display)The empty string is falsy, so or moves on and returns 'anonymous'.
| Expression | Result |
|---|---|
| `0 and 5` | `0` |
| `3 and 5` | `5` |
| `0 or 5` | `5` |
| `3 or 5` | `3` |
Inside an if, only the truthiness of the result matters. When you assign the result to a variable, remember that it can be any value.
Common errors
- Wrong order. Placing the risky expression before its guard, as in the
KeyErrorexample above. - Hidden side effects. If the right side must always run, such as a function that logs or updates something, do not put it after
andoror. Call it on its own line first. - Using
orfor defaults when 0 is valid.count or 10replaces a legitimate0with10. Use an explicit check instead:
count = 0
value = 10 if count is None else count
print(value)This prints 0, because only None triggers the default.
Exercise
What does this code print, and does risky() run?
def risky():
print('risky ran')
return True
items = []
if items and risky():
print('yes')
else:
print('no')
Show answer
It prints only no. The empty list is falsy, so and short-circuits and risky() is never called, so risky ran does not appear.
Exercise
Rewrite limit = user_limit or 100 so that a user_limit of 0 is kept as 0, and only None falls back to 100.
Show answer
limit = 100 if user_limit is None else user_limit