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.
Comments (0)
No comments yet. Be the first!
Leave a Comment