Back to All Nuggets
Python python ⏱️ 2 min read
Production Implementation
Ask endoAI
from dataclasses import dataclass, field
from datetime import datetime
from decimal import Decimal
from typing import Optional

@dataclass(frozen=True, slots=True, kw_only=True)
class MpesaTransactionRecord:
    transaction_id: str
    phone_number: str
    amount: Decimal
    account_reference: str
    timestamp: datetime = field(default_factory=datetime.utcnow)
    status: str = 'COMPLETED'
    failure_reason: Optional[str] = None

    def __post_init__(self) -> None:
        if self.amount <= Decimal('0'):
            raise ValueError(f'Amount must be positive, got {self.amount}')
        if not self.phone_number.startswith('254') or len(self.phone_number) != 12:
            raise ValueError(f'Invalid Kenyan MSISDN: {self.phone_number}')

Replacing Plain Dictionaries with Type-Safe Python Dataclasses

Relying on loose dictionaries across Python applications causes runtime KeyError exceptions. Python's built-in dataclasses module provides an elegant, memory-efficient domain model structure.

  • frozen=True: Guarantees immutability and thread safety.
  • slots=True: Dramatically reduces memory overhead in high-throughput loops.
  • __post_init__: Enforces business domain validation on instantiation.

Accelerate Your Engineering Career

Get monthly masterclasses, exclusive code snippets, and direct architectural reviews.

Become a Supporter • KES 500 / Month