On this page
dataclasses.dataclass
Prev: dataclasses.astuple | Up: dataclasses | Next: dataclasses.field
Rel: dataclasses.asdict, dataclasses.astuple, dataclasses.field, dataclasses.Field
Ref: docs.python.org — dataclasses.dataclass
Tags: #public #python3 #stdlib #dataclasses
Import
import dataclasses
from dataclasses import dataclass
Signature & Overview
dataclasses.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.
Usage
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class Config:
host: str = "localhost"
port: int = 8080
tags: tuple[str, ...] = field(default_factory=tuple)
cfg = Config(port=9000)
assert cfg.host == "localhost" and cfg.port == 9000
Gotchas
- Never use mutable defaults directly:
items: list[int] = []raisesValueError—usefield(default_factory=list). frozen=Trueenables hashing: Unfrozen dataclasses with defaulteq=Trueare unhashable (__hash__ = None).slots=True(Python 3.10+): Cuts per-instance memory and speeds attribute access, though it prevents dynamic attributes.
REPL Inspect
from dataclasses import dataclass
help(dataclass)
Linked from
- tuts/python3/stdlib_module/dataclasses
- tuts/python3/stdlib_module/dataclasses/asdict
- tuts/python3/stdlib_module/dataclasses/astuple
- 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
Related notes
- tuts/python3/stdlib_module/dataclasses/asdict Linked here; links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/astuple Linked here; links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/field Linked here; links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/Field_class Linked here; links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses/fields links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/FrozenInstanceError links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/InitVar links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/is_dataclass links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/make_dataclass links to this page; shared tags: #dataclasses, #stdlib