📡 You're offline — showing cached content
New version available!
Quick Access
Python Intermediate

Python Data Classes and attrs: Clean Data Models Without Boilerplate

Master Python dataclasses — auto-generated init/repr/eq, frozen immutable instances, slots for memory efficiency, and attrs for advanced validation.

EzyCoders Admin December 7, 2025 10 min read 1 views
Python Data Classes attrs Clean Models
Share: Twitter LinkedIn WhatsApp

Python Data Classes

Python's dataclasses module generates boilerplate (init, repr, eq) automatically. They make clean, self-documenting data models without verbose manual class definitions.

from dataclasses import dataclass, field, asdict
from datetime import datetime

@dataclass
class User:
    id:         int
    name:       str
    email:      str
    role:       str       = 'member'
    tags:       list      = field(default_factory=list)
    created_at: datetime  = field(default_factory=datetime.now)

    def __post_init__(self):
        if '@' not in self.email:
            raise ValueError(f"Invalid email: {self.email}")
        self.name = self.name.strip().title()

u = User(id=1, name='rahul sharma', email='r@e.com')
print(u)           # User(id=1, name='Rahul Sharma', email='r@e.com', ...)
print(asdict(u))   # {'id': 1, 'name': 'Rahul Sharma', ...}

Frozen and Slots

@dataclass(frozen=True)   # immutable — hashable, usable as dict key
class Point:
    x: float
    y: float
    def distance(self): return (self.x**2 + self.y**2)**0.5

@dataclass(slots=True)    # Python 3.10+ — memory efficient
class Pixel:
    x: int
    y: int
    color: str = '#000000'

Q: Dataclass vs Pydantic?

Dataclasses are stdlib — zero dependencies, no runtime coercion. Pydantic adds runtime type coercion, JSON serialization, and validation. Use dataclasses for internal models, Pydantic for API boundaries and config loading.

EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment