Twelve @dataclass Examples for Better Python Code
Transform data into structured objects with @dataclass. Source: Photo by Andreas Klassen on Unsplash

Twelve @dataclass Examples for Better Python Code

Twelve @dataclass Examples

@dataclass was an added feature of Python 3.7. The main driving force was to eliminate boilerplate associated with the state in a def class definition.

Classes can exist with no state and only methods, but what is the point? Classes exist to encapsulate state (data fields) and the methods that operate on the data fields. Without the state to encapsulate, transform the methods into functions.

Note: If you are not using pandas, you can speed up these functions with a quick insert @jit from the numba package.

@dataclass decorates a def class definition and automatically generates the five double dunder methods __init__() , __repr__() , __str__ ,__eq__(), and, __hash__().

Note: It generates others, but we get to that later.

Notice that all these five double dunder methods work directly with the class’s encapsulated state. @dataclass virtually eliminates repetitive boilerplate code required to define a basic class.

An example of a short class in photon/photonai/base/hyperpipe.py transformed by the @dataclass.

### Example #1
class Data:
    def __init__(self, X=None, y=None, kwargs=None):
        self.X = X
        self.y = y
        self.kwargs = kwargs

Example #1, after @dataclassdecorater=>

from dataclasses import dataclass
from typing import Dict
import numpy as np
@dataclass
class Data:
    X: np.ndarray = None  # The field declaration: X
    y: np.array = None    # The field declaration: y
    kwargs: Dict = None   # The field declaration: kwargs

Note: If the type is not part of that declaration, the field is ignored. Use the type Any for the wildcard type, if type varies or unknown at runtime.

Was__eq__()code generated?

continue ...



To view or add a comment, sign in

More articles by Bruce Cottman

Insights from the community

Others also viewed

Explore topics