Capstone · lesson 2 of 9
Parts in this lesson
A@dataclass class LibraryItem(ABC)an abstract dataclass
B__post_init__checks after the fields are set
Ckind: ClassVar[str]a class attribute in a dataclass
Dsuper().matches(text)4.6: extending
E@abstractmethod4.13: abstraction

The items

Last updated

Every library system starts with what's on the shelves. In this lesson you'll write items.py: an abstract LibraryItem and its four children, Book, ReferenceBook, DVD and Magazine. This time they're dataclasses, so Python writes __init__, __repr__ and __eq__ for you, and you write only what's different.

By the end of this lesson you can

  • Write an abstract dataclass with children that are dataclasses too
  • Check new objects in __post_init__
  • Explain the error when a field without a default follows one with a default
  • Override a method and extend it with super()

The family of items

The library lends three kinds of thing: books, DVDs and magazines. It also holds reference books, which stay in the building. Lesson 4.P built this family with ordinary classes. Here's the plan for items.py:

items.py
100%
«abstract» LibraryItem
  • +item_id: str
  • +title: str
  • +year: int
  • +kind: str
  • +__post_init__()
  • +loan_days(): int
  • +can_lend(): bool
  • +matches(text: str): bool
  • +__str__(): str
  • +to_dict(): dict[str, Any]
  • +from_dict(data: dict[str, Any]): Self
«dataclass» Book
  • +author: str
  • +isbn: str
  • +kind: str
  • +loan_days(): int
  • +matches(text: str): bool
  • +__str__(): str
«dataclass» DVD
  • +minutes: int
  • +kind: str
  • +loan_days(): int
  • +__str__(): str
«dataclass» Magazine
  • +issue: int
  • +kind: str
  • +loan_days(): int
  • +__str__(): str
«dataclass» ReferenceBook
  • +kind: str
  • +loan_days(): int
  • +can_lend(): bool
  • +__str__(): str
  • Abstract class LibraryItem; attributes: item_id, title, year, kind; methods: __post_init__, loan_days, can_lend, matches, __str__, to_dict, from_dict.
  • Dataclass Book; inherits from LibraryItem; attributes: author, isbn, kind; methods: loan_days, matches, __str__.
  • Dataclass ReferenceBook; inherits from Book; attributes: kind; methods: loan_days, can_lend, __str__.
  • Dataclass DVD; inherits from LibraryItem; attributes: minutes, kind; methods: loan_days, __str__.
  • Dataclass Magazine; inherits from LibraryItem; attributes: issue, kind; methods: loan_days, __str__.
  • LibraryItem is abstract (lesson 4.13). There's no plain "item" on the shelf, and every real kind must say its own loan_days().
  • Every item has an item_id, like b1. Two copies of Dune are two items with the same title, and the id tells them apart.
  • ReferenceBook is a Book whose can_lend() says no.

Here's every kind on one shelf. The loop never asks what kind each item is: each one answers loan_days() and __str__ its own way (lesson 4.9). Press Run, then open the library/items.py tab to see all of it.

Step 1 code
Edit the code, then run it again

Dataclasses write the dull parts

Lesson 3.6 showed dataclasses: you list the fields with their types, and @dataclass writes __init__, __repr__ and __eq__ from them. Items are mostly data, so they're a good fit. An abstract class can be a dataclass too: @dataclass on a class that inherits from ABC.

How the reference does it library/items.py, lines 7–25
@dataclass
class LibraryItem(ABC):
    item_id: str
    title: str
    year: int

    kind: ClassVar[str] = "item"

    def __post_init__(self) -> None:
        if not self.item_id.strip():
            raise ValueError("an item needs an id")
        if not self.title.strip():
            raise ValueError("an item needs a title")
        if not 1450 <= self.year <= 2100:
            raise ValueError(f"{self.year} isn't a year an item could be from")

    @abstractmethod
    def loan_days(self) -> int:
        """How many days this item can be borrowed for."""

A child is a dataclass too, and its fields come after its parent's. So Book takes item_id, title and year, then its own author and isbn:

Step 2 code
Edit the code, then run it again

__repr__ lists every field by name, which is handy when debugging. == compares field by field, so two Book objects with the same fields are equal, even though they're two objects (is is False, lesson 3.5).

