MyInternships.in

Python OOP

Python Dataclasses

The @dataclass decorator automatically writes common boilerplate methods like __init__, __repr__ and __eq__ for classes that mainly just hold data.


Why Dataclasses?

Many classes exist purely to store a group of related values. Writing __init__ and __repr__ by hand for these is repetitive; the dataclasses module removes that boilerplate.

A basic dataclass
Python
from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1

p = Product("Notebook", 45.5)
print(p)
Output
Output
Product(name='Notebook', price=45.5, quantity=1)

@dataclass automatically generates __init__ (using the type-annotated fields), a readable __repr__ for printing, and __eq__ for comparing two instances field by field.

default_factory for Mutable Defaults

You cannot give a field a mutable default like [] directly. Instead, use field(default_factory=list) to safely create a fresh list or dictionary for each new object.

Using default_factory
Python
from dataclasses import dataclass, field

@dataclass
class Cart:
    items: list = field(default_factory=list)

c1 = Cart()
c1.items.append("Pen")
c2 = Cart()
print(c1.items, c2.items)
Output
Output
['Pen'] []

Frozen (Immutable) Dataclasses

Passing frozen=True makes instances immutable — once created, their fields cannot be reassigned, which is useful for representing fixed values safely.

A frozen dataclass
Python
@dataclass(frozen=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
p.x = 5
Output
Output
dataclasses.FrozenInstanceError: cannot assign to field 'x'
💡

Reach for @dataclass whenever a class is mostly about storing structured data with little custom behaviour — it keeps your code short and consistent.

FeatureHow
Auto __init__/__repr__/__eq__@dataclass on the class
Default valuefield_name: type = value
Safe mutable defaultfield(default_factory=list)
Immutability@dataclass(frozen=True)

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships