Python - Reduce Boilerplate Code with Dataclasses


Python Clean Code Tip:

Use dataclasses when only storing attributes inside your class instances to reduce the amount of boilerplate code.

For example:

# without dataclass
class Address:
    def __init__(self, street, city, zip_code):
        self.street = street
        self.city = city
        self.zip_code = zip_code

    def __repr__(self):
        return (
            f"Address(street={self.street}, city={self.city}, zip_code={self.zip_code})"
        )

    def __hash__(self) -> int:
        return hash((self.street, self.city, self.zip_code))

    def __eq__(self, other) -> bool:
        if not isinstance(other, Address):
            return NotImplemented
        return (self.street, self.city, self.zip_code) == (
            other.street,
            other.city,
            other.zip_code,
        )


# with dataclass
from dataclasses import dataclass

@dataclass(unsafe_hash=True)
class Address:
    street: str
    city: str
    zip_code: str