Dataclasses with Post-Init Processing
Use Python dataclasses with __post_init__ for computed fields, validation, and default factories.
from dataclasses import dataclass, field
from datetime import datetime
from uuid import uuid4
@dataclass
class Order:
customer_id: str
items: list[str]
unit_price: float
quantity: int = 1
id: str = field(default_factory=lambda: str(uuid4()))
created_at: datetime = field(default_factory=datetime.now)
total: float = field(init=False)
status: str = field(init=False, default="pending")
def __post_init__(self):
if self.quantity < 1:
raise ValueError("Quantity must be at least 1")
if self.unit_price < 0:
raise ValueError("Price cannot be negative")
self.total = round(self.unit_price * self.quantity, 2)
# Usage
order = Order(
customer_id="cust_123",
items=["Widget A"],
unit_price=19.99,
quantity=3,
)
print(f"Order {order.id}: ${order.total}")Use Cases
- Domain models
- Configuration objects
- DTO patterns
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Pydantic v2 Model Patterns
Define and validate data models with Pydantic v2 using field validators, computed fields, and serialization.
Data Validation with Pydantic
Validate and parse data records using Pydantic models with custom validators and error reporting.
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.