A lambda stored in a loop reads the loop variable when called, not when made

tx0/python:loop-variable-closurerecommendedwarningbug

What it finds

handlers.append(lambda: run(name)) in for name in names:: the lambda looks name up when it is called, not when it is made, so every stored lambda sees the value of the last pass. Binding the value as a default, lambda name=name: run(name), or with functools.partial, keeps the value of each pass.

Reported are lambdas made in a loop body and stored, by append, add, insert, setdefault, as a dict value or into a subscript or attribute, that read a target of the loop. Lambdas that are called during the pass, as keys of sorted or filter, are left alone.

From the rule's source, loop_variable_closure.rs.

Example from the rule's tests
def build(names, run, table):    handlers = []    for name in names:        handlers.append(lambda: run(name))tx0 reports: the lambda reads name when it is called, so it sees the value of the last pass        table[name] = lambda: run(name)tx0 reports: the lambda reads name when it is called        handlers.append(lambda name=name: run(name))        ordered = sorted(names, key=lambda other: other == name)        run(ordered)    return handlers
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/python:loop-variable-closure" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

# tx0: ignore[tx0/python:loop-variable-closure] reason="..."

tx0 explain tx0/python:loop-variable-closure shows the same in the terminal. Found a false positive? Report it.