Akshay Kaushik 🐍👨‍💻 Profile picture
Converting complex problems into elegant solutions. Passionate about code, coffee, and creativity. ☕ #developer #python #javascript

Feb 5, 2022, 9 tweets

Do you know #Python "Data Classes"

They are a great Python feature that can help you write less code

🧵Let's find out more👇

1️⃣ 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.

Fields are defined as type annotated class attributes.

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
👇

5️⃣ You can enable the ordering of instances 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 read more here.
docs.python.org/3/library/data…

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling