DEV Community

Max Montesino
Max Montesino

Posted on

The @dataclass Decorator In Python

Decorators: when used well, they make code cleaner. But to the uninitiated, they can turn the mysterious into the totally inscrutable.

Wait, What's a decorator?

A decorator is essentially a function that can alter the behavior of another function or class, without altering its code. You can add functionality like timing a function or logging its output, or completely change what the function does.

@dataclass

The @dataclass decorator, added before a class meant to hold data, automatically adds common methods for dealing with that data:

  • an __init__() constructor that accepts parameters to create a class instance
  • a __repr__() method that outputs a string representation of the instance
  • __eq__() for testing equality of two class instances
  • __hash__ allows the data in your class to serve as dictionary keys--assuming the data is hashable and frozen=True
  • if you set order=True, you can use comparison methods such as __lt__ (less than), __le__ (less than or equal to), __gt__ (greater than), __ge__ (greater than or equal to)

First you from dataclasses import dataclass in your code, then you add @dataclass right before your class definition:

@dataclass
class Article:
    title: str
    author: str
    description: str
    url: str
    source: str
    published_at: datetime.now.strftime("%Y-%m-%d %H:%M:%S")
Enter fullscreen mode Exit fullscreen mode

Your class now comes with all of the above methods, saving you the headache of writing them all out.

Top comments (0)