Dataclasses
Dataclasses auto-generate __init__, __repr__, __eq__, and more. They're the easiest way to create data-holding classes in modern Python.
15 min•By Priygop Team•Updated 2026
Dataclasses
Dataclasses
from dataclasses import dataclass, field
from typing import List
# Basic dataclass
@dataclass
class Point:
x: float
y: float
p1 = Point(3, 4)
p2 = Point(3, 4)
print(p1) # Point(x=3, y=4)
print(p1 == p2) # True (auto __eq__!)
# With defaults and methods
@dataclass
class User:
name: str
email: str
age: int = 0
active: bool = True
tags: List[str] = field(default_factory=list)
def greet(self):
return f"Hello, {self.name}!"
user = User("Alice", "alice@email.com", 25)
user.tags.append("python")
print(user)
print(user.greet())
# Frozen (immutable) dataclass
@dataclass(frozen=True)
class Config:
host: str = "localhost"
port: int = 8080
debug: bool = False
config = Config()
print(config)
# config.port = 3000 # FrozenInstanceError!
# Ordered dataclass
@dataclass(order=True)
class Student:
gpa: float
name: str = field(compare=False)
students = [Student(3.8, "Alice"), Student(3.5, "Bob"), Student(3.9, "Charlie")]
for s in sorted(students):
print(f" {s.name}: {s.gpa}")
# Post-init processing
@dataclass
class Product:
name: str
price: float
quantity: int
total: float = field(init=False)
def __post_init__(self):
self.total = self.price * self.quantity
product = Product("Widget", 9.99, 5)
print(f"{product.name}: ${product.total:.2f}")Tip
Tip
Use Enum for fixed sets of values (colors, statuses). Use NamedTuple for lightweight immutable data. Use Protocol for structural typing.
Diagram
Loading diagram…
@dataclass auto-generates __init__, __repr__, __eq__
Common Mistake
Warning
Using magic strings ('active', 'pending') instead of Enums. Enums prevent typos and provide IDE autocomplete.
Quick Quiz
Practice Task
Note
(1) Create a Status enum with values. (2) Use NamedTuple for a Point. (3) Define a Protocol for duck typing.