Python Dataclasses
Create clean, readable classes for storing structured data with less boilerplate.
What are dataclasses?
Python's dataclasses module helps you define data-focused classes without manually writing common methods such as __init__() and __repr__().
person.py
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
person = Person("Aisha", 24)
print(person)Creating a dataclass
Add @dataclass above a class and declare its fields. Python generates useful methods automatically.
Fields and defaults
Fields can have type annotations and default values. This is useful for configuration objects, records and lightweight domain models.
defaults.py
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
active: bool = TrueKey takeaway
Dataclasses reduce repetitive code while keeping structured data models easy to read and maintain.
Ready to continue?