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.
- 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:
# 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(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:
__init__: Assigns each field in declaration order (enforcing defaults anddefault_factorycalls per instance).__repr__: ProducesCourse(slug='...', title='...', hours=10, tags=[])for clean debugging.__eq__: Compares(self.slug, self.title, ...)tuple-by-tuple against anotherCourse—unlike standard classes, which compare memory addresses (is)!- Optional extras via flags:
frozen=Trueblocks mutation and generates__hash__;order=Truegenerates<,<=,>,>=;slots=True(3.10+) cuts memory per instance.
Two Crucial Dataclass Safeguards
field(default_factory=list): Never writetags: list[str] = []inside a dataclass—Python raisesValueError: mutable default <class 'list'> for field tags is not allowedso separate instances never accidentally share one list!frozen=True: Makes instances immutable (read-only) and hashable so they can live insidesets or serve asdictkeys:
@dataclass(frozen=True)
class Coordinate:
lat: float
lon: float2. Replacing Magic Strings with Enum
Compare fragile strings (status = "pending" vs "Pending" typo) against an explicit Enum (or StrEnum in Python 3.11+):
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 | Noneinstead of verboseOptional[int] - Literal:
Literal["asc", "desc"]restricts allowed constants for type checkers - Callable:
Callable[[int, int], bool]describes a function taking twoints and returning abool - Protocol (Structural Duck Typing): Any class with matching methods satisfies the
Protocol—no inheritance needed!
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
| Container | Mutability | Memory & Speed | Best Used When |
|---|---|---|---|
dict | Mutable | Flexible keys, no schema | Dynamic/unstructured JSON payloads |
NamedTuple | Immutable | Lightest; unpacks like a tuple | Small fixed 2–4 field return values |
@dataclass | Mutable (or frozen=True) | Rich methods, defaults, slots=True | Domain models, configs, typed records |
Try It Yourself in the Playground
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
Why does @dataclass forbid items: list[str] = [] and require field(default_factory=list)?
What does @dataclass(frozen=True) give you?