The catalogue and search
Last updated
The library needs somewhere to keep its items, and a way to find them. In this lesson you'll write catalogue.py: a Catalogue that works with for, in and len() like a built-in collection, refuses duplicate ids, and searches by title, author or ISBN with a comprehension and sorted(key=…).
By the end of this lesson you can
- Make your own collection work with
for,inandlen() - Search with a comprehension and let each item decide if it matches
- Sort objects with
key=, and explain the error without it
A collection of your own
The catalogue holds every item, keyed by its id in a dictionary (lesson 2.2), so finding b2 among thousands is one step. The dictionary is "protected", _items, so items only come in through add(), which can check them.
Code that uses the catalogue shouldn't need to know there's a dictionary inside. It should work like any other collection: loop over it with for, ask in, and get its size with len(). Lesson 4.11 showed how: each of those calls a dunder method, so the catalogue writes those three.
library/catalogue.py, lines 26–33def __iter__(self) -> Iterator[LibraryItem]: return iter(self._items.values()) def __len__(self) -> int: return len(self._items) def __contains__(self, item_id: object) -> bool: return item_id in self._items
__iter__ hands back an iterator over the items, and for uses it. __len__ is what len() calls. __contains__ is what in calls, and here it checks ids.
The items come out in the order they were added, because dictionaries keep that order.
Ids are unique
Two items with the same id would make get() ambiguous, so add() refuses a second one with AlreadyExists, and get() raises NotFound for an unknown id, both from C.4's family. remove() reuses get(), so it refuses unknown ids too, without writing the check again.
library/catalogue.py, lines 13–24def add(self, item: LibraryItem) -> None: if item.item_id in self._items: raise AlreadyExists(f"there's already an item {item.item_id}") self._items[item.item_id] = item def get(self, item_id: str) -> LibraryItem: if item_id not in self._items: raise NotFound(f"no item {item_id}") return self._items[item_id] def remove(self, item_id: str) -> LibraryItem: return self._items.pop(self.get(item_id).item_id)
get() raises rather than returning None, so a missing item can't slip on into the code as None and fail further away, where the cause is harder to see.
Search
The search is one comprehension: every item that matches. Which items match isn't the catalogue's business: it asks each item, and each kind answers its own way (C.2, step 5). Then the results are sorted by title, ignoring capitals.
library/catalogue.py, lines 35–38def search(self, text: str) -> list[LibraryItem]: """Items whose title, author or ISBN matches, in title order.""" found = [item for item in self if item.matches(text.strip())] return sorted(found, key=lambda item: item.title.lower())
"e" finds five items: four with an e in the title, and Middlemarch, whose author has one. "eliot" is found only through the author, and the ISBN only through Book.matches. Nothing matching gives an empty list, not an error: "no results" is a normal answer to a search.
The last lines use the rest of the catalogue: sorted_by sorts by any key, reverse=True puts the newest first, and isinstance picks out the books.
Sorting objects
Why does sorted_by need a key? The wrong way: sort two books with none. Press Run:
Read the bottom line: TypeError: '<' not supported between instances of 'Book' and 'Book'. To sort, Python compares items with <. Numbers and text know how, but should Emma come before Dune? By title, by year, by author? Python won't guess, and @dataclass doesn't write < unless you ask for order=True.
key= answers the question: a function that turns each item into something Python can compare. Change line 7 to sorted(books, key=lambda book: book.title) and it runs, with Dune first. Try book.year instead, and Emma is first.
Check what you learned
On your computer, write library/catalogue.py, and use it in desk.py in place of any stand-in from C.4. The reference's tests are in tests/test_catalogue.py.
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.