TIL: dataclasses Auto-Generate init, repr, and eq for You
When creating classes in Python, you often find yourself writing boilerplate code for __init__, __repr__, and __eq__ methods. However, with the introduction of @dataclass decorator in Python 3.7, this boilerplate code can be automatically generated for you.
Let's compare a regular class with a @dataclass:
Regular 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})"
def __eq__(self, other):
return self.name == other.name and self.age == other.age
@dataclass
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
As you can see, the @dataclass version is much more concise, with the __init__, __repr__, and __eq__ methods automatically generated for you, saving a significant amount of boilerplate code.
The takeaway is that using @dataclass can greatly simplify your code and reduce boilerplate when creating classes in Python.
Follow me on Dev.to for daily Python tips and quick guides!
Top comments (0)