Read Code Fast

Lesson 14 State and time

5 min read · Python · Quiz

stale closures, late binding in loops, order of execution

What you'll learn

  • Ask when a callback runs and which values it will see
  • Spot a loop whose callbacks all share one variable
  • Tell a stale copy from a live value

Code is read from top to bottom, but it doesn't always run that way. Timers, callbacks and promises run later, and by then the world has changed.

The idea

A function made inside another function remembers the variables around it, not the values they held at that moment. When it finally runs, later, it looks them up then. Python calls this late binding.

Two traps follow. A loop can create many lambdas that all share one variable, so they all see its last value. And Python evaluates a default argument once, when the function is defined, not on every call. Whenever you see a lambda, a callback or a default, ask: when does this run, and what will it see?

greeters.py
1import time23def make_greeters(names):4    greeters = []5    for name in names:6        greeters.append(lambda: f"hello {name}")7    return greeters89def log_event(msg, at=time.time()):10    print(at, msg)
  1. Line 5 One variable, name, is reused on every turn of the loop.
  2. Line 6 The lambda looks up name when it is called, not when it is made. After the loop name is the last name, so every greeter says hello to the last person. The fix: lambda name=name: ....
  3. Line 9 time.time() runs once, when def runs. Every call without at gets the same old time.

Take away

  • A function remembers variables, not the values they had when it was made.
  • Ask of every callback, timer and default: when does this run, and what will it see?
  • A loop that makes functions can give them all the same variable.

Quiz: test yourself

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