Search⌘ K
AI Features

Creating Classes with a More Compact Syntax

Explore how to write more compact Python classes using the dataclasses module. Understand the use of the @dataclass decorator to automate __init__ creation, how to manage mutable default attributes with field, and implement post-initialization validation. This lesson helps you write clean, maintainable code while reducing boilerplate in class definitions.

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:

Python 3.8
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 ...