Read Code Fast
Lesson 11 Control flow
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.
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
- Line 3 Exit 1: no code, return the cart. The
finallybelow is never reached, socheckedstays unset on this path. - Line 7 Exit 2: expired coupon, return the cart.
finallystill runs first, socheckedis set. - Line 8 Exit 3: a good coupon. The function ends with no
return, so the caller getsNone. Almost certainly a bug. - 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,continueandraiseskip the lines after them.finallyruns on every path, and areturninside 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.