On this page
  1. dataclasses
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Mutable Defaults, Validation (__post_init__) & replace()
  7. 2. Keyword-Only Fields & Serialization
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

dataclasses

Prev: curses | Up: stdlib_module | Next: datetime
Rel: sys, sysconfig, builtins, warnings, contextlib
Ref: docs.python.org — dataclasses
Tags: #public #python3 #stdlib


Import

import dataclasses

Overview

Code-generating decorator (@dataclass) that builds __init__, __repr__, __eq__, and optional ordering/hashing directly from standard type annotations. Reach for dataclasses for structured domain records, configs, and value objects; use TypedDict (in typing) when you specifically need plain dict instances.

Quick Start

from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Point:
    x: float
    y: float
    tags: tuple[str, ...] = ()

p = Point(1.0, 2.5, tags=("origin",))
assert p == Point(1.0, 2.5, tags=("origin",))

Implementation Walkthrough

1. Mutable Defaults, Validation (__post_init__) & replace()

Never assign a mutable list/dict directly as a default; use field(default_factory=...). Validate invariants in __post_init__ and derive updated copies of frozen instances with replace():

from dataclasses import dataclass, field, replace

@dataclass(frozen=True, slots=True)
class Task:
    title: str
    priority: int = 1
    labels: list[str] = field(default_factory=list)

    def __post_init__(self) -> None:
        if not self.title.strip():
            raise ValueError("title must be non-empty")
        if not 1 <= self.priority <= 5:
            raise ValueError("priority must be between 1 and 5")

t1 = Task("Ship docs", priority=2)
t2 = replace(t1, priority=1)
assert t1.priority == 2 and t2.priority == 1

2. Keyword-Only Fields & Serialization

from dataclasses import asdict, dataclass

@dataclass(kw_only=True, slots=True)
class Config:
    host: str = "127.0.0.1"
    port: int = 8000

assert asdict(Config(port=9000)) == {"host": "127.0.0.1", "port": 9000}

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes