Python data classes

Omar Hussein
The Modern Scientist
2 min readDec 20, 2022
Photo by Artturi Jalli on Unsplash

Python's dataclass module, introduced in Python 3.7, is a decorator that helps you create classes that are primarily used to store data. These classes are similar to namedtuple classes, but they have several additional features, such as default values, type hints, and methods.

To use the dataclass decorator, you first need to import it from the dataclasses module. Then, you can use it to decorate your class definition. For example, here is a simple Person class with a name and age field:

from dataclasses import dataclass

@dataclass
class Person:
name: str
age: int

The dataclass decorator automatically generates several useful methods for you, such as __init__, __repr__, and __eq__.

To create an instance of the Person class, you can use the standard syntax:

You can also specify default values for your fields by using the default argument:

In addition to the default methods, you can also define your own methods within the dataclass. For example, you might want to define a grow_older method that increments the person’s age:

You can also specify type hints for your fields using the typing module. This can be helpful for documentation and static analysis tools. For example:

from typing import List

@dataclass
class Person:
name: str
age: int = 18
friends: List[str] = []

def add_friend(self, friend_name: str):
self.friends.append(friend_name)

There are several other options and decorators available in the dataclasses module, such as the field decorator, which allows you to specify additional options for individual fields. For more information, you can refer to the official Python documentation for the dataclasses module.

--

--