Use Data Classes To Make Your Code More Readable

Since version 3.7, Python offers data classes. There are several advantages over regular classes or other alternatives, like returning multiple values using a tuple or dictionaries:

  • A data class requires a minimal amount of code
  • You can compare data classes because __eq__ is implemented for you
  • You can easily print a data class for debugging because __repr__ is implemented as well
  • Data classes require type hints, reducing the chances of bugs

Here’s an example of a data class at work:

from dataclasses import dataclass

class Card:
    rank: str
    suit: str
card = Card("Q", "hearts")

print(card == card)
# True

# 'Q'

Card(rank='Q', suit='hearts')

Share this

Leave a Comment