ruk·si

🐍 Python
dataclass

Updated at 2022-09-19 10:50

dataclasses module provide a interface to create data classes that automatically define magic methods such as __init__ and __repr__.

You can configure the data class using the decorator e.g. @dataclass(frozen=True).

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p1 = Point(x=10, y=10)
p2 = Point(x=10, y=10)
assert p1 == p2
p2.y = 11
assert p1 != p2

Data classes can have methods like any class. They simply have a basic set of functionality for a class which's main use is to contain information.

from dataclasses import dataclass

@dataclass
class Item:
    name: str
    value: float
    quality: float = 1

    @property
    def price(self):
        return self.value * self.quality

sword = Item('Sword', 5.1)
assert sword.price == 5.1
assert str(sword) == "Item(name='Sword', value=5.1, quality=1)"

shield = Item('Shield', 10.0, 0.75)
assert shield.price == 7.5
assert str(shield) == "Item(name='Shield', value=10.0, quality=0.75)"

Use dataclasses.field to configure individual properties. For example, mutable default values need a generator.

from dataclasses import dataclass, field
from typing import List

@dataclass
class Lotto:
    numbers: List[int] = field(default_factory=list)

lotto = Lotto()
lotto.numbers += [1, 2]
lotto.numbers += [3, 4]
assert lotto.numbers == [1, 2, 3, 4]

The generated init will call post_init. This is useful e.g. when:

  1. you want a property to be calculated based off other properties
  2. you use inheritance with data classes and want to call the super().__init__

Source

  • Python 3 Docs