Topic 47 of 58
Data Classes
Overview
Writing classes just to store data (like API responses or Database records) used to require tedious boilerplate code to define __init__, __repr__, and __eq__. Introduced in Python 3.7, the @dataclass decorator automates all of this. By simply defining your variables with Type Hints, Python dynamically generates the constructor and magic methods for you, resulting in immensely clean, readable code.
Syntax
python
from dataclasses import dataclass
# The decorator writes the boilerplate automatically
@dataclass
class Product:
id: int
name: str
price: float
in_stock: bool = True # Default value supported
# We get a full __init__ automatically
p1 = Product(1, "Laptop", 999.99)
p2 = Product(1, "Laptop", 999.99)
# We get a clean __repr__ automatically
print(p1) # Product(id=1, name='Laptop', price=999.99, in_stock=True)
# We get an __eq__ that compares VALUES, not memory addresses
print(p1 == p2) # True!Common Pitfalls
- Using mutable default values (like
tags: list = []). You MUST usefield(default_factory=list)to ensure a fresh list is created for every instance, preventing shared state bugs.
Interview Questions
Q:
How can you make a dataclass completely immutable (read-only)?
A:
By setting frozen=True in the decorator signature: @dataclass(frozen=True). This blocks variable reassignment and makes the instances fully hashable.
Real-World Example
Creating robust data models for incoming JSON payloads in web frameworks.
example
python
from dataclasses import dataclass, field
@dataclass
class APIResponse:
status_code: int
# Proper mutable default factory
data: dict = field(default_factory=dict)
error_message: str = NoneCheck Your Knowledge
Test your understanding of Data Classes with these quick questions.