Read Code Fast
Lesson 7 Guards and defaults
early return, optional access and the default-value traps
What you'll learn
- Read a guard clause and say what it protects
- Tell a real missing value from a falsy one
- Spot the default-value traps AI code falls into
AI code is full of defaults and guards. Most are fine. A few quietly turn a real value into the wrong one.
The idea
A guard checks a condition up front and leaves early, so the rest of the function can assume the good case. Read a guard as a promise: after this line, this is true.
A default supplies a value when one is missing. The trap is what counts as missing. In Python, or replaces every falsy value (0, "", [], {}, None), is None replaces only None, and dict.get(key, default) uses the default only when the key is absent. There is no ?. in Python, so you will see (x or {}).get(...) instead.
1def describe(options=None):2 if not options:3 return "defaults"4 size = options.get("size") or 205 owner = (options.get("user") or {}).get("name", "guest")6 return f"{owner}: {size}"
- Line 2 A guard.
not optionsis true forNoneand also for an empty dict{}: both leave early here. - Line 4
orreplaces0and""too. Ifsize: 0can be a real value, this line is a bug. - Line 5
(x or {})is Python's stand-in for?.: it makes a missing user safe to read from.
Take away
- Read a guard as a promise about the lines after it.
- Ask of every default: can 0, "", [] or False be a real value here?
ormeans "falsy";is Noneand.get(key, default)mean "missing".
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.