Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

Python’s dataclasses: The Supercharged Alternative to Classes 🚀

Elshad Karimov
Dev Genius
Published in
3 min readFeb 18, 2025

Photo by Markus Spiske on Unsplash

If you’ve been writing Python classes with __init__, __repr__, and __eq__ manually, you’re working too hard!

Python’s dataclasses module, introduced in Python 3.7, can automate all of that with just one decorator.

🔹 Why dataclasses?

Less boilerplate: No need to write __init__, __repr__, or __eq__ manually.
More readable: Focus on what the class does, not how to structure it.
Easy defaults: Set default values effortlessly.
Frozen instances: Make objects immutable with one argument.
Auto-comparisons: Supports <, >, <=, >=, and == out of the box.

By the end of this post, you’ll be saving time and writing cleaner Python code. Let’s dive in! 🚀

🔹 Writing Classes the Old Way (Painful!)

Before dataclasses, creating a simple class with attributes required a lot of repetitive code:

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})"

def __eq__(self, other):
return self.name == other.name and self.age == other.age

p1 = Person("Alice", 30)
p2 = Person("Alice", 30)

print(p1) # ✅ Person(name=Alice, age=30)
print(p1 == p2) # ✅ True (because we implemented __eq__)

❌ Problems with this approach

🚨 Too much boilerplate code.
🚨 Forgetting __repr__ means debugging becomes a nightmare.
🚨 Forgetting __eq__ means comparisons won't work as expected.

🔹 Enter dataclass – The Superhero 🦸‍♂️

With dataclasses, we can achieve the same functionality with just one line of code!

from dataclasses import dataclass

@dataclass
class Person:
name: str
age: int

p1 = Person("Alice", 30)
p2 = Person("Alice", 30)

print(p1) # ✅ Person(name='Alice', age=30)
print(p1 == p2) # ✅ True (Auto-generated __eq__)

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet

Write a response