🤔 Python data classes

What are they? How to use them?

🧵Let's find out👇
1️⃣ There's really nothing special about the class: the dataclass decorator adds generated methods
- __init__
- __repr__
- __eq__

to the class and returns the same class it was given.
2️⃣ Generated __init__ method takes all fields
as function parameters. Their values are set to instance attributes with the same names.

For example, you can define User with fields id and name.👇
3️⃣ Generated __repr__ method returns a string containing:

- class name
- field names
- field representation

The order of fields is the same as the order of their definition in a class
4️⃣ Generated __eq__ method compares the class tuples containing field values of the current and the other instance.

It supports only instances of the same class

True is returned if:
- current and other are of the same class
- fields of both have the same values

For example👇
5️⃣ You can enable order by setting the order argument of the decorator to True.

It adds methods:
- __lt__
- __le__
- __gt__
- __ge__

They are implemented in the same way as __eq__
6️⃣ You can make instances immutable by setting the argument frozen to True

In such case dataclasses.FrozenInstanceError is raised if you try to reassign instance attribute
7️⃣ You can use __post_init__ hook on data classes to set the value of the attribute based on the others' values
You can follow @jangiacomelli.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.