pythonintermediate
Frozen Dataclass for Immutable Objects
Create immutable value objects using frozen dataclasses with hash support and custom methods.
pythonPress ⌘/Ctrl + Shift + C to copy
from dataclasses import dataclass, replace
from typing import Self
@dataclass(frozen=True, slots=True)
class Money:
amount: int # cents
currency: str = "USD"
def __post_init__(self) -> None:
if self.amount < 0:
raise ValueError("Amount cannot be negative")
@classmethod
def from_dollars(cls, dollars: float, currency: str = "USD") -> Self:
return cls(amount=round(dollars * 100), currency=currency)
@property
def dollars(self) -> float:
return self.amount / 100
def add(self, other: Self) -> Self:
if self.currency != other.currency:
raise ValueError(f"Cannot add {self.currency} and {other.currency}")
return replace(self, amount=self.amount + other.amount)
def __str__(self) -> str:
return f"{self.currency} {self.dollars:.2f}"
price = Money.from_dollars(29.99)
tax = Money.from_dollars(2.40)
total = price.add(tax)
print(total) # USD 32.39
# Frozen = hashable, usable in sets / dict keys
prices = {Money(999, "USD"): "Basic", Money(1999, "USD"): "Pro"}Use Cases
- value objects
- financial calculations
- immutable data
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonintermediate
Python Dataclass Advanced Patterns
Advanced dataclass usage with validation, post-init processing, slots, and frozen instances.
Best for: Type-safe data models without ORMs
#python#dataclass
pythonintermediate
Dataclass with __post_init__ Validation
Add custom validation to Python dataclasses using __post_init__.
Best for: Input validation
#python#dataclass
pythonintermediate
Dataclass
Advanced Python pattern: dataclass
Best for: advanced programming
#python#advanced