PyLearn
PyLearnLevel 6Lesson 55
LESSON 55

Python Dataclasses

Create clean, readable classes for storing structured data with less boilerplate.

Intermediate 10 min
01 · INTRODUCTION

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)
02 · SYNTAX

Creating a dataclass

Add @dataclass above a class and declare its fields. Python generates useful methods automatically.

03 · FIELDS

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 = True
04 · SUMMARY

Key takeaway

Dataclasses reduce repetitive code while keeping structured data models easy to read and maintain.

Ready to continue?