Skip to content

Python Dataclass Default Factory Error Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Python Dataclass Default Factory Error Fix. We cover key concepts, practical examples, and best practices.

Python dataclasses reject mutable default values like lists, dicts, or sets directly in field definitions. Using default_Factory is required to provide fresh mutable defaults for each instance, preventing bugs in data pipelines.

The Wrong Way

from dataclasses import dataclass
from typing import List

@dataclass
class ShoppingCart:
    items: List[str] = []  # Mutable default

Output:

Traceback (most recent call last):
  File "script.py", line 6, in <module>
    class ShoppingCart:
ValueError: mutable default <class 'list'> is not allowed: use default_factory

The Right Way

Use field(default_factory=list) to create a new list for each instance:

from dataclasses import dataclass, field
from typing import List

@dataclass
class ShoppingCart:
    items: List[str] = field(default_factory=list)

cart1 = ShoppingCart()
cart1.items.append("apple")

cart2 = ShoppingCart()
cart2.items.append("banana")

print(cart1)
print(cart2)

Output:

ShoppingCart(items=['apple'])
ShoppingCart(items=['banana'])

Step-by-Step Fix

1. Import field and use default_factory

from dataclasses import dataclass, field

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

2. Create custom factory functions

from dataclasses import dataclass, field
from datetime import datetime

def default_timestamp():
    return datetime.now()

@dataclass
class Event:
    name: str
    created_at: datetime = field(default_factory=default_timestamp)

3. Use lambda for simple factories

@dataclass
class Matrix:
    rows: int
    cols: int
    data: list = field(default_factory=lambda: [[0] * 3 for _ in range(3)])

4. Combine default_factory with init=False

@dataclass
class Request:
    url: str
    headers: dict = field(default_factory=dict, init=False)

req = Request("https://example.com")
print(req)

Output:

Request(url='https://example.com', headers={})

5. Handle nested dataclasses

@dataclass
class Address:
    street: str = ""
    city: str = ""

@dataclass
class Person:
    name: str
    address: Address = field(default_factory=Address)

Prevention Tips

  • Always use field(default_factory=...) for mutable types in dataclasses.
  • Use field(default_factory=list) for lists, dict for dicts, and set for sets.
  • Use field(default=None) with None as a sentinel for optional mutable fields.
  • Define named factory functions for complex defaults instead of inline lambdas.
  • Use dataclasses.field(compare=False) for fields that should not affect equality.

Common Mistakes with dataclass default

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does Python forbid mutable defaults in dataclasses?

Mutable defaults are shared across all instances, causing bugs where modifying one instance affects others. Dataclasses enforce default_factory to ensure each instance gets a fresh copy.

What is the difference between default and default_factory?

default sets a fixed value (used once). default_factory is a callable invoked for each instance, producing independent values. Use default for immutable types and default_factory for mutable ones.

Can I use default_factory for immutable types?

Yes, but it is unnecessary. Immutable types like int, str, tuple, and frozenset are safe to use with plain default because they cannot be mutated after creation.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro