A loop adds to or removes from the collection it is walking

tx0/python:modified-while-iteratingdefaultwarningbug

What it finds

for key in cache: del cache[key]: changing the size of a dict or set while a loop walks it raises RuntimeError: dictionary changed size during iteration, and removing items from a list being walked skips the item after each removed one. Walking a copy, for key in list(cache):, avoids both.

Reported are del name[...] and calls of pop, remove, discard, clear, add, update and setdefault on the very name the loop walks, directly or through .keys(), .values() or .items(), when the loop is not left right after, by break, return or raise in the same block. Appending to a list being walked is left alone, since it is the usual way to process a growing work list, and so is self, whose methods may change something else.

From the rule's source, modified_while_iterating.rs.

Example from the rule's tests
def prune(cache, items, seen):    for key in cache:        if cache[key] is None:            del cache[key]tx0 reports: this changes cache while the loop walks it    for key, value in seen.items():        seen.pop(key)tx0 reports: this changes seen while the loop walks it    for item in items:        if item:            items.remove(item)tx0 reports: this changes items while the loop walks it    for item in items:        items.append(item)    for key in list(cache):        del cache[key]    for item in items:        if item:            items.remove(item)            break
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 in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/python:modified-while-iterating" = "off"

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:modified-while-iterating] reason="..."

tx0 explain tx0/python:modified-while-iterating shows the same in the terminal. Found a false positive? Report it.