QA
Intermediate LevelPython

How do you use @dataclass with __post_init__, field(default_factory=...), and frozen=True for immutable domain models?

❓ Interview Prompt: Explain `@dataclass`, `__post_init__` validation, `field(default_factory=list)`, and `frozen=True` immutable dataclasses.

Python 3.7+ '@dataclass' automates class boilerplate ('__init__', '__repr__', '__eq__'):

Advanced Features:

•
'field(default_factory=list)': Solves mutable default argument bugs by initializing new list instances per object.
•
'__post_init__(self)': Executes validation or computed attribute calculations after '__init__' finishes.
•
'frozen=True': Creates immutable objects where modifying attributes raises 'FrozenInstanceError'!

Code Implementation Example

python
from dataclasses import dataclass, field

@dataclass(frozen=True) # Immutable dataclass!
class User:
    id: int
    name: str
    tags: list[str] = field(default_factory=list) # Safe mutable default!
    
    def __post_init__(self):
        if self.id <= 0:
            raise ValueError('ID must be positive')

u = User(id=101, name='Alice')
# u.name = 'Bob' # Raises FrozenInstanceError!
💡Building immutable validated domain models using @dataclass.
🎯 Interview Key Takeaway

Use @dataclass(frozen=True) for immutable data models and field(default_factory=list) for safe defaults.

#dataclasses#frozen=True#default_factory#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?