In Python, dataclass is a feature introduced in Python 3.7 that helps you create classes mainly used for storing data with less boilerplate code.
Instead of writing long __init__, __repr__, and other methods manually, Python automatically generates them for you.
🔹 What is a Dataclass in Python?
A dataclass is:
A special class used to store data, where Python automatically generates common methods like
__init__(),__repr__(), and__eq__().
In simple words:
- It is a shortcut for creating data-focused classes
- Reduces repetitive code
🔹 Why Use Dataclass?
Dataclasses help you:
- ✔ Reduce boilerplate code
-
✔ Automatically create constructor (
__init__) -
✔ Auto-generate readable output (
__repr__) -
✔ Compare objects easily (
__eq__) - ✔ Improve code clarity
🔹 Importing Dataclass
To use dataclass, import it from dataclasses module:
from dataclasses import dataclass
🔹 Basic Dataclass Example
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
Using the class:
s1 = Student("John", 20)
print(s1)
Output:
Student(name='John', age=20)
👉 Python automatically created the constructor and print format.
🔹 Without Dataclass (Normal Class)
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Student(name={self.name}, age={self.age})"
👉 Compare this with dataclass — much more code!
🔹 Dataclass with Default Values
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float = 0.0
stock: int = 0
Usage:
p1 = Product("Laptop", 1000)
p2 = Product("Mouse")
print(p1)
print(p2)
🔹 Output:
Product(name='Laptop', price=1000, stock=0)
Product(name='Mouse', price=0.0, stock=0)
🔹 Dataclass Comparison Feature
Dataclasses automatically support comparison.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
Usage:
p1 = Point(1, 2)
p2 = Point(1, 2)
p3 = Point(2, 3)
print(p1 == p2)
print(p1 == p3)
Output:
True
False
🔹 Dataclass with Post-Init Processing
You can add extra logic using __post_init__.
from dataclasses import dataclass
@dataclass
class Employee:
name: str
salary: float
def __post_init__(self):
if self.salary < 0:
raise ValueError("Salary cannot be negative")
Usage:
e = Employee("Alice", 5000)
print(e)
🔹 Dataclass with Frozen (Immutable)
If you want objects that cannot be changed:
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
host: str
port: int
Usage:
config = Config("localhost", 8080)
print(config)
Trying to modify:
config.port = 9090 # ❌ Error
🔹 Dataclass with Field Customization
from dataclasses import dataclass, field
@dataclass
class User:
name: str
roles: list = field(default_factory=list)
Usage:
u = User("John")
u.roles.append("admin")
print(u)
🔹 Real-Life Example (Bank Account)
from dataclasses import dataclass
@dataclass
class BankAccount:
account_number: int
balance: float
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
Usage:
acc = BankAccount(12345, 1000)
acc.deposit(500)
acc.withdraw(200)
print(acc)
🔹 Output:
BankAccount(account_number=12345, balance=1300)
🔹 Features of Dataclass
✔ Automatic constructor
✔ Automatic representation
✔ Easy comparison
✔ Less boilerplate code
✔ Cleaner structure
🔹 Dataclass vs Normal Class
| Feature | Dataclass | Normal Class |
|---|---|---|
| Code length | Short | Long |
| Constructor | Auto-generated | Manual |
| Readability | High | Medium |
| Comparison | Built-in | Manual |
| Usage | Data storage | Full logic |
🔹 When to Use Dataclass?
Use dataclasses when:
- You are storing data
- You need simple models
- You are building APIs or structures
- You want clean and fast development
🔹 When NOT to Use Dataclass?
Avoid when:
- You need complex behavior only
- You need full control over initialization
- You are building heavy logic systems
🚀 Conclusion
Python dataclasses are a powerful feature that helps you write clean, simple, and efficient data-focused classes.
They reduce boilerplate code and improve readability, making them perfect for:
- APIs
- Data models
- Configuration objects
- Business logic structures


0 Comments