On this page
Modern Data Modeling
Prev: Object-Oriented Programming (OOP) | Up: Intermediate Python & Software Engineering | Next: Error Handling and Context Managers
Rel: dataclasses, collections, enum, typing
Ref: docs.python.org — dataclasses | docs.python.org — enum
Tags: #public #python3 #tutorials #software-engineering #data-modeling
Contents
- > `@dataclass` (`dataclasses`)
- > `namedtuple` & `typing.NamedTuple`
- > Enumerations (`enum`)
- > Choosing the Right Construct
@dataclass (dataclasses)
[[stdlib_module/dataclasses|dataclasses]] auto-generates __init__, __repr__, __eq__, and optionally ordering (order=True), immutability (frozen=True), and memory-compact __slots__ (slots=True).
from dataclasses import dataclass, field, asdict, replace
@dataclass(frozen=True, slots=True)
class Task:
title: str
priority: int = 1
tags: tuple[str, ...] = field(default_factory=tuple)
def __post_init__(self) -> None:
if not 1 <= self.priority <= 5:
raise ValueError("priority must be between 1 and 5")
t1 = Task("Write docs", priority=2, tags=("wiki", "python"))
t2 = replace(t1, priority=1)
print(t2)
print(asdict(t2))
Use field(default_factory=list) for mutable defaults on non-frozen dataclasses so instances never share the same container.
namedtuple & typing.NamedTuple
Named tuples create lightweight, immutable, tuple-compatible records that support both positional unpacking and attribute access. Prefer [[stdlib_module/typing|typing.NamedTuple]] for clean type annotations and defaults.
from collections import namedtuple
from typing import NamedTuple
Point2D = namedtuple("Point2D", ["x", "y"])
p = Point2D(3, 4)
x, y = p
class Coordinate(NamedTuple):
lat: float
lon: float
label: str = "unnamed"
c = Coordinate(36.0395, -114.9817, "Henderson")
print(c.label, tuple(c))
Enumerations (enum)
[[stdlib_module/enum|enum]] defines fixed sets of symbolic constants with type safety, iteration, and bitwise flag support (Flag, IntFlag).
from enum import Enum, StrEnum, Flag, auto
class HttpStatus(Enum):
OK = 200
NOT_FOUND = 404
SERVER_ERROR = 500
class Environment(StrEnum):
DEV = "dev"
STAGING = "staging"
PROD = "prod"
class Permission(Flag):
READ = auto()
WRITE = auto()
EXEC = auto()
rw = Permission.READ | Permission.WRITE
print(HttpStatus.OK.value, Environment.PROD == "prod", Permission.READ in rw)
Choosing the Right Construct
@dataclass: Primary choice for domain models (mutable or frozen, defaults,__post_init__validation,slots=True).NamedTuple: Lightweight immutable records that must behave as tuples (unpacking, indexing, low memory).Enum/StrEnum/Flag: Closed sets of states, error codes, or bitmask permissions.
Linked from
- tuts/python3/tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering
- tuts/python3/tutorials/intermediate_python_and_software_engineering/error_handling_and_context_managers
- tuts/python3/tutorials/intermediate_python_and_software_engineering/modern_data_modeling
- tuts/python3/tutorials/intermediate_python_and_software_engineering/object_oriented_programming
Related notes
- tuts/python3/tutorials/intermediate_python_and_software_engineering Linked here; links to this page; shared tags: #tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering/error_handling_and_context_managers Linked here; links to this page; shared tags: #tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering/object_oriented_programming Linked here; links to this page; shared tags: #tutorials
- tuts/python3/tutorials links to this page; shared tags: #tutorials
- tuts/python3/stdlib_module/collections Linked here
- tuts/python3/stdlib_module/dataclasses Linked here
- tuts/python3/stdlib_module/enum Linked here
- tuts/python3/stdlib_module/typing Linked here
- tuts/c/tutorials shared tags: #tutorials
- tuts/c/tutorials/arena_allocator_pattern shared tags: #tutorials