How to Define Dataclass Field Defaults in Python
Implement a Python dataclass with default values for simple fields and default factories for mutable collections.
Python code
20 linesfrom dataclasses import dataclass, field
from typing import List
@dataclass
class Product:
name: str
price: float = 0.0
quantity: int = 0
tags: List[str] = field(default_factory=list)
metadata: dict = field(default_factory=dict)
if __name__ == "__main__":
p1 = Product("Laptop", 999.99, 5)
p2 = Product("Mouse")
p2.tags.append("wireless")
p2.metadata["brand"] = "Logitech"
print(p1)
print(f"Default price: {p2.price}, qty: {p2.quantity}")
print(f"Tags: {p2.tags}, Metadata: {p2.metadata}")
Output
Product(name='Laptop', price=999.99, quantity=5, tags=[], metadata={})
Default price: 0.0, qty: 0
Tags: ['wireless'], Metadata: {'brand': 'Logitech'}
How it works
The @dataclass decorator auto-generates an __init__, __repr__, and __eq__ based on class fields. Simple defaults like price: float = 0.0 work directly because they are immutable. Mutable defaults like lists and dicts must use field(default_factory=list) to avoid shared state across instances. default_factory calls a zero-argument function each time a new instance is created, giving each object its own list or dict. Without this, all instances would share the same mutable object, causing bugs.
Common mistakes
- Using `tags: List[str] = []` instead of `field(default_factory=list)` — causes shared state
- Forgetting that mutable defaults like dicts also need `default_factory=dict`
- Ordering fields with defaults before non-default fields, which raises a TypeError
Variations
- Use `field(default_factory=lambda: [])` for custom factory logic
- Set `frozen=True` in the decorator for immutable instances
Real-world use cases
- Defining API response models where optional fields fall back to sensible defaults.
- Modeling database records with default quantities or metadata before persistence.
- Creating configuration objects with default tag lists for analytics events.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.