A dataclass field defaults to a list, dict or set, and defining the class raises ValueError

tx0/python:dataclass-mutable-defaultdefaultwarningbug

What it finds

items: list = [] in a @dataclass: the default would be shared by every instance, so dataclasses refuses it and raises ValueError when the class is defined. field(default_factory=list) makes a new value per instance.

Reported are list, dict and set displays, comprehensions and calls of list, dict and set as defaults of fields of classes decorated with dataclasses.dataclass. Fields annotated ClassVar are class attributes, not fields, and are left alone.

From the rule's source, dataclass_mutable_default.rs.

Example from the rule's tests
import dataclassesfrom dataclasses import dataclass, fieldfrom typing import ClassVar  @dataclassclass Order:    items: list = []tx0 reports: dataclasses refuses the default [] and raises ValueError    tags: dict = dict()tx0 reports: refuses the default dict()    notes: list = field(default_factory=list)    registry: ClassVar[list] = []    count: int = 0  @dataclasses.dataclass(frozen=True)class Point:    coords: set = {0}tx0 reports: refuses the default {0}  class Plain:    items: list = []
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:dataclass-mutable-default" = "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:dataclass-mutable-default] reason="..."

tx0 explain tx0/python:dataclass-mutable-default shows the same in the terminal. Found a false positive? Report it.