Phase 2 of 25 · Topic 2.5

Custom Immutable Objects with NamedTuple & dataclass(frozen=True)

1Concept

`typing.NamedTuple` and `@dataclass(frozen=True)` create lightweight, self-documenting immutable data carrier classes. `NamedTuple` inherits from tuple, adding zero per-instance dict overhead while allowing field access by name.

2Architecture Diagram

NamedTuple:  Memory identical to tuple (compact C struct, no __dict__ overhead)
Frozen Data: Raises FrozenInstanceError on any mutation attempt!

3Code Example

Python 3.12
from typing import NamedTuple
from dataclasses import dataclass, FrozenInstanceError

class Coordinate(NamedTuple):
    latitude: float
    longitude: float

@dataclass(frozen=True)
class ServiceConfig:
    service_name: str
    port: int

coord = Coordinate(37.7749, -122.4194)
config = ServiceConfig("AuthService", 8080)

print(f"Coordinate: {coord.latitude}, {coord.longitude}")
print(f"Config: {config.service_name}:{config.port}")

try:
    config.port = 9000
except FrozenInstanceError as e:
    print(f"Mutation Blocked: {e}")

4Expected Output

Coordinate: 37.7749, -122.4194
Config: AuthService:8080
Mutation Blocked: cannot assign to field 'port'

5Key Takeaways

  • `NamedTuple` instances are indexable like tuples (`coord[0]`) and unpackable (`lat, lon = coord`).
  • `frozen=True` dataclasses automatically generate `__hash__()` based on their fields.
  • Ideal for thread-safe DTOs in concurrent and async applications.