2 min read

Python Dataclasses

Dataclasses are a feature introduced in Python 3.7 that provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. They are primarily used to store data.

Importing the Module

from dataclasses import dataclass

Basic Usage

To create a dataclass, decorate a class with @dataclass.

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(10, 20)
print(p) # Output: Point(x=10, y=20)

Default Values

You can provide default values for fields.

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1

item = Product("Laptop", 999.99)
print(item) # Output: Product(name='Laptop', price=999.99, quantity=1)

field() Function

For mutable default values (like lists) or more complex field configuration, use the field() function.

from dataclasses import dataclass, field
from typing import List

@dataclass
class Student:
    name: str
    grades: List[int] = field(default_factory=list)

s = Student("Alice")
s.grades.append(90)
print(s)

Immutable Dataclasses (Frozen)

You can make a dataclass immutable (read-only) by setting frozen=True. This also makes instances hashable, so they can be used as dictionary keys or in sets.

@dataclass(frozen=True)
class Point:
    x: int
    y: int

p = Point(10, 20)
# p.x = 30 # This would raise a FrozenInstanceError

Post-Init Processing

The __post_init__ method allows for additional initialization after __init__ has been called.

@dataclass
class Rectangle:
    width: float
    height: float
    area: float = field(init=False)

    def __post_init__(self):
        self.area = self.width * self.height

programming/python/python