dataclasses
from dataclasses import dataclass, field Added in v3.7 · Updated March 13, 2026 · Modules
stdlib classes decorator data-structures object-oriented
The dataclasses module simplifies creating classes that primarily store data. Introduced in Python 3.7 via PEP 557, it automatically generates __init__, __repr__, __eq__, and other special methods based on class attributes defined with the field() function.
The @dataclass Decorator
The main decorator that transforms a class into a dataclass.
@dataclass
Syntax
@dataclass(*, init=True, repr=True, eq=True, frozen=False, match_args=True, kw_only=False, slots=False)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
init | bool | True | Generate __init__ method |
repr | bool | True | Generate __repr__ method |
eq | bool | True | Generate __eq__ method |
frozen | bool | False | If True, fields cannot be modified after creation |
match_args | bool | True | Generate __match_args__ for pattern matching |
kw_only | bool | False | If True, all fields are keyword-only in __init__ |
slots | bool | False | Generate __slots__ for memory efficiency |
Examples
Basic dataclass
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
p = Point(3.0, 4.0)
print(p)
# Point(x=3.0, y=4.0)
print(p.x, p.y)
# 3.0 4.0
print(p == Point(3.0, 4.0))
# True
Frozen dataclass (immutable)
from dataclasses import dataclass
@dataclass(frozen=True)
class RGB:
red: int
green: int
blue: int
color = RGB(255, 128, 0)
# color.red = 0 # Raises FrozenInstanceError
Dataclass with default values
from dataclasses import dataclass, field
from typing import List
@dataclass
class Person:
name: str
age: int = 0
hobbies: List[str] = field(default_factory=list)
person = Person("Alice")
print(person)
# Person(name='Alice', age=0, hobbies=[])
person.hobbies.append("reading")
print(person.hobbies)
# ['reading']
The field() Function
Use field() to customize individual field behavior.
field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
default | value | MISSING | Default value for the field |
default_factory | callable | MISSING | Function that returns the default value |
init | bool | True | Include in __init__ |
repr | bool | True | Include in __repr__ |
hash | bool or None | None | Include in __hash__ |
compare | bool | True | Include in comparison methods |
metadata | dict or None | None | Custom data accessible via field.metadata |
Examples
Field with default factory
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class LogEntry:
message: str
timestamp: datetime = field(default_factory=datetime.now)
tags: list = field(default_factory=list)
log = LogEntry("Application started")
print(log.timestamp)
# 2024-01-15 10:30:45.123456
Field with repr=False
from dataclasses import dataclass, field
@dataclass
class User:
username: str
password_hash: str = field(repr=False)
user = User("john", "hashed_password_here")
print(user)
# User(username='john')
Module Functions
asdict()
Convert a dataclass instance to a dictionary.
from dataclasses import dataclass, asdict
@dataclass
class Point:
x: int
y: int
p = Point(10, 20)
print(asdict(p))
# {'x': 10, 'y': 20}
astuple()
Convert a dataclass instance to a tuple.
from dataclasses import astuple
print(astuple(p))
# (10, 20)
replace()
Create a copy with some fields modified.
from dataclasses import replace
p2 = replace(p, x=100)
print(p2)
# Point(x=100, y=20)
print(p) # Original unchanged
# Point(x=10, y=20)
Common Patterns
Post-init processing
Use __post_init__ to process fields after initialization:
from dataclasses import dataclass
@dataclass
class Circle:
radius: float
diameter: float = 0.0
def __post_init__(self):
self.diameter = self.radius * 2
c = Circle(5.0)
print(c.diameter)
# 10.0
Validation in dataclasses
from dataclasses import dataclass, field
@dataclass
class Account:
balance: float = field(default=0.0)
def __post_init__(self):
if self.balance < 0:
raise ValueError("Balance cannot be negative")
# Account(balance=-100) # Raises ValueError
Inheritance with dataclasses
from dataclasses import dataclass
@dataclass
class Animal:
name: str
species: str
@dataclass
class Dog(Animal):
breed: str = "Unknown"
bark_volume: int = 5
dog = Dog("Buddy", "Canis familiaris", "Golden Retriever", 8)
print(dog)
# Dog(name='Buddy', species='Canis familiaris', breed='Golden Retriever', bark_volume=8)