Dataclass Mutable Default Error: What It Means and How to Fix It
Error reference
Dataclass Mutable Default Error
Language
Severity
MediumWhen it happens
Python's dataclass decorator raises a ValueError when a field is given a mutable default value (list, dict, set, etc.).
Potential fixes
Replace mutable defaults with field(default_factory=list), field(default_factory=dict), etc. For a custom default, use field(default_factory=lambda: MyClass()). This ensures each instance gets its own independent copy of the mutable value.
Related errors
Deep dive
Python's dataclass decorator raises a ValueError when a field is given a mutable default value (list, dict, set, etc.). If allowed, all instances would share the same object, causing subtle bugs. The fix is to use field(default_factory=...) instead.
Why it happens
- •A dataclass field is assigned an empty list, dict, or set as a default value.
- •A custom mutable object is used as a default without wrapping it in default_factory.
- •Copying a non-dataclass class to a dataclass without updating default values.
Potential fixes
Replace mutable defaults with field(default_factory=list), field(default_factory=dict), etc. For a custom default, use field(default_factory=lambda: MyClass()). This ensures each instance gets its own independent copy of the mutable value.
Examples
Code that triggers the error
from dataclasses import dataclass
@dataclass
class Config:
tags: list = [] # mutable defaultError output
ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory
Fixed code
from dataclasses import dataclass, field
@dataclass
class Config:
tags: list = field(default_factory=list)Practice in English
How would you explain a Dataclass Mutable Default Error to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free