dataclasses | Python Standard Library – Real Python

The Python dataclasses module provides functionality for creating and working with user-defined data classes. These types of classes are mainly used to store data as attributes (fields) but can provide more functionality.

Data classes also provide default implementations for some common special methods, including .__init__(), .__repr__(), .__eq__(), and .__hash__(). This behavior saves you from writing the associated boilerplate code.

Here’s a quick example:

Key Features

  • Automatically generates special methods like .__init__(), .__repr__(), and .__eq__()
  • Supports default values and default factories for fields
  • Allows customization of field behavior with field metadata
  • Provides a way to create immutable data classes

Frequently Used Classes and Functions

Examples

Creating a data class with default values for fields:

Converting a data class to a dictionary:

Common Use Cases

  • Facilitating the creation of classes that are mainly used for storing data
  • Automatically generating common methods like .__init__(), .__repr__(), and .__eq__()
  • Converting data class instances to dictionaries or tuples for serialization

Real-World Example

Suppose you need to manage a collection of employees with attributes like .name, .age, and .position. You can use dataclasses as shown below:

In this example, the dataclasses module streamlines the creation and management of employee records.

Data Classes in Python 3.7 (And Above)

For additional information on related topics, take a look at the following resources: