Python Dataclass Default Factory Error Fix
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,dictfor dicts, andsetfor sets. - Use
field(default=None)withNoneas 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
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto 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
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro