TIL: dataclasses Auto-Generate init, repr, and eq for You
When creating classes in Python, we often find ourselves writing boilerplate code for __init__, __repr__, and __eq__ methods. Let's compare a regular class with a @dataclass to see the difference.
Consider a simple Person 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
Now, let's rewrite it using @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 us. This saves a significant amount of boilerplate code and makes our classes more readable and maintainable.
By using @dataclass, you can focus on the logic of your class without worrying about the tedious implementation details, making your code more efficient and Pythonic.
Follow me on Dev.to for daily Python tips and quick guides!
Top comments (0)