https://blog.logrocket.com/understanding-python-dataclasses/

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/e206004c-69e2-443e-971f-e38388583515/Understanding-Python-dataclasses.png

The Python 3.7 release saw a new feature introduced: dataclasses.

For reference, a class is basically a blueprint for creating objects. An example of a class could be a country, which we would use the Country class to create various instances, such as Monaco and Gambia.

When initializing values, the properties supplied to the constructor (like population, languages, and so on) are copied into each object instance:

classCountry:
    def __init__(self, name: str, population: int, continent: str, official_lang: str):
        self.name = name
        self.population = population
        self.continent = continent
        self.official_lang = official_lang

smallestEurope = Country("Monaco", 37623, "Europe")
smallestAsia= Country("Maldives", 552595, "Asia")
smallestAfrica= Country("Gambia", 2521126, "Africa")

If you ever worked with object-oriented programming (OOP) in programming languages like Java and Python, then you should already be familiar with classes.

A dataclass, however, comes with the basic class functionalities already implemented, decreasing the time spent writing code.

In this article, we’ll delve further into what dataclasses in Python are, how to manipulate object fields, how to sort and compare dataclasses, and more.

Note that because this was released in Python 3.7, you must have a recent version of Python installed on your local machine to use it.

What is a Python dataclass?

As mentioned previously, Python dataclasses are very similar to normal classes, but with implemented class functionalities that significantly decrease the amount of boilerplate code required to write.

An example of such boilerplate is the __init__ method.

In the Country class example, you can observe that we had to manually define the __init__ method, which gets called when you initialize the class. Now, for every normal class you define, you are required to provide this function, which means you must write a lot of repetitive code.

The Python dataclass comes with this method already defined. So, you can write the same Country class without manually defining a constructor.

Under the hood, @dataclass calls this method when you initialize the object with new properties.

Note that __init__ is not the only method provided by default. Other utility methods like __repr__ (representation), __lt__ (less than), __gt__ (greater than), __eq__ (equal to), and many others are also implemented by default.

Using the normal Python class

When working with a normal class in Python, we have longer code to implement the base methods.