Dataclasses, enumerations and types · 2 / 15 Theory

Dataclasses: classes to hold data

Many classes are only used to hold data: a point, a product, a student. Writing them by hand is repetitive:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

print(Point(3, 4))                    # Point(x=3, y=4)
print(Point(3, 4) == Point(3, 4))     # True

The @dataclass decorator generates all of that automatically from the annotated attributes:

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(3, 4)

print(p)                    # Point(x=3, y=4)
print(p.x, p.y)             # 3 4
print(Point(3, 4) == p)     # True

Python creates __init__, __repr__ (what print shows) and __eq__ (the ==). Practice with Point with a dataclass and Comparing dataclasses.

Methods

A dataclass is still a normal class: you can add methods:

@dataclass
class Rectangle:
    base: float
    height: float

    def area(self) -> float:
        return self.base * self.height

print(Rectangle(3, 4).area())   # 12

Default values

Attributes with a default value go after those without one:

@dataclass
class Product:
    name: str
    price: int = 0
    active: bool = True

print(Product("bread"))            # Product(name='bread', price=0, active=True)
print(Product("bread", 2, False))  # Product(name='bread', price=2, active=False)

Default lists: field(default_factory=...)

For a mutable default value (list, dictionary, set) you must use field(default_factory=...). Otherwise Python gives an error, because all the objects would share the same list:

from dataclasses import dataclass, field

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

    def average(self) -> float:
        return sum(self.grades) / len(self.grades) if self.grades else 0

a = Student("Ana")
b = Student("Luis")

a.grades.append(8)
a.grades.append(6)

print(a)             # Student(name='Ana', grades=[8, 6])
print(b)             # Student(name='Luis', grades=[])
print(a.average())   # 7.0

default_factory=list creates a new, empty list for each object. Practice with Grades with default values.

__post_init__: checking or calculating after creation

@dataclass
class Circle:
    radius: float
    area: float = 0.0

    def __post_init__(self):
        if self.radius < 0:
            raise ValueError("The radius cannot be negative")
        self.area = round(3.14159 * self.radius ** 2, 2)

print(Circle(2))   # Circle(radius=2, area=12.57)

__post_init__ runs right after the generated __init__.