đź§© What is a Data Class?
A data class is a class that is mainly used to hold data values. Instead of writing all the methods like __init__ , __repr__, or __eq__ manually, Python provides the dataclasses module (introduced in Python 3.7) to generate them automatically.
👉 In short: Data classes simplify classes that only store data.
🔑 Why Use a Data Class?
Normally, if you want to create a class to hold data, you’d need to write a lot of repetitive code.
Example without Data Class:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
p1 = Person("Alice", 25)
print(p1)
Output:
Person(name=Alice, age=25)
This works, but writing the __init__ and __repr__every time is repetitive.
⚡ Using Data Class
With data classes, you can achieve the same with less code.
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
p1 = Person("Alice", 25)
print(p1)
Output:
Person(name='Alice', age=25)
👉 The dataclass
decorator automatically creates __init__ , __repr__, and __eq__ methods for you.
🛠️ Features of Data Classes
Automatic __init__ method – No need to manually write constructors.
Automatic __repr__ method – Easy-to-read string representation of objects.
Automatic __eq__ method – You can compare two objects directly.
Example:
@dataclass
class Person:
name: str
age: int
p1 = Person("Alice", 25)
p2 = Person("Alice", 25)
print(p1 == p2)
Output:
True
Here, both objects are equal because their data is the same.
📦 Default Values and Field Options
You can also set default values for attributes.
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float = 0.0 # default value
item = Product("Book")
print(item)
Output:
Product(name='Book', price=0.0)
You can even control behavior using thefield() function:
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
tags: list = field(default_factory=list)
item = Product("Book")
print(item.tags)
Output:
[]
🏗️ Immutability with frozen=True
If you want to make your data class immutable (read-only), you can use frozen=True .
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(2, 3)
print(p.x)
# Trying to modify will raise an error
p.x = 10
Output:
2
Traceback (most recent call last):
...
FrozenInstanceError: cannot assign to field 'x'
🔍 Data Class vs Normal Class
Feature | Normal Class | Data Class |
---|
Auto __init__ | ❌ No | ✅ Yes |
Auto __repr__ | ❌ No | ✅ Yes |
Auto __eq__ | ❌ No | ✅ Yes |
Less Boilerplate Code | ❌ No | ✅ Yes |
📌 Summary
Data classes in Python provide a clean and efficient way to store structured data. They automatically handle common methods like __init__, __repr__, and __eq__, which saves time and makes the code easier to read. You can also use advanced features like default values, immutability (frozen=True), and custom field options. If you want to reduce boilerplate code when working with classes that only hold data, data classes are the perfect choice. 🚀