Lingua-e
← Errors
Python

Dataclass Mutable Default Error: What It Means and How to Fix It

Error reference

Dataclass Mutable Default Error

Language

Python

Severity

Medium

When 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.

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

Python

Code that triggers the error

from dataclasses import dataclass

@dataclass
class Config:
    tags: list = []  # mutable default

Error 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...

Debugging in English?

You just read real developer English to fix this. Lingua-e has free exercises built the same way: standups, code reviews, and real workplace scenarios.

Practice developer English, free