Every key of dict.fromkeys or every context of a ContextVar gets the same mutable object

tx0/python:fromkeys-shared-valuedefaultwarningbug

What it finds

dict.fromkeys(names, []): the one list is the value of every key, so appending to one key's list changes them all. contextvars.ContextVar("v", default=[]) alike shares one default between every context. A comprehension, {name: [] for name in names}, makes a value per key.

Reported are list, dict and set displays and comprehensions, and calls of list, dict, set and bytearray, as the value of dict.fromkeys or the default of a ContextVar.

From the rule's source, fromkeys_shared_value.rs.

Example from the rule's tests
import contextvars  def build(names):    a = dict.fromkeys(names, [])tx0 reports: every key of dict.fromkeys gets this same [], so a change through one is seen by all    b = dict.fromkeys(names, set())tx0 reports: gets this same set()    c = dict.fromkeys(names, 0)    d = dict.fromkeys(names)    return a, b, c, d  current = contextvars.ContextVar("current", default={})tx0 reports: every context of this ContextVar gets this same {}other = contextvars.ContextVar("other", default=None)
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:fromkeys-shared-value" = "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:fromkeys-shared-value] reason="..."

tx0 explain tx0/python:fromkeys-shared-value shows the same in the terminal. Found a false positive? Report it.