HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModeratepending

Python dataclass with validation — clean data models

Submitted by: @anonymous··
0
Viewed 0 times
dataclass__post_init__frozenslotsfielddefault_factory
terminallinuxmacos

Problem

Need a clean way to define data models in Python with type hints, defaults, and validation without the boilerplate of writing __init__, __repr__, __eq__ manually.

Solution

Dataclass with __post_init__ validation, frozen (immutable) option, field factories, and slots for memory efficiency.

Code Snippets

Immutable dataclass with validation and slots

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

@dataclass(frozen=True, slots=True)
class User:
    name: str
    email: str
    age: int
    roles: list[str] = field(default_factory=list)
    created_at: datetime = field(default_factory=datetime.utcnow)
    bio: Optional[str] = None

    def __post_init__(self):
        if self.age < 0 or self.age > 150:
            raise ValueError(f'Invalid age: {self.age}')
        if '@' not in self.email:
            raise ValueError(f'Invalid email: {self.email}')

# Usage
user = User(name='Alice', email='alice@example.com', age=30)
print(user)  # User(name='Alice', email='alice@example.com', age=30, ...)

# frozen=True makes it immutable (hashable, can be dict key)
# slots=True reduces memory by ~30%

Revisions (0)

No revisions yet.