Python Dataclasses

Dataclasses are python classes, but are suited for storing data objects. This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes.

Features

  1. They store data and represent a certain data type. Ex: A number. For people familiar with ORMs, a model instance is a data object. It represents a specific kind of entity. It holds attributes that define or represent the entity.

  2. They can be compared to other objects of the same type. Ex: A number can be greater than, less than, or equal to another number.

Python 3.7 provides a decorator dataclass that is used to convert a class into a dataclass.

class Number:
    def __init__(self, val):
        self.val = val

obj = Number(2)
obj.val
2

with dataclass

# Dataclass: automatically generates __init__ and __repr__ methods
from dataclasses import dataclass

@dataclass  # Decorator converts class to dataclass
class Number:
    val: int  # Type annotation required

obj = Number(2)  # __init__ automatically created
obj.val
2

Default values

It is easy to add default values to the fields of your data class.

# Dataclass with default values: fields with defaults must come after required fields
@dataclass
class Product:
    name: str        # Required field
    count: int = 0   # Optional field with default value
    price: float = 0.0  # Optional field with default value

obj = Product("Python")  # Only name required, others use defaults
obj.name
Python
obj.count
0
obj.price
0.0
Quiz

Sign in to answer this quiz and track your learning progress

In a dataclass, where must fields with default values be placed?
A. Before fields without default values
B. After fields without default values
C. It doesn't matter
D. In a separate section

Type hints

It is mandatory to define the data type in dataclass. However, If you would rather not specify the datatype then, use typing.Any.

from dataclasses import dataclass
from typing import Any

@dataclass
class WithoutExplicitTypes:
   name: Any
   value: Any = 42