pythonintermediate

Frozen Dataclass for Immutable Objects

Create immutable value objects using frozen dataclasses with hash support and custom methods.

python
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.