Each class also has a kind: "book", "dvd" and so on. Lesson C.6 uses it to save items. It's marked ClassVar[str], which tells @dataclass it belongs to the class, not to each object, so it isn't a field: it's not in __init__, and not in the repr.

Why is kind marked ClassVar?

No bad items: __post_init__

With a hand-written __init__, lesson 4.4 checked each value before keeping it. A dataclass writes __init__ for you, so where do checks go? Into a method called __post_init__. The __init__ that @dataclass writes calls it last, once every field is set:

How the reference does it library/items.py, lines 15–21
    def __post_init__(self) -> None:
        if not self.item_id.strip():
            raise ValueError("an item needs an id")
        if not self.title.strip():
            raise ValueError("an item needs a title")
        if not 1450 <= self.year <= 2100:
            raise ValueError(f"{self.year} isn't a year an item could be from")

Every child inherits it, so every kind of item is checked. Press Run:

Step 3 code
Edit the code, then run it again

Each try raises ValueError before the item exists. The lambdas (lesson 2.5) wrap each try in a small function, so the loop can call them one at a time. A ValueError is right here: a bad value, not a broken library rule. Library rules get their own errors in C.4.

Try adding a check of your own: a DVD must last at least 1 minute. Where does it go? (A __post_init__ in DVD that calls super().__post_init__() first.)

Fields in the wrong order

The wrong way. Suppose every item should default to the year 2000 when none is given. That means a default on year in the parent. Press Run:

Step 4 code order.py
Edit the code, then run it again

Read the bottom line: TypeError: non-default argument 'author' follows default argument 'year'. It stops on the line with @dataclass over Book, before any book is made.

Here's why. @dataclass writes __init__ with the parent's fields first, then the child's: Book(item_id, title, year=2000, author). In Python, a parameter with no default can't come after one with a default (lesson 2.5): in Book("b1", "Dune", "Frank Herbert"), would "Frank Herbert" be the year or the author?

The fix the reference uses: no defaults in LibraryItem. Take = 2000 away and it runs. (Python 3.10 also added kw_only=True, which makes fields keyword-only so the order no longer matters. It's worth knowing, but plain positional fields are simpler here.)

Search, overridden and extended

Lesson C.5 searches the catalogue, and each item decides whether it matches. A plain item matches on its title. A book also matches on its author or its exact ISBN, so Book extends its parent's method (lesson 4.6): it calls super().matches(text) and adds its own checks.

How the reference does it library/items.py, lines 45–60
@dataclass
class Book(LibraryItem):
    author: str
    isbn: str

    kind: ClassVar[str] = "book"

    def loan_days(self) -> int:
        return 21

    def matches(self, text: str) -> bool:
        text = text.lower()
        return super().matches(text) or text in self.author.lower() or text == self.isbn

    def __str__(self) -> str:
        return f"{self.title} by {self.author} ({self.year})"
Step 5 code
Edit the code, then run it again

ReferenceBook overrides two methods: can_lend() returns False, and loan_days() returns 0. It doesn't raise an error itself. Deciding what to do about an item that can't be lent is the library's job, in C.4.

A DVD's title is Herbert's Garden. Does matches("herbert") find it?

Test the items

On your computer, write library/items.py and save the tests beside it as tests/test_items.py. Here's part of the reference's:

How the reference does it tests/test_items.py, lines 1–19
import pytest

from library.items import DVD, Book, LibraryItem, Magazine, ReferenceBook, item_from_dict


def test_each_kind_has_its_own_loan_period():
    items = [
        Book("b1", "Dune", 1965, "Frank Herbert", "1"),
        DVD("d1", "Up", 2009, 96),
        Magazine("m1", "Garden", 2026, 4),
    ]
    assert [item.loan_days() for item in items] == [21, 7, 14]


def test_library_item_is_abstract():
    with pytest.raises(TypeError):
        LibraryItem("x1", "Nothing", 2000)

pytest.raises (lesson 2.10) passes only if the code inside raises that error. @pytest.mark.parametrize runs one test several times with different values: here, three bad items. Run pytest and every case shows as its own dot.

Where do checks go in a dataclass, since Python writes its __init__?
LibraryItem has year: int = 2000, and its child Book adds author: str. What happens?
dune == copy is True for two separate Book objects. Why?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python