#34 · Loops and closures

Find the bug · #34 · Loops and closures Medium Python

Every tab button opens the last tab

A desktop app builds a click handler per tab, and every button opens the last tab.

On this page

The report

Bug report

A desktop app builds a click handler for each tab in its sidebar. Whichever tab you click, it opens Profile, the last one.

The code

Read it first: what should it do? Then click the line where you think the bug is.

PythonClick the line you think is wrong
def make_tab_handlers(tabs):
    """One click handler per tab; each opens its own tab."""
    handlers = []
    for name in tabs:
        handlers.append(lambda: f"open {name}")
    return handlers

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
handlers = make_tab_handlers(["Home", "Orders", "Profile"])
print([h() for h in handlers])

It prints

['open Profile', 'open Profile', 'open Profile']

It should print

['open Home', 'open Orders', 'open Profile']
Show the answer: the bug, the fix, and how you’d find it

The bug (line 5)

Line 5 creates a lambda that uses the loop variable name. Python closures look a variable up when they’re called, not when they’re made, and by the time anyone clicks, the loop has finished and name is “Profile” for every handler. Capture the current value as a default argument: lambda name=name: ....

The fix

2    """One click handler per tab; each opens its own tab."""3    handlers = []4    for name in tabs:5        handlers.append(lambda: f"open {name}")5        handlers.append(lambda name=name: f"open {name}")6    return handlers

How you’d find it

  1. Reproduce: build the handlers, call each one. All three open Profile.
  2. All of them show the last value of the loop, so they’re reading the variable after the loop ended, not when they were created.
  3. That’s late binding: a closure keeps a reference to the variable, not a copy of its value.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

hs = make_tab_handlers(["a", "b"])
assert hs[0]() == "open a"
assert hs[1]() == "open b"

Where else this bites

  • JavaScript’s var in a loop (see “Every reminder says undefined”).
  • Callbacks or queries built in a loop and run later.
Your progress stays on this device.