Dataclasses are a special feature in Python that help you create classes used mainly for storing data.
They reduce boilerplate code by automatically generating common methods like:
__init__()__repr__()__eq__()
Dataclasses were introduced in Python 3.7.
Why Use Dataclasses?
- Less code
- Cleaner syntax
- Automatic constructor creation
- Built-in comparison support
- Easy to read and maintain
Creating a Dataclass
To use dataclasses, import the dataclass decorator from the dataclasses module.
from dataclasses import dataclass@dataclass
class Student:
name: str
age: int
marks: floats1 = Student("Hira", 22, 85.5)
print(s1)
Output:
Student(name='Hira', age=22, marks=85.5)
Notice:
- No need to write
__init__() - No need to write
__str__() - Everything is automatically created
Equality Comparison
Dataclasses automatically support comparison.
s1 = Student("Hira", 22, 85.5)
s2 = Student("Hira", 22, 85.5)print(s1 == s2)
Output:
True
Default Values
You can provide default values.
from dataclasses import dataclass@dataclass
class Student:
name: str
age: int = 18
Using field() for Advanced Options
The field() function allows customization.
from dataclasses import dataclass, field@dataclass
class Student:
name: str
age: int
marks: float = field(default=0.0)
Frozen Dataclass (Immutable)
To make objects immutable:
from dataclasses import dataclass@dataclass(frozen=True)
class Student:
name: str
age: ints1 = Student("Hira", 22)
Now you cannot modify attributes.
Dataclass vs Normal Class
Normal Class
You manually write __init__()
More code
Manual comparison methods
Dataclass
Auto-generated methods
Less code
Built-in comparison
When to Use Dataclasses
- When class is mainly used to store data
- When you want clean and readable code
- When you need automatic comparison
Key Takeaway
Dataclasses simplify class creation for data storage.
They automatically generate important methods and make Python code cleaner, shorter, and easier to maintain.