Product case study · November 20, 2026

Ask Claude Code why every callback picks the last item

Build a tiny delayed-callback bug, give Claude Code a fixed contract, and test that each Python callback keeps its own value without running early.

Reading time
6 min
Checked
Nov 20, 2026
Three paper timer wheels release distinct geometric tokens into separate trays on a warm paper background.
Each delayed task should keep the value it was given.
Bottom line

Test callbacks after the loop finishes. A correct count of queued functions tells you nothing about which values they will use.

You queue three jobs: draft, review, publish. Later, all three announce “publish.” The queue has the right number of functions. Each function is looking at the wrong moment in time.

This is a useful Claude Code exercise because a plausible fix can introduce a different bug: running the jobs immediately instead of saving them for later. The acceptance test needs to catch both.

You’ll need Bash on macOS, Linux or WSL, Python 3, and an installed, signed-in Claude Code. The Python fixture and reference repair were tested locally; the Claude prompt is an authored exercise, not a recorded agent run. Official documentation was checked November 20, 2026. All jobs here operate on synthetic strings. Nothing publishes anything.

Build a queue that forgets its first two values

In a terminal, create a practice directory and the deliberately broken builder:

callback_lab=$(mktemp -d /tmp/claude-callback.XXXXXX)
cd "$callback_lab"
cat > jobs.py <<'PY'
def make_jobs(names, emit):
    jobs = []
    for name in names:
        jobs.append(lambda: emit(name))
    return jobs


if __name__ == "__main__":
    jobs = make_jobs(["draft", "review", "publish"], str.upper)
    print([job() for job in jobs])
PY
python3 jobs.py

The broken version prints:

['PUBLISH', 'PUBLISH', 'PUBLISH']

The functions read name when called, after the loop has finished. Python’s programming FAQ explains this behavior and notes that regular nested functions can do it too. Replacing lambda with def alone does not fix it.

I would debug this without timers, threads or a UI. Delayed execution only needs two steps: build the functions, then call them. A scheduler adds noise to a bug that fits in four lines.

Write down what must stay delayed

Save this contract as SPEC.md:

make_jobs(names, emit) accepts a finite list of strings and a callable.
Return a list with one callable per input item, in the same order.
Building that list must not call emit or mutate names.
Each returned callable must work with no arguments.
When called, it must call emit once with its own original string,
and return emit's result. Preserve duplicates and whitespace.
Calling a job again must call emit again with the same string.
An empty input returns an empty list without calling emit.
Separate calls to make_jobs must not interfere with each other.
Invalid input types and callbacks that receive arguments are out of scope.
Only jobs.py may change. Keep SPEC.md and test_jobs.py fixed.
Use the standard library only; no network access or package installation.

Save these five tests as test_jobs.py:

import unittest
from jobs import make_jobs


class JobTests(unittest.TestCase):
    def test_build_is_lazy(self):
        calls = []
        names = ["draft", "review", "publish"]
        jobs = make_jobs(names, calls.append)
        self.assertIsInstance(jobs, list)
        self.assertEqual(len(jobs), 3)
        self.assertTrue(all(callable(job) for job in jobs))
        self.assertEqual(calls, [])
        self.assertEqual(names, ["draft", "review", "publish"])

    def test_each_job_keeps_its_value_and_result(self):
        calls = []

        def emit(name):
            calls.append(name)
            return "done:" + name

        jobs = make_jobs(["draft", "review", "publish"], emit)
        self.assertEqual(
            [job() for job in jobs],
            ["done:draft", "done:review", "done:publish"],
        )
        self.assertEqual(calls, ["draft", "review", "publish"])
        self.assertEqual(jobs[0](), "done:draft")
        self.assertEqual(calls, ["draft", "review", "publish", "draft"])

    def test_duplicates_and_whitespace_survive(self):
        jobs = make_jobs([" draft ", "review", " draft "], str.upper)
        self.assertEqual(
            [job() for job in jobs], [" DRAFT ", "REVIEW", " DRAFT "]
        )

    def test_empty_input(self):
        calls = []
        self.assertEqual(make_jobs([], calls.append), [])
        self.assertEqual(calls, [])

    def test_batches_are_independent(self):
        first = make_jobs(["draft", "review"], str.upper)
        second = make_jobs(["publish"], str.upper)
        self.assertEqual(second[0](), "PUBLISH")
        self.assertEqual([job() for job in first], ["DRAFT", "REVIEW"])

Run the baseline:

python3 -m unittest -v test_jobs

Locally, five tests ran and three failed. The builder already passed the laziness and empty-input checks. The failures exposed incorrect values in the delayed calls. Python’s unittest reference documents this runner and the assertions used here.

The laziness test earns its place even though it passes on the broken code. A patch that replaces the lambda with emit(name) would execute work while building the list. Correct strings printed at the wrong time would still violate the contract.

Give Claude the failure, then inspect the timing

Start claude in the practice folder and paste:

Read SPEC.md, jobs.py and test_jobs.py.
Run python3 -m unittest -v test_jobs and report the actual baseline.
Explain why the demo returns the final name three times.
Repair only jobs.py, preserving the demo and delayed execution.
Do not edit the tests or spec, install packages, commit or delegate.
Run the same five tests and python3 jobs.py after the change.
Explain when emit is called and how each job retains its own name.
Report commands and results; do not claim an unexecuted check passed.

Anthropic’s debugging workflow recommends supplying a reproduction command and concrete error details. Here, the demo shows the symptom and the tests define the repair. Check the active permissions before accepting commands: the prompt limits the requested work but does not create a filesystem sandbox.

If Claude changes the expected output to three copies of PUBLISH, reject that edit. If it moves the callback calls into the loop, rerun the laziness test. Both moves hide the problem by changing the assignment.

Review a repair that binds the argument now

This reference implementation passed all five tests locally. Replace only the function at the top of jobs.py, adding the import, and leave the demo below it:

from functools import partial


def make_jobs(names, emit):
    return [partial(emit, name) for name in names]

Python documents functools.partial as creating a callable with arguments already supplied. Here, each partial holds its own string argument; calling it later invokes emit with that string. Building it does not invoke emit.

Rerun both commands:

python3 -m unittest -v test_jobs
python3 jobs.py

The reference repair produced five passing tests and:

['DRAFT', 'REVIEW', 'PUBLISH']

A default argument such as lambda name=name: emit(name) also binds the current string when the function is created, as the Python FAQ illustrates. I prefer partial for this contract because the intent is direct: save a function plus one argument for later. Neither technique is a promise to deep-copy mutable objects; this exercise deliberately uses strings.

Before applying the pattern to an event handler, inspect its calling convention. An event system may supply an argument when it calls a handler. partial forwards additional positional arguments after the bound ones, while a lambda’s default parameter can be overridden by a supplied argument. Our zero-argument job contract does not test either integration.

Keep the tests that separate construction from execution. That’s the useful habit to take back to an agent-built queue: check what gets saved, then check what happens when it finally runs.

Sources

Checked November 20, 2026:

Put this to work

Why a function created inside a loop can read the loop variable's final value.

Try

Ask Claude Code to repair one callback builder in a disposable Python project.

Prove it worked

Run five fixed tests against the broken builder and the reference repair.

Keep in view

  • Reproduce three callbacks that all return the final item.
  • Keep execution delayed while repairing the captured loop value.
  • Check order, duplicates, repeated calls and independent batches.
Learn the workflow: Set up your first Claude Code project session