Read Code Fast

Lesson 7 Guards and defaults

6 min read · Python · Quiz

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.

describe.py
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}"
  1. Line 2 A guard. not options is true for None and also for an empty dict {}: both leave early here.
  2. Line 4 or replaces 0 and "" too. If size: 0 can be a real value, this line is a bug.
  3. 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?
  • or means "falsy"; is None and .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.