PythonmediumPython

Data Class for Models

Use Python dataclasses for clean, type-hinted data models.

01

The problem

You need to create clean data models with automatic __init__, __repr__, and comparison methods.

02

The solution

Python
from dataclasses import dataclass, field
from typing import List, Optional
from datetime import datetime

@dataclass
class User:
    id: int
    username: str
    email: str
    created_at: datetime = field(default_factory=datetime.now)
    is_active: bool = True
    roles: List[str] = field(default_factory=list)
    bio: Optional[str] = None
    
    def __post_init__(self):
        self.email = self.email.lower()
    
    @property
    def is_admin(self) -> bool:
        return 'admin' in self.roles

03

Put it to work

Example
# Create user
user = User(
    id=1,
    username="johndoe",
    email="[email protected]",
    roles=["user", "admin"]
)

print(user)
# User(id=1, username='johndoe', email='[email protected]', ...)

print(user.is_admin)  # True

# Easy comparison
user2 = User(id=1, username="johndoe", email="[email protected]")
print(user == user2)  # True (compares all fields)

Worth knowing

Use frozen=True for immutable dataclasses. Combine with asdict() for easy JSON serialization.