On this page
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
asdict()deep-copies everything recursively: It can be slow on large graphs and fails on unpicklable objects; write an explicit.to_dict()method for hot paths.- Frozen dataclasses don't freeze mutable attributes:
frozen=Trueprevents rebindingobj.labels = ..., notobj.labels.append(...); usetuplefor true immutability. - No runtime type enforcement: Type annotations are metadata only; validate values in
__post_init__or with a validator library. - Use
slots=True(Python 3.10+): Cuts memory overhead and catches accidental typo attribute assignments.
Common Functions
- dataclasses.asdict() —
asdict(obj, *, dict_factory=<class 'dict'>)— Return the fields of a dataclass instance as a new dictionary mapping field names to field values. - dataclasses.astuple() —
astuple(obj, *, tuple_factory=<class 'tuple'>)— Return the fields of a dataclass instance as a new tuple of field values. - dataclasses.dataclass() —
dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)— Add dunder methods based on the fields defined in the class. - dataclasses.field() —
field(*, default=<dataclasses._MISSING_TYPE object at 0x10967b380>, default_factory=<dataclasses._MISSING_TYPE object at 0x10967b380>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object at 0x10967b380>, doc=None)— Return an object to identify dataclass fields. - dataclasses.fields() —
fields(class_or_instance)— Return a tuple describing the fields of this dataclass. - dataclasses.is_dataclass() —
is_dataclass(obj)— Returns True if obj is a dataclass or an instance of a dataclass. - dataclasses.make_dataclass() —
make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False, module=None, decorator=<function dataclass at 0x109638720>)— Return a new dynamically created dataclass. - dataclasses.replace() —
replace(obj, /, **changes)— Return a new object replacing specified fields with new values.
Classes & Objects
- dataclasses.Field —
dataclasses.Fieldclass. - dataclasses.FrozenInstanceError —
dataclasses.FrozenInstanceErrorclass. (Methods:.add_note(),.with_traceback()) - dataclasses.InitVar —
dataclasses.InitVarclass.
Constants & Attributes
dataclasses.KW_ONLY(_KW_ONLY_TYPE) =<dataclasses._KW_ONLY_TYPE object at 0x10967b4d0>dataclasses.MISSING(_MISSING_TYPE) =<dataclasses._MISSING_TYPE object at 0x10967b380>
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/abc
- tuts/python3/stdlib_module/antigravity
- tuts/python3/stdlib_module/ast
- tuts/python3/stdlib_module/atexit
- tuts/python3/stdlib_module/builtins
- tuts/python3/stdlib_module/code
- tuts/python3/stdlib_module/codeop
- tuts/python3/stdlib_module/compileall
- tuts/python3/stdlib_module/contextlib
- tuts/python3/stdlib_module/curses
- tuts/python3/stdlib_module/dataclasses/asdict
- tuts/python3/stdlib_module/dataclasses/astuple
- tuts/python3/stdlib_module/dataclasses/dataclass
- tuts/python3/stdlib_module/dataclasses/field
- tuts/python3/stdlib_module/dataclasses/Field_class
- tuts/python3/stdlib_module/dataclasses/fields
- tuts/python3/stdlib_module/dataclasses/FrozenInstanceError
- tuts/python3/stdlib_module/dataclasses/InitVar
- tuts/python3/stdlib_module/dataclasses/is_dataclass
- tuts/python3/stdlib_module/dataclasses/make_dataclass
- tuts/python3/stdlib_module/dataclasses/replace
- tuts/python3/stdlib_module/datetime
- tuts/python3/stdlib_module/dis
- tuts/python3/stdlib_module/ensurepip
- tuts/python3/stdlib_module/gc
- tuts/python3/stdlib_module/importlib
- tuts/python3/stdlib_module/inspect
- tuts/python3/stdlib_module/keyword
- tuts/python3/stdlib_module/modulefinder
- tuts/python3/stdlib_module/opcode
- tuts/python3/stdlib_module/pickletools
- tuts/python3/stdlib_module/pkgutil
- tuts/python3/stdlib_module/py_compile
- tuts/python3/stdlib_module/pyclbr
- tuts/python3/stdlib_module/pyexpat
- tuts/python3/stdlib_module/runpy
- tuts/python3/stdlib_module/site
- tuts/python3/stdlib_module/sre_compile
- tuts/python3/stdlib_module/sre_constants
- tuts/python3/stdlib_module/sre_parse
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/symtable
- tuts/python3/stdlib_module/sys
- tuts/python3/stdlib_module/sysconfig
- tuts/python3/stdlib_module/tabnanny
- tuts/python3/stdlib_module/this
- tuts/python3/stdlib_module/token
- tuts/python3/stdlib_module/tokenize
- tuts/python3/stdlib_module/traceback
- tuts/python3/stdlib_module/venv
- tuts/python3/stdlib_module/warnings
- tuts/python3/stdlib_module/zipapp
- tuts/python3/stdlib_module/zipimport
- tuts/python3/tutorials/advanced_python_internals/python_object_mro_and_initialization
- tuts/python3/tutorials/intermediate_python_and_software_engineering
- tuts/python3/tutorials/intermediate_python_and_software_engineering/modern_data_modeling
Related notes
- tuts/python3/stdlib_module/builtins Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/curses Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses/asdict Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses/astuple Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses/dataclass Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses/field Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses/Field_class Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses/fields Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses/FrozenInstanceError Linked here; links to this page; shared tags: #stdlib