...

/

Creating Classes with a More Compact Syntax

Creating Classes with a More Compact Syntax

Learn how to make use of dataclasses decorator to create classes with compact syntax.

Let's continue with the idea that sometimes, we need objects to hold values. There's a common boilerplate in Python when it comes to the initialization of objects, which is to declare in the __init__ method all attributes that the object will have, and then set that to internal variables, typically in this form:

Press + to interact
def __init__(self, x, y, ...):
self.x = x
self.y = y

The dataclasses module

Ever since Python 3.7 was released, we can simplify this by using the dataclasses module.

The @dataclass decorator

This module provides a @dataclass decorator, which, when applied to a class, will take all the class attributesThese are attributes shared by all instances of a class. with annotations and treat them as instance attributesThese are attributes attached to a specific instance of a class., as if they were declared in the initialization method. When using this decorator, it will automatically generate the __init__ method on the class, so we don't have to. ...