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:
def __init__(self, x, y, ...):self.x = xself.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 __init__
method on the class, so we don't have to.
The field
object
Additionally, this module provides a field
object that will help us define particular traits for some of the attributes. For example, if one of the attributes we need needs to be mutable (such as a list
), we cannot pass this default empty list in the __init__
method. Instead we should pass None
, and set it to a default list inside __
...