Dataclasses
suggest changeThe @dataclass decorator from the dataclasses module writes the boring parts of a class for you. You list the fields with type annotations, and it generates __init__, __repr__ and __eq__. If you ask for them, it also generates ordering methods, __hash__, __slots__ and __match_args__.
Dataclasses were added in Python 3.7. Later versions added more options:
| Version | Addition |
|---|---|
| 3.7 | @dataclass, field(), frozen, order, __post_init__, InitVar, asdict(), astuple(), replace() |
| 3.10 | kw_only=True, KW_ONLY, slots=True, match_args |
| 3.11 | weakref_slot=True |
| 3.13 | copy.replace() works on dataclasses |
| 3.14 | field(doc=...) |
All examples were run with Python 3.13, except the doc= example, which needs Python 3.14.
A first dataclass
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
p = Point(1.5, 2.0)
print(p)
print(p.x, p.y)
print(p == Point(1.5, 2.0))
print(p is Point(1.5, 2.0))
p.x = 10
print(p)
Point(x=1.5, y=2.0)
1.5 2.0
True
False
Point(x=10, y=2.0)
Without the decorator you would write this yourself:
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x!r}, y={self.y!r})"
def __eq__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
Fields are compared in the order they are declared. __eq__ returns True only when both objects have exactly the same class.
The type annotations are not checked at runtime. Point("a", None) works fine. Use a type checker such as mypy or pyright to catch mistakes like that.
Only annotated class attributes become fields. An attribute without an annotation stays a plain class attribute:
from dataclasses import dataclass
@dataclass
class Config:
retries = 3 # no annotation: a plain class attribute, not a field
timeout: float = 5.0
print(Config())
print(Config.retries)
Config(timeout=5.0)
3
To declare a class-level constant that also has a type annotation, use typing.ClassVar[int]. Dataclasses skip ClassVar attributes too.
Default values and field()
A plain default works for immutable values like numbers, strings and tuples. For anything else, and to change how a single field behaves, use field():
from dataclasses import dataclass, field
@dataclass
class Order:
customer: str
items: list[str] = field(default_factory=list)
discount: float = 0.0
note: str = field(default="", repr=False)
internal_id: int = field(default=0, compare=False)
a = Order("alice")
b = Order("bob")
a.items.append("book")
print(a)
print(b)
print(Order("x", internal_id=1) == Order("x", internal_id=2))
Order(customer='alice', items=['book'], discount=0.0, internal_id=0)
Order(customer='bob', items=[], discount=0.0, internal_id=0)
True
The most useful field() arguments:
| Argument | Meaning |
|---|---|
default |
default value |
default_factory |
a zero-argument callable that is called for every new instance (list, dict, lambda: [1, 2]) |
init=False |
leave the field out of __init__ (set it in __post_init__ instead) |
repr=False |
hide the field in __repr__, for example for secrets or large blobs |
compare=False |
ignore the field in __eq__ and in ordering |
hash |
include the field in __hash__ or not (defaults to the value of compare) |
kw_only=True |
make the field keyword-only (3.10+) |
metadata |
a read-only dict for your own use, which dataclasses ignores |
Dataclasses protect you from the mutable default argument trap. A list, dict or set used as a plain default raises an error when the class is defined. Dataclasses also check field order. A field without a default can't come after a field that has one, because the generated __init__ would not be valid Python:
from dataclasses import dataclass
try:
@dataclass
class Bad:
tags: list = []
except ValueError as e:
print("ValueError:", e)
try:
@dataclass
class Bad2:
a: int = 0
b: int
except TypeError as e:
print("TypeError:", e)
ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory
TypeError: non-default argument 'b' follows default argument 'a'
The mutable-default check only catches unhashable values (list, dict, set and similar). It doesn't catch an instance of your own mutable class, so use default_factory for those too.
Validation and derived fields with post_init
The generated __init__ calls __post_init__() when it's done, if you define one. Use it to validate arguments or compute fields that are not passed in:
from dataclasses import dataclass, field
@dataclass
class Rect:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
if self.width < 0 or self.height < 0:
raise ValueError("width and height must be >= 0")
self.area = self.width * self.height
print(Rect(3, 4))
try:
Rect(-1, 2)
except ValueError as e:
print("ValueError:", e)
Rect(width=3, height=4, area=12)
ValueError: width and height must be >= 0
Note that area is computed only once. If you change width later, area is stale. For values that must always stay in sync, use a property instead of a field.
InitVar: init-only arguments
Sometimes __init__ needs an argument that should not be stored on the object. Annotate it with InitVar[T]. It's passed to __post_init__ as an extra argument and is not a field:
from dataclasses import dataclass, field, InitVar
import hashlib
@dataclass
class User:
name: str
password: InitVar[str]
password_hash: str = field(init=False, repr=False)
def __post_init__(self, password: str):
self.password_hash = hashlib.sha256(password.encode()).hexdigest()[:16]
u = User("alice", "s3cret")
print(u)
print(u.password_hash)
print(hasattr(u, "password"))
User(name='alice')
1ec1c26b50d5d3c5
False
The example only shows how InitVar works. To store real passwords, use a slow password hash such as hashlib.scrypt, argon2 or bcrypt.
Immutable dataclasses: frozen=True
With frozen=True, assigning to a field after construction raises FrozenInstanceError. Because their value can't change, frozen instances also get a __hash__, so they can be dict keys and set members:
from dataclasses import dataclass, FrozenInstanceError
@dataclass(frozen=True)
class Color:
r: int
g: int
b: int
red = Color(255, 0, 0)
try:
red.r = 0
except FrozenInstanceError as e:
print("FrozenInstanceError:", e)
palette = {red: "red", Color(0, 0, 255): "blue"}
print(palette[Color(255, 0, 0)])
print(hash(red) == hash(Color(255, 0, 0)))
FrozenInstanceError: cannot assign to field 'r'
red
True
The freeze is shallow. A frozen dataclass that holds a list still lets you append to that list. Use tuples or frozenset for collection fields if you need real immutability.
A frozen dataclass's __post_init__ can't assign with self.x = ... either. To set a derived field, go through object.__setattr__:
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Temperature:
celsius: float
fahrenheit: float = field(init=False)
def __post_init__(self):
object.__setattr__(self, "fahrenheit", self.celsius * 9 / 5 + 32)
print(Temperature(100))
Temperature(celsius=100, fahrenheit=212.0)
Equality and hashing rules
The default @dataclass (with eq=True and frozen=False) sets __hash__ to None. Mutable objects whose hash could change would corrupt dicts and sets, so their instances are unhashable:
from dataclasses import dataclass
@dataclass
class Mutable:
x: int
@dataclass(frozen=True)
class Frozen:
x: int
@dataclass(unsafe_hash=True)
class Forced:
x: int
print(Mutable.__hash__, Frozen.__hash__ is not None, Forced.__hash__ is not None)
try:
{Mutable(1)}
except TypeError as e:
print("TypeError:", e)
print({Frozen(1), Frozen(1), Frozen(2)})
None True True
TypeError: unhashable type: 'Mutable'
{Frozen(x=1), Frozen(x=2)}
unsafe_hash=True forces a hash on a mutable class. It's only safe if you never change a field while the object is inside a set or used as a dict key. In most cases frozen=True is the better choice.
With eq=False the class keeps object's identity-based __eq__ and __hash__.
Ordering: order=True
order=True generates __lt__, __le__, __gt__ and __ge__. They compare the fields as tuples, in declaration order. Fields with compare=False are skipped:
from dataclasses import dataclass, field
@dataclass(order=True)
class Version:
major: int
minor: int
patch: int
label: str = field(default="", compare=False)
versions = [Version(1, 10, 0), Version(1, 2, 3, "beta"), Version(0, 9, 9)]
print(sorted(versions))
print(Version(1, 2, 3) < Version(1, 10, 0))
print(max(versions))
[Version(major=0, minor=9, patch=9, label=''), Version(major=1, minor=2, patch=3, label='beta'), Version(major=1, minor=10, patch=0, label='')]
True
Version(major=1, minor=10, patch=0, label='')
If you want to sort by something other than field order, add a hidden first field that holds the sort key:
from dataclasses import dataclass, field
@dataclass(order=True)
class Task:
sort_key: tuple = field(init=False, repr=False)
title: str
priority: int
def __post_init__(self):
self.sort_key = (-self.priority, self.title)
tasks = [Task("write docs", 1), Task("fix bug", 3), Task("deploy", 3)]
for t in sorted(tasks):
print(t)
Task(title='deploy', priority=3)
Task(title='fix bug', priority=3)
Task(title='write docs', priority=1)
sort_key has no default and comes before title, but that's allowed. Fields with init=False don't appear in __init__, so they don't count for the "non-default after default" rule.
For a single sort you can also pass key= to sorted(). See Make custom classes orderable for writing comparison methods by hand.
Keyword-only fields: kw_only and KW_ONLY
Positional calls like Connection("db", 5432, "admin", "secret", True) are hard to read and break when someone reorders fields. Since Python 3.10, kw_only=True makes every field keyword-only:
from dataclasses import dataclass
@dataclass(kw_only=True)
class Connection:
host: str
port: int = 5432
user: str
c = Connection(host="db.local", user="admin")
print(c)
try:
Connection("db.local", 5432, "admin")
except TypeError as e:
print("TypeError:", e)
Connection(host='db.local', port=5432, user='admin')
TypeError: Connection.__init__() takes 1 positional argument but 4 were given
Keyword-only fields can be listed in any order. Here the required user comes after port, which has a default.
To mix positional and keyword-only fields, use the KW_ONLY sentinel. Every field after it is keyword-only. You can also set kw_only=True on a single field():
from dataclasses import dataclass, field, KW_ONLY
@dataclass
class Request:
method: str
url: str
_: KW_ONLY
timeout: float = 10.0
headers: dict[str, str] = field(default_factory=dict)
verify: bool
r = Request("GET", "https://example.com", verify=False, timeout=2.5)
print(r)
@dataclass
class Job:
name: str
retries: int = field(default=3, kw_only=True)
command: str = ""
print(Job("backup", "tar czf"))
print(Job("backup", "tar czf", retries=5))
Request(method='GET', url='https://example.com', timeout=2.5, headers={}, verify=False)
Job(name='backup', retries=3, command='tar czf')
Job(name='backup', retries=5, command='tar czf')
The _: KW_ONLY pseudo-field is not a real field. The name _ is just a convention.
Inheritance
A dataclass subclass inherits the parent's fields and adds its own fields after them:
from dataclasses import dataclass
@dataclass
class Base:
id: int
created: str = "today"
@dataclass
class Child(Base):
name: str = ""
tags: tuple[str, ...] = ()
print(Child(1, "yesterday", "x"))
try:
@dataclass
class Broken(Base):
name: str
except TypeError as e:
print("TypeError:", e)
@dataclass(kw_only=True)
class Fixed(Base):
name: str
print(Fixed(1, name="ok"))
Child(id=1, created='yesterday', name='x', tags=())
TypeError: non-default argument 'name' follows default argument 'created'
Fixed(id=1, created='today', name='ok')
Before 3.10, the "base class has defaults, so every subclass field needs a default" problem was the most common complaint about dataclasses. With kw_only, the subclass's fields move to the end of __init__ as keyword-only arguments, so they can be required again. In Fixed, kw_only=True applies only to the fields declared in Fixed. id and created stay positional.
Lower memory and no typos: slots=True
A regular instance stores its attributes in a per-instance __dict__. Since Python 3.10, slots=True generates __slots__ instead. The objects use less memory, attribute access is a bit faster, and assigning to a misspelled attribute fails instead of silently creating a new one:
import sys
from dataclasses import dataclass
@dataclass
class Plain:
x: int
y: int
@dataclass(slots=True)
class Slotted:
x: int
y: int
p, s = Plain(1, 2), Slotted(1, 2)
print(Slotted.__slots__)
print(hasattr(p, "__dict__"), hasattr(s, "__dict__"))
print(sys.getsizeof(p) + sys.getsizeof(p.__dict__), sys.getsizeof(s))
p.z = 3 # silently adds a new attribute
try:
s.z = 3
except AttributeError as e:
print("AttributeError:", e)
('x', 'y')
True False
344 48
AttributeError: 'Slotted' object has no attribute 'z' and no __dict__ for setting new attributes
Things to know about slots=True:
- The decorator has to create a new class, because
__slots__can't be added to a class that already exists. Code that keeps a reference to the original class (some other decorators do) will see a different object. - Slotted instances can't be weakly referenced unless you also pass
weakref_slot=True(3.11+). - You can't use
functools.cached_propertyon a slotted class, because it needs__dict__. - A field default is stored in
__init__rather than as a class attribute, because__slots__and a class attribute with the same name conflict.@dataclasstakes care of that for you.
@dataclass(frozen=True, slots=True) is a good default for small value objects.
Pattern matching: match_args
Dataclasses generate __match_args__, a tuple of the field names that can be passed to __init__ positionally. This lets you use positional class patterns in match:
from dataclasses import dataclass
@dataclass
class Move:
x: int
y: int
@dataclass
class Quit:
reason: str = ""
print(Move.__match_args__)
def handle(cmd):
match cmd:
case Move(0, 0):
return "stay"
case Move(x, 0):
return f"horizontal {x}"
case Move(x=x, y=y):
return f"move to {x},{y}"
case Quit(reason):
return f"quit: {reason or 'no reason'}"
for c in [Move(0, 0), Move(5, 0), Move(1, 2), Quit()]:
print(handle(c))
('x', 'y')
stay
horizontal 5
move to 1,2
quit: no reason
Keyword-only fields are left out of __match_args__. Pass match_args=False to skip generating it.
Converting to dicts and tuples: asdict and astuple
asdict() and astuple() convert an instance recursively. Nested dataclasses, lists, tuples and dicts are converted too, and copied deeply. That makes JSON serialization a one-liner:
import json
from dataclasses import dataclass, field, asdict, astuple
@dataclass
class Address:
city: str
zip: str
@dataclass
class Person:
name: str
age: int
addresses: list[Address] = field(default_factory=list)
p = Person("Alice", 30, [Address("Warsaw", "00-001"), Address("Krakow", "30-001")])
d = asdict(p)
print(d)
print(astuple(p))
print(json.dumps(d))
def person_from_dict(d: dict) -> Person:
return Person(d["name"], d["age"], [Address(**a) for a in d["addresses"]])
print(person_from_dict(d) == p)
{'name': 'Alice', 'age': 30, 'addresses': [{'city': 'Warsaw', 'zip': '00-001'}, {'city': 'Krakow', 'zip': '30-001'}]}
('Alice', 30, [('Warsaw', '00-001'), ('Krakow', '30-001')])
{"name": "Alice", "age": 30, "addresses": [{"city": "Warsaw", "zip": "00-001"}, {"city": "Krakow", "zip": "30-001"}]}
True
There is no built-in reverse operation. Person(**d) works for flat classes, but nested ones need code like person_from_dict. If you need validation and nested parsing from JSON, use a library such as pydantic or cattrs. Both understand dataclasses.
asdict() deep-copies everything, which is slow for big objects. For a shallow dict use {f.name: getattr(obj, f.name) for f in fields(obj)}.
Copying with changes: replace() and copy.replace()
dataclasses.replace(obj, **changes) creates a new instance with some fields changed. It's the usual way to "modify" a frozen dataclass. Since Python 3.13, dataclasses also implement __replace__, so the generic copy.replace() works with them, as well as with named tuples, datetime objects and other types:
import copy
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Settings:
debug: bool = False
level: str = "INFO"
workers: int = 4
base = Settings()
dev = replace(base, debug=True, level="DEBUG")
print(base)
print(dev)
print(copy.replace(base, workers=8)) # Python 3.13+
try:
replace(base, colour="red")
except TypeError as e:
print("TypeError:", e)
Settings(debug=False, level='INFO', workers=4)
Settings(debug=True, level='DEBUG', workers=4)
Settings(debug=False, level='INFO', workers=8)
TypeError: Settings.__init__() got an unexpected keyword argument 'colour'
replace() creates the new object by calling __init__, so __post_init__ runs again and validation still applies. Fields with init=False can't be passed to it. They are recomputed by __post_init__, or reset to their default.
Introspection: fields(), is_dataclass() and make_dataclass()
from dataclasses import MISSING, dataclass, field, fields, is_dataclass, make_dataclass
@dataclass
class Item:
name: str
price: float = 0.0
tags: list[str] = field(default_factory=list, metadata={"help": "free-form labels"})
for f in fields(Item):
default = "<required>" if f.default is MISSING else repr(f.default)
if f.default_factory is not MISSING:
default = f"factory {f.default_factory.__name__}()"
print(f"{f.name:6} {str(f.type):18} {default:16} {f.metadata}")
print(is_dataclass(Item), is_dataclass(Item("x")), is_dataclass(dict))
Point3 = make_dataclass("Point3", [("x", int), ("y", int), ("z", int, 0)], frozen=True)
print(Point3(1, 2))
name <class 'str'> <required> {}
price <class 'float'> 0.0 {}
tags list[str] factory list() {'help': 'free-form labels'}
True True False
Point3(x=1, y=2, z=0)
fields() is what generic code like serializers, CLI argument builders and ORMs uses to inspect a dataclass. metadata is where you put per-field information for that kind of code. make_dataclass() builds a class at runtime, for example from a schema.
Python 3.14 adds a doc argument to field(). It is stored on the Field object and, for slotted classes, in __slots__, so help() can show it:
from dataclasses import dataclass, field, fields
@dataclass(slots=True)
class Server:
host: str = field(doc="Host name or IP address")
port: int = field(default=443, doc="TCP port")
for f in fields(Server):
print(f"{f.name}: {f.doc}")
print(Server.__slots__)
host: Host name or IP address
port: TCP port
{'host': 'Host name or IP address', 'port': 'TCP port'}
On 3.13 and earlier this fails with TypeError: field() got an unexpected keyword argument 'doc'.
Dataclass vs namedtuple vs NamedTuple
collections.namedtuple and typing.NamedTuple also create small record classes, but their instances are tuples:
from collections import namedtuple
from typing import NamedTuple
from dataclasses import dataclass
PointNT = namedtuple("PointNT", ["x", "y"])
class PointTN(NamedTuple):
x: int
y: int
@dataclass(frozen=True, slots=True)
class PointDC:
x: int
y: int
for P in (PointNT, PointTN, PointDC):
p = P(1, 2)
try:
x, y = p
unpack = "yes"
except TypeError:
unpack = "no"
print(f"{P.__name__}: repr={p!r} tuple={isinstance(p, tuple)} "
f"unpack={unpack} eq_tuple={p == (1, 2)}")
PointNT: repr=PointNT(x=1, y=2) tuple=True unpack=yes eq_tuple=True
PointTN: repr=PointTN(x=1, y=2) tuple=True unpack=yes eq_tuple=True
PointDC: repr=PointDC(x=1, y=2) tuple=False unpack=no eq_tuple=False
| namedtuple / NamedTuple | dataclass | |
|---|---|---|
| Mutable | no | yes (or frozen=True) |
Is a tuple (indexing, unpacking, == (1, 2)) |
yes | no |
Mutable defaults (default_factory) |
no | yes |
__post_init__ validation |
no | yes |
| Ordering | always (tuple ordering) | opt-in with order=True |
| Keyword-only fields, inheritance of fields | no | yes |
| Memory | small | small with slots=True |
Use a named tuple when the value really is a tuple: a function returning several values, a CSV row, or code that unpacks it. Use a dataclass for everything else, especially when the class will grow methods, defaults or validation.
For nesting dataclasses inside other classes, see Nested classes.
Quick reference
@dataclass(
init=True, # generate __init__
repr=True, # generate __repr__
eq=True, # generate __eq__
order=False, # generate __lt__, __le__, __gt__, __ge__
unsafe_hash=False, # force __hash__ on a mutable class
frozen=False, # assigning to fields raises FrozenInstanceError
match_args=True, # generate __match_args__ (3.10+)
kw_only=False, # all fields keyword-only (3.10+)
slots=False, # generate __slots__ (3.10+)
weakref_slot=False, # add __weakref__ slot when slots=True (3.11+)
)