Most classes exist mainly to hold a few values. Writing __init__, __repr__
and __eq__ for each one by hand is exactly the sort of work a language should
do for you.
The boilerplate problem
class Book:
def __init__(self, title, author, pages=0):
self.title = title
self.author = author
self.pages = pages
def __repr__(self):
return f"Book(title={self.title!r}, author={self.author!r}, pages={self.pages})"
def __eq__(self, other):
if not isinstance(other, Book):
return NotImplemented
return (self.title, self.author, self.pages) == (other.title, other.author, other.pages)
book = Book("Dune", "Herbert", 412)
print(book)
print(book == Book("Dune", "Herbert", 412))If you skipped Dunder Methods, the names with double underscores are methods
Python calls for you: __repr__ decides how an object looks when printed, and
__eq__ is what == runs. You don't need to write either — not writing them is
exactly what the rest of this lesson is about. isinstance(other, Book)
checks whether the other value is a Book. NotImplemented lets Python handle
an unsupported comparison rather than trying to read book fields from an
unrelated value. It is a special return value, not an exception to raise.
The same class as a dataclass
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
pages: int = 0
book = Book("Dune", "Herbert", 412)
print(book) # __repr__ for free
print(book == Book("Dune", "Herbert", 412)) # __eq__ for free
print(book.title, book.pages)
book.pages = 500 # still an ordinary object
print(book)The @dataclass line is a decorator: a function that takes your class and
returns an enhanced version of it. It writes __init__, __repr__ and
__eq__ from the annotated fields.
Dataclass options
from dataclasses import dataclass, field
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int
patch: int = 0
def __str__(self):
return f"{self.major}.{self.minor}.{self.patch}"
v1 = Version(1, 4)
v2 = Version(1, 10)
print(str(v1), str(v2))
print(v1 < v2) # order=True gives comparison from field order
print(sorted([v2, v1]))
v1.major = 2 # frozen=True rejects normal field assignmentfrozen=True rejects ordinary assignment to fields; it does not recursively
freeze their contents. With the default equality behavior, it also generates a
hash method, but hashing works only when the participating field values are
hashable. The Version above holds only integers, so it can be a dictionary key.
A frozen record holding a list cannot be hashed that way. order=True
generates the comparison methods from field order.
Mutable defaults, once more
tags: list = [] in a dataclass raises an error outright — Python knows the
trap. Use tags: list = field(default_factory=list) to give each instance its
own list.
from dataclasses import dataclass, field
@dataclass
class Playlist:
name: str
tracks: list = field(default_factory=list)
plays: int = 0
a = Playlist("Focus")
b = Playlist("Party")
a.tracks.append("Kind of Blue")
print(a)
print(b) # still empty, as it should beType hints
The title: str annotations above are type hints. Python does not enforce
them at runtime — but editors, linters and type checkers do, and readers do
most of all.
def repeat(text: str, times: int = 2) -> str:
"""Return text repeated, separated by spaces."""
return " ".join([text] * times)
print(repeat("ha", 3))
print(repeat.__annotations__)
# Nothing stops you passing the wrong type - Python just runs it:
print(repeat(5, 2))That last line produces a TypeError deep inside join. A type checker such
as mypy or pyright would flag the call before you ran it. Ruff is a
linter and formatter; type checking is a separate job.
def total_prices(prices: list[float]) -> float:
return sum(prices)
def lookup(table: dict[str, int], key: str) -> int | None:
"""Return the value, or None when the key is absent."""
return table.get(key)
print(total_prices([1.5, 2.5]))
print(lookup({"a": 1}, "a"), lookup({"a": 1}, "z"))list[float], dict[str, int] and int | None are the modern spellings —
no imports needed on Python 3.10 and later.
Frozen fields do not freeze a nested list
Predict which operation is allowed: replacing a field, or changing the list that field already refers to. The exception handling is from Day 5.
from dataclasses import dataclass, FrozenInstanceError
@dataclass(frozen=True)
class ReadingList:
titles: list[str]
reading = ReadingList(["Dune"])
reading.titles.append("Piranesi")
print(reading.titles)
try:
reading.titles = []
except FrozenInstanceError:
print("field assignment refused")
try:
hash(reading)
except TypeError:
print("the list field is not hashable")Check your prediction
['Dune', 'Piranesi']
field assignment refused
the list field is not hashablehash is the lookup operation used by dictionaries and sets. If this record
needs fixed contents as well as fixed fields, store a tuple of strings instead
of a list. A tuple containing another mutable object would still share it.
Properties
Sometimes an attribute should be computed, or validated on assignment.
@property makes a method look like an attribute.
class Rectangle:
def __init__(self, width: float, height: float):
self.width = width
self.height = height
@property
def area(self) -> float:
"""Computed on access - no parentheses at the call site."""
return self.width * self.height
class Temperature:
def __init__(self, celsius: float):
self.celsius = celsius
@property
def celsius(self) -> float:
return self._celsius
@celsius.setter
def celsius(self, value: float) -> None:
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
@property
def fahrenheit(self) -> float:
return self._celsius * 9 / 5 + 32
r = Rectangle(3, 4)
print(r.area)
t = Temperature(21.5)
print(t.celsius, t.fahrenheit)
t.celsius = -300Properties let you start with a plain attribute and add validation later without changing a single line of calling code.
Before you write your own
Predict. Two expenses with the same values, and one using a default.
from dataclasses import dataclass
@dataclass
class Expense:
item: str
cost: float = 0.0
a = Expense("lunch", 12.5)
b = Expense("lunch", 12.5)
c = Expense("bus")
print(a)
print(a == b, a is b)
print(c.cost)Check your prediction
Expense(item='lunch', cost=12.5)
True False
0.0The generated __eq__ compares field values, so a == b; they are still two
separate objects, so a is b is false. A field with a default can be left out.
Fix. Each note should get its own list of tags. Python refuses to even create the class — and its error message tells you the fix.
from dataclasses import dataclass
@dataclass
class Note:
text: str
tags: list[str] = []
a = Note("buy milk")
a.tags.append("shopping")
b = Note("call Sam")
print(a.tags, b.tags)Check your fix
from dataclasses import dataclass, field
@dataclass
class Note:
text: str
tags: list[str] = field(default_factory=list)
a = Note("buy milk")
a.tags.append("shopping")
b = Note("call Sam")
print(a.tags, b.tags)['shopping'] []This is the shared-default trap from Day 4, and dataclasses catch it for you:
= [] would be one list shared by every note. default_factory=list calls
list() afresh for each one.
Model an order
Write a frozen dataclass Item with name: str and price: float, and a
dataclass Order with customer: str and items: list[Item] (defaulting to
empty). Give Order an add method and a total property. With the two items
from the solution added, printing the order and its total gives:
Order(customer='Ada', items=[Item(name='keyboard', price=49.99), Item(name='mouse', price=25.5)])
75.49from dataclasses import dataclass, field
# Your code hereHint 1: the idea
Two classes, and the second holds a list of the first. The fields are just
annotated names. The options above cover the two special parts: frozen=True
for Item, and an empty-list default for Order, which needs
field(default_factory=list). total is a property — a method you read like an
attribute.
Hint 2: a first step
Write Item first and check print(Item("keyboard", 49.99)) shows a readable
result. Then Order with its two fields, then add (append to self.items),
and last total, with @property on the line above it. Round the total to two
places.
Show one solution
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Item:
name: str
price: float
@dataclass
class Order:
customer: str
items: list[Item] = field(default_factory=list)
def add(self, item: Item) -> None:
self.items.append(item)
@property
def total(self) -> float:
return round(sum(item.price for item in self.items), 2)
order = Order("Ada")
order.add(Item("keyboard", 49.99))
order.add(Item("mouse", 25.50))
print(order)
print(order.total)Item is frozen because an item in a placed order should not change under
you; Order is not, because adding items is the whole point of it.
Day 6 checkpoint: combine today's ideas
Close the worked examples and try this from memory. It takes about 15–20 minutes.
Independent study plans
Define a frozen Session dataclass holding topic: str and minutes: int. Write StudyPlan with add(topic, minutes) and total_minutes(). Each plan owns its own list of sessions. add refuses negative minutes with ValueError before changing that list; zero is allowed. Use the class through add for this task: the Session annotations themselves do not validate inputs.
Add two sessions of 20 and 10 minutes to one plan and create a second empty
plan. Attempt a negative addition, catch its error, and show that the first
total remains 30. Print 30, 0, Rejected, and 30 on separate lines.
from dataclasses import dataclass
# Define Session and StudyPlan. Keep per-plan state inside __init__.
# Demonstrate two plans and one rejected update.Hint 1: the idea
The record describes one session; the plan owns a collection of those records. Reject before appending so an error cannot leave invalid state behind.
Hint 2: a first step
Create the session list inside each StudyPlan initialization. In add, check the value before constructing and storing its Session.
Show one solution
from dataclasses import dataclass
@dataclass(frozen=True)
class Session:
topic: str
minutes: int
class StudyPlan:
def __init__(self):
self.sessions = []
def add(self, topic, minutes):
if minutes < 0:
raise ValueError("minutes may not be negative")
self.sessions.append(Session(topic, minutes))
def total_minutes(self):
return sum(session.minutes for session in self.sessions)
first = StudyPlan()
second = StudyPlan()
first.add("Read", 20)
first.add("Review", 10)
print(first.total_minutes())
print(second.total_minutes())
try:
first.add("Invalid", -5)
except ValueError:
print("Rejected")
print(first.total_minutes())30
0
Rejected
30When your output matches, try these changes. Each says what to change and what you should then see:
| Change | What you should see |
|---|---|
| Make two plans and add a session to only one | The other plan's total doesn't change |
add("Read", -5) inside try | ValueError, and the total is the same as before the call |
add("Read", 0) | No error, and the total doesn't change |
Close the solution and change one input. Explain which case would expose the mistake you were most likely to make. Begin your next session by rebuilding one small part without looking back.
Day 6 is done
You can now design types that carry their own rules — the step from writing scripts to designing programs.
What you learned
@dataclassgenerates__init__,__repr__and__eq__from annotated fields.frozen=Truerejects normal field assignment; nested mutable values remain mutable.order=Truegives comparisons.- Use
field(default_factory=list)for mutable defaults. - Type hints document intent and power editors and type checkers; Python does not enforce them.
@propertyturns a method into a computed or validated attribute.