Lingua-e
Python

What is a Dataclass Mutable Default Error?

← Errors

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.

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

How to fix it

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.

Fixed code

from dataclasses import dataclass, field

@dataclass
class Config:
    tags: list = field(default_factory=list)

Related errors

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