Skip to content

set-dict-quadratic-merge (OPT102)

Family: Complexity Rewrites (OPT) · Exact · Enabled by default · Severity warning (slower code) · Safe fix (--fix)

Unconditionally profitable set/dict quadratic merge ({**d, ...} with d first).

What it does

Checks loops that rebuild a dict or set every iteration and rewrites them in place:

  • d = {**d, k: v} → d[k] = v, or d.update({...}) when the remaining entries have side effects;
  • d = {**d, **other} → d.update(other);
  • s = s | {e} → s |= {e} (also d = d | other for dicts).

What a report states

A report states that the merge ({**d, ...} with the accumulator first, s = s | t, d = d | other), in a loop, builds a new set or dict from the whole accumulated one each time it runs, where updating it would change it in place.

Its premises:

  • Builtin type by construction: the value is a builtin set or dict by its construction. Established: the Soundness lane takes types from constructions only.
  • Loop-carried: the result is the value the next iteration starts from. Established by the IR.
  • In a loop: the statement is in the body of a loop. Established by the IR.
  • Rewrite proven safe: the help says [safe fix: ...], [proven-safe suggestion: ...], or [proven safe; ...]. A report whose help names a blocking obligation instead ([not auto-fixable: ...]) lacks this premise and is heuristic whatever the rule's certainty; the proven reports are the rule's exact tier.

Not part of the claim: how many times the statement runs (one under a branch inside the loop counts), and how large the loop or the set or dict is. The message claims no size and no cost estimate. The rewrite never makes the code slower, so a loop the code fixes at a few items is reported too.

Why is this bad?

Each rebuild copies the whole container, so the loop is quadratic. The in-place update is never slower.

Example

def index(items: list[tuple[str, int]]) -> dict[str, int]:
    d = {}
    for k, v in items:
        d = {**d, k: v}
    return d

Use instead:

def index(items: list[tuple[str, int]]) -> dict[str, int]:
    d = {}
    for k, v in items:
        d[k] = v
    return d

Fix safety

Applied by heki check --fix only when proven safe, with the same obligations as OPT101 (exact builtin, unique, no live alias / iterator / view, evaluation order preserved), plus:

  • the accumulator must be the leading ** entry. found = {**site, **found} keeps the keys already in found, while found.update(site) would overwrite them, so it is never rewritten;
  • for |, the right operand must be an exact set / dict (a subclass could make __ror__ and __ior__ disagree);
  • the display inserts each entry before it evaluates the next one, and an insertion can run a key's __eq__ (on a hash collision) or a mapping's keys() / __getitem__. Gathering several entries into one d.update({...}) is applied only when the keys are int / str / bytes / bool / float values and the later entries are constants or local names; d = {**d, **other} with an unknown mapping other is not rewritten;
  • an update that inserts several keys stops halfway when an insertion raises, where the display left d unchanged: it is not applied when an exception handler reads d;
  • s |= t grows the set's table in place, while s = s | t copies it into a new one, and the two can iterate the same elements in different orders (an int set in the same order in every run). The set form is applied only when every later use of the set just tests it (x in s, len(s), truthiness, == / != with a builtin value); a set that is iterated, converted (sorted(s), list(s)), formatted, returned, stored, yielded, or passed to other code keeps s = s | t. A dict keeps its insertion order either way.