Sub topic 1
The Boilerplate Problem with Plain Classes
Prerequisites
Assume you know how to define Python classes, create instances, use type annotations, and distinguish mutable objects such as lists from immutable values such as integers and strings.
Plain Classes Repeat Data-Handling Code
A data-holding class mainly stores values and displays or compares them. With a plain class, you commonly write the constructor, representation, and equality method yourself:
class Point:
def __init__(self, x: float, y: float = 0.0):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x!r}, y={self.y!r})"
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.y
print(Point(1.5) == Point(1.5, 0.0)) # TrueThis code is straightforward, but every new data class needs similar methods. Repetition creates opportunities for inconsistent behavior.
Your First Dataclass
A dataclass is a class whose data fields are declared with annotations. The @dataclass decorator reads those declarations and generates common methods, including __init__, __repr__, and __eq__.
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float = 0.0
p = Point(1.5)
print(p) # Point(x=1.5, y=0.0)
print(p == Point(1.5, 0.0)) # TrueThe generated constructor follows field order. Fields without defaults must come before fields with defaults.
Fields, Defaults, and Mutable Values
Each annotated attribute is a field. A default value is used when the caller omits that argument. Defaults should be immutable when possible:
from dataclasses import dataclass
@dataclass
class Server:
host: str
port: int = 8080A mutable default, such as [], would be shared conceptually across instances and could cause state to leak between objects. Dataclasses reject this pattern instead of silently creating that bug.
Use field(default_factory=...) to call a factory separately for each instance:
from dataclasses import dataclass, field
@dataclass
class Basket:
owner: str
items: list[str] = field(default_factory=list)
a = Basket("Ana")
b = Basket("Ben")
a.items.append("apple")
print(a.items) # ['apple']
print(b.items) # []Exercise
Why must items use default_factory=list instead of items: list[str] = []?
Show answer
The factory creates a separate list for each instance, preventing changes to one Basket from appearing in another.