How to Define Dataclass Field Defaults in Python

Implement a Python dataclass with default values for simple fields and default factories for mutable collections.

Easy Python 3.7+ Aug 9, 2026 OOP & classes 13 views 0 copies

Python code

20 lines
Python 3.7+
from 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

stdout
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

  1. Use `field(default_factory=lambda: [])` for custom factory logic
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.