What does dataclass decorator in Python Class


In Python, the @dataclass decorator is a feature introduced in Python 3.7 as part of the dataclasses module. It provides a convenient way to define classes that are primarily used to store data.

By applying the @dataclass decorator to a class, you can automatically generate several common methods and functionality, such as initializing attributes, comparing instances, generating string representations, and more. This helps reduce boilerplate code that would otherwise be required for such operations.

Here’s an example of using @dataclass:

from dataclasses import dataclass

@dataclass
class Person:
name: str
age: int
profession: str

# Create an instance of the dataclass
person = Person("John Doe", 30, "Engineer")

# Accessing attributes
print(person.name) # Output: John Doe
print(person.age) # Output: 30
print(person.profession) # Output: Engineer

# String representation
print(person) # Output: Person(name='John Doe', age=30, profession='Engineer')

By simply adding the @dataclass decorator, Python automatically generates the init method, repr method, and various other methods behind the scenes. It also provides default implementations for comparison methods such as eq, ne, lt, gt, le, and ge.

You can further customize the behavior of the dataclass by using additional class-level decorators or by providing explicit type annotations, default values, and other options within the class definition. The dataclasses module offers additional features to enhance the functionality of dataclass, such as ordering, immutability, and more.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC