Module lessons (2/4)
dataclass: data classes without boilerplate
The @dataclass decorator (dataclasses module) automatically generates
__init__, __repr__, and __eq__ for classes whose only job is to hold
data. Less boilerplate, clearer code.
Without dataclass (boilerplate)
class Punto:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def __repr__(self) -> str:
return f"Punto(x={self.x}, y={self.y})"
def __eq__(self, other) -> bool:
if not isinstance(other, Punto):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)With dataclass
from dataclasses import dataclass
@dataclass
class Punto:
x: float
y: float
p = Punto(3, 4)
p # Punto(x=3, y=4) ← __repr__ gratis
Punto(3, 4) == Punto(3, 4) # True ← __eq__ gratis
p.x, p.y # 3, 4The pattern: declare fields as class annotations (name: type),
optionally with a default value. @dataclass generates the rest.
Default and default_factory
from dataclasses import dataclass, field
@dataclass
class Articolo:
nome: str
prezzo: float = 0.0
tag: list[str] = field(default_factory=list)frozen=True: immutable
@dataclass(frozen=True)
class Coordinata:
lat: float
lon: float
c = Coordinata(45.4, 9.2)
c.lat = 99 # FrozenInstanceError!frozen dataclasses are also hashable: you can use them as dict keys
or set elements.
order=True: automatic comparisons
@dataclass(order=True)
class Voto:
valore: int
Voto(10) < Voto(20) # True
sorted([Voto(30), Voto(10), Voto(20)])Generates __lt__, __le__, __gt__, __ge__ comparing fields in the order
they were declared.
Normal methods
Dataclasses remain regular classes: you can add methods.
import math
from dataclasses import dataclass
@dataclass
class Punto:
x: float
y: float
def distanza_dall_origine(self) -> float:
return math.hypot(self.x, self.y)
Punto(3, 4).distanza_dall_origine() # 5.0Immutable and efficient dataclasses
You can make a dataclass immutable by passing the argument frozen=True to the decorator: @dataclass(frozen=True). This raises an error on any attempt to mutate attributes after instantiation, making instances safe for concurrent environments or for use as dictionary keys.
Try it yourself
Create a dataclass `Book` with fields `title: str` and `pages: int`. Instantiate it as `l = Book('Moby Dick', 635)`. Evaluate `l == Book('Moby Dick', 635)`.
Show hint
@dataclass generates __eq__ comparing field by field.
Solution available after 3 attempts
Review exercise
Create a dataclass `Basket` with field `items: list[str]` with default_factory=list. Instantiate `c1 = Basket()` and `c2 = Basket()`, append 'mela' to c1.items. Evaluate `(c1.items, c2.items)` to verify they are NOT the same list.
Show hint
field(default_factory=list) guarantees a new list per instance.
Solution available after 3 attempts
Additional challenge
Import `dataclass` from `dataclasses`. Create a dataclass `Point` containing two float coordinates `x` and `y`. Instantiate a point with `x=1.5` and `y=2.5` storing it in `p`. Finally, evaluate `p`.
Show hint
Use @dataclass above the class Point, and declare x: float and y: float.
Solution available after 3 attempts