Jotting one man's journey through software development, programming, and technology
dataclass◀️ Home
A dataclass is a class decorator (@dataclass) that automatically generates common methods like __init__, __repr__, and __eq__ based on class fields.
Use
dataclasswhen your class is primarily structured data with minimal custom behavior.
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int = 0
user = User("Pablo", 24)
print(user) # User(name='Pablo', age=24)
__init__: constructor. Creates the object and assigns field values.
User("Pablo", 24) sets name and age.__repr__: developer-friendly string representation of the object.
print(obj) (if no __str__), typing obj in REPL.User(name='Pablo', age=24).__eq__: equality comparison. Two instances are equal if all fields are equal.
==.User("Ana", 20) == User("Ana", 20) returns True.frozen=True: makes instances immutable.order=True: adds comparison methods (<, <=, etc.).field(...): customize defaults, metadata, and behavior per field.