Passing default list argument to dataclasses
From the dataclasses.field
docs:
The parameters to
field()
are:
- default_factory: If provided, it must be a zero-argument callable thatwill be called when a default value is needed for this field. Amongother purposes, this can be used to specify fields with mutabledefault values, as discussed below. It is an error to specify bothdefault and default_factory.
Your default_factory
is not a 0-argument callable but a list, which is the reason for the error:
from dataclasses import dataclass, fieldfrom typing import List@dataclassclass Pizza(): ingredients: List = field(default_factory=['dow', 'tomatoes']) # <- wrong!
Use a lambda function instead:
@dataclassclass Pizza(): ingredients: List = field(default_factory=lambda: ['dow', 'tomatoes'])
For complex datatypes i tend to abbreviate like so:
import copyfrom dataclasses import dataclass, fieldfrom typing import Dict, Tupledef default_field(obj): return field(default_factory=lambda: copy.copy(obj))@dataclassclass C: complex_attribute: Dict[str, Tuple[int, str]] = default_field({"a": (1, "x"), "b": (1, "y")})