Read Code Fast

Lesson 11 Control flow

5 min read · Python · Quiz

draw the paths, exceptions as jumps

What you'll learn

  • Count the exits of a function, including falling off the end
  • Follow jumps like return, break, throw and finally
  • Spot swallowed errors and returns that hide results

A function can leave in more ways than you think. The bug is usually on a path the AI never looked at.

The idea

To read control flow, draw the paths. Every function has exits: a return, a raise, or falling off the end, which quietly returns None. Count them, then ask what the caller gets on each one.

Watch for jumps. return, break, continue and raise skip the lines after them, and an exception jumps straight to the nearest except. finally runs on every path, even right before a return. And a return inside finally wins over everything, even an error.

coupon.py
1def apply_coupon(cart, code):2    if not code:3        return cart4    try:5        coupon = lookup_coupon(code)6        if coupon["expired"]:7            return cart8        cart["total"] -= coupon["amount"]9    except KeyError:10        print("bad coupon")11    finally:12        cart["checked"] = True
  1. Line 3 Exit 1: no code, return the cart. The finally below is never reached, so checked stays unset on this path.
  2. Line 7 Exit 2: expired coupon, return the cart. finally still runs first, so checked is set.
  3. Line 8 Exit 3: a good coupon. The function ends with no return, so the caller gets None. Almost certainly a bug.
  4. Line 10 Exit 4: the error is printed and swallowed. Also None. The caller can't tell a bad coupon from a good one.

Take away

  • Count the exits: return, raise, and falling off the end.
  • return, break, continue and raise skip the lines after them.
  • finally runs on every path, and a return inside it hides everything else.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.