3. Modern OOP, Dataclasses & Context Managers

Modern Data Modeling: @dataclass, Enum & Advanced Type Hints

Eliminate class boilerplate with @dataclass, replace error-prone magic strings using Enum, and write flexible static contracts with Union, Literal, Callable, and Protocol.

4 min readUpdated 2026-11-30
In This Lesson
  • Generate __init__, __repr__, and __eq__ automatically with @dataclass and frozen=True
  • Avoid mutable default bugs with field(default_factory=list)
  • Replace magic strings with Enum and model structural interfaces with Protocol

In Python Fundamentals, you wrote classes manually with def __init__(self, ...):. That works, but for data-holding classes it creates repetitive boilerplate (self.x = x, self.y = y, custom __repr__, custom __eq__).

Modern Python solves this cleanly with @dataclass, Enum, and expressive typing annotations.

Why It Matters: Before vs After

Compare a hand-written data class with a @dataclass—to get readable printing and value equality (c1 == c2), the manual version requires 15+ lines of error-prone boilerplate:

python
# Before: repetitive boilerplate + easy to forget __eq__ or __repr__
class CourseManual:
    def __init__(self, slug: str, title: str, hours: int = 10):
        self.slug = slug
        self.title = title
        self.hours = hours
    def __repr__(self) -> str:
        return f"CourseManual(slug={self.slug!r}, title={self.title!r}, hours={self.hours!r})"
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, CourseManual):
            return NotImplemented
        return (self.slug, self.title, self.hours) == (other.slug, other.title, other.hours)

# After: @dataclass generates all three methods from your type hints!
from dataclasses import dataclass, field

@dataclass
class Course:
    slug: str
    title: str
    hours: int = 10
    tags: list[str] = field(default_factory=list)

1. How @dataclass Generates Methods Under the Hood

@dataclass Auto-Generates Boilerplate Methods

@dataclass(frozen=True)

class Ticket:

id: int

priority: Priority

tags: tuple[str, ...]

__init__

Sets self fields

__repr__

Readable debug str

__eq__

Value comparison

__hash__

Dict/Set safe (frozen)

Declare typed fields once; @dataclass generates __init__, __repr__, __eq__, and optional immutability (frozen=True).

When Python evaluates @dataclass, it inspects your class's type annotations (__annotations__) at class-creation time and synthesizes:

  1. __init__: Assigns each field in declaration order (enforcing defaults and default_factory calls per instance).
  2. __repr__: Produces Course(slug='...', title='...', hours=10, tags=[]) for clean debugging.
  3. __eq__: Compares (self.slug, self.title, ...) tuple-by-tuple against another Course—unlike standard classes, which compare memory addresses (is)!
  4. Optional extras via flags: frozen=True blocks mutation and generates __hash__; order=True generates <, <=, >, >=; slots=True (3.10+) cuts memory per instance.

Two Crucial Dataclass Safeguards

  1. field(default_factory=list): Never write tags: list[str] = [] inside a dataclass—Python raises ValueError: mutable default <class 'list'> for field tags is not allowed so separate instances never accidentally share one list!
  2. frozen=True: Makes instances immutable (read-only) and hashable so they can live inside sets or serve as dict keys:
python
@dataclass(frozen=True)
class Coordinate:
    lat: float
    lon: float

2. Replacing Magic Strings with Enum

Compare fragile strings (status = "pending" vs "Pending" typo) against an explicit Enum (or StrEnum in Python 3.11+):

python
from enum import Enum

class OrderStatus(str, Enum):
    PENDING = "pending"
    PAID = "paid"
    CANCELLED = "cancelled"

status = OrderStatus.PAID
print(status.value)           # "paid"
print(status == "paid")       # True because it inherits from str!

Now your editor autocompletes valid statuses, and invalid states like OrderStatus("shipped") fail loudly with a ValueError at the boundary.

3. Advanced Type Hints: |, Literal, Callable, Protocol

Modern Python (3.10+) supports sleek, readable static contracts:

  • Union & Optional: int | None instead of verbose Optional[int]
  • Literal: Literal["asc", "desc"] restricts allowed constants for type checkers
  • Callable: Callable[[int, int], bool] describes a function taking two ints and returning a bool
  • Protocol (Structural Duck Typing): Any class with matching methods satisfies the Protocol—no inheritance needed!
python
from typing import Protocol

class Exportable(Protocol):
    def to_row(self) -> list[str]: ...

def export_csv(items: list[Exportable]) -> list[list[str]]:
    return [item.to_row() for item in items]

Decision Table: dict vs NamedTuple vs @dataclass

ContainerMutabilityMemory & SpeedBest Used When
dictMutableFlexible keys, no schemaDynamic/unstructured JSON payloads
NamedTupleImmutableLightest; unpacks like a tupleSmall fixed 2–4 field return values
@dataclassMutable (or frozen=True)Rich methods, defaults, slots=TrueDomain models, configs, typed records

Try It Yourself in the Playground

Python 3Try It Live: @dataclass, Enum & Protocol
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Create a @dataclass named ShoppingCart with owner: str and items: list[str] = field(default_factory=list), plus a method add(self, item: str) that appends to self.items. Verify two separate ShoppingCart instances do not share the same items list.

Quick Checkpoints

Check Your Understanding

Why does @dataclass forbid items: list[str] = [] and require field(default_factory=list)?

Check Your Understanding

What does @dataclass(frozen=True) give you?