Capstone · lesson 1 of 9
Parts in this lesson
Alibrary/__init__.pymakes a folder a package
Bpython -m libraryruns a package
Cpyproject.tomldescribes the project
Dpython -m venv .venv2.9: a project's own Python
Epytest, ruff2.9, 2.10: checks

Plan and set up

Last updated

The capstone builds a whole program on your own computer: a library management system that keeps a catalogue, lends and takes back items, charges fines, searches, saves between runs and has a menu. This lesson plans it as a set of classes, and sets up the project folder: a package, a virtual environment, pytest and ruff.

By the end of this lesson you can

  • Turn the nouns and verbs of a problem into classes and methods
  • Lay out a program as a package with one module for each job
  • Run a package with python -m, and explain the error when it's run the wrong way
  • Set up a project with a virtual environment, pyproject.toml, pytest and ruff

What you'll build

The capstone puts everything from the course into one program: a library management system. It keeps a catalogue of books, DVDs and magazines, registers members, lends items and takes them back with due dates, charges fines for late returns, searches the catalogue, and saves it all to a file between runs. A menu drives it.

Here's the finished program running in the page. The input box types the commands. Press Run:

Step 1 code tour.py
Edit the code, then run it again

You'll build it on your own computer, one part a lesson. You've written much of it already: the fine rules in 1.P, the catalogue search in 2.P, and the loan desk in 4.P.

There's also a finished reference version, written for this course. Each lesson shows how the reference does it, like this. Your code doesn't have to match it line for line.

How the reference does it README.md, lines 1–5
# Library

A simple library management system for the command line. It keeps a catalogue of books, DVDs and magazines, registers members, lends items and takes them back with due dates, charges fines for late returns, searches the catalogue, and saves everything to `library.json` between runs.

This is the reference version of the Simple Python capstone.

Nouns become classes, verbs become methods

A good first plan for a program made of classes: write down what it has to do in plain words, then look at the words.

A library keeps a catalogue of items: books, DVDs and magazines. Members borrow items, and each loan is due back on a date. When an item is given back late, the member pays a fine. Anyone can search the catalogue. Everything is saved to a file.

The nouns (things) become classes, and the verbs (actions) become methods on them:

From words to classes
NounWhat it has or doesIn the code
item (book, DVD, magazine)has a title, a year, a loan periodLibraryItem and its children
memberhas a name and a borrowing limitMember, with a BorrowingPolicy
loanis due back on a dateLoan
catalogueholds every item, is searchedCatalogue
librarylends, takes back, charges finesLibrary: lend(), give_back()
filekeeps everything between runsJsonStorage: save(), load()

This program uses the classes that way. Nouns become objects, verbs become method calls:

Step 2 code nouns.py
Edit the code, then run it again

And here's the plan as a class diagram, read as in lesson 4.1: an open triangle points from a child to its parent, and a diamond marks a class that holds others.

The library system
100%
Library in library/desk.py
  • #_clock: FixedClock
  • +catalogue: Catalogue
  • #_members: dict[str, Member]
  • #_loans: list[Loan]
  • +__init__(clock: Clock | None)
  • +today(): date
  • +join(member: Member)
  • +member(member_id: str): Member
  • +members(): tuple[Member, ...]
  • +loans(): tuple[Loan, ...]
  • +open_loans(): tuple[Loan, ...]
  • +loans_of(member_id: str): tuple[Loan, ...]
  • +loan_of(item_id: str): Loan | None
  • +is_available(item: LibraryItem): bool
  • +lend(item_id: str, member_id: str): Loan
  • +give_back(item_id: str): int
  • +restore(items: list[LibraryItem], members: list[Member], loans: list[Loan])
Catalogue in library/catalogue.py
  • #_items: dict[str, LibraryItem]
  • +__init__()
  • +add(item: LibraryItem)
  • +get(item_id: str): LibraryItem
  • +remove(item_id: str): LibraryItem
  • +__iter__(): Iterator[LibraryItem]
  • +__len__(): int
  • +__contains__(item_id: object): bool
  • +search(text: str): list[LibraryItem]
  • +sorted_by(key: Callable[[LibraryItem], Any], reverse: bool): list[LibraryItem]
«abstract» LibraryItem in library/items.py
  • +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, frozen» Loan in library/loans.py
  • +item_id: str
  • +member_id: str
  • +lent_on: date
  • +due_on: date
  • +returned_on: date | None
  • +__post_init__()
  • +is_open(): bool
  • +days_late(on: date): int
  • +is_overdue(on: date): bool
  • +closed(on: date): Self
  • +to_dict(): dict[str, Any]
  • +from_dict(data: dict[str, Any]): Self
«dataclass, frozen» BorrowingPolicy in library/members.py
  • +name: str
  • +max_loans: int
  • +fine_per_day: int
  • +max_fine: int
  • +fine_for(days_late: int): int
Member in library/members.py
  • #_member_id: str
  • #_name: str
  • #_policy: BorrowingPolicy
  • +__init__(member_id: str, name: str, policy: BorrowingPolicy)
  • +get_id(): str
  • +get_name(): str
  • +set_name(name: str)
  • +get_policy(): BorrowingPolicy
  • +set_policy(policy: BorrowingPolicy)
  • +check_can_borrow(loans_now: int)
  • +__str__(): str
  • +__eq__(other: object): bool
  • +__hash__(): int
  • +to_dict(): dict[str, Any]
  • +from_dict(data: dict[str, Any]): "Member"
«dataclass» Book in library/items.py
  • +author: str
  • +isbn: str
  • +kind: str
  • +loan_days(): int
  • +matches(text: str): bool
  • +__str__(): str
«dataclass» DVD in library/items.py
  • +minutes: int
  • +kind: str
  • +loan_days(): int
  • +__str__(): str
«dataclass» Magazine in library/items.py
  • +issue: int
  • +kind: str
  • +loan_days(): int
  • +__str__(): str
«dataclass» ReferenceBook in library/items.py
  • +kind: str
  • +loan_days(): int
  • +can_lend(): bool
  • +__str__(): str
  • Class Catalogue; attributes: _items; methods: __init__, add, get, remove, __iter__, __len__, __contains__, search, sorted_by.
  • Class Library; attributes: _clock, catalogue, _members, _loans; methods: __init__, today, join, member, members, loans, open_loans, loans_of, loan_of, is_available, lend, give_back, restore.
  • 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__.
  • Dataclass Loan; attributes: item_id, member_id, lent_on, due_on, returned_on; methods: __post_init__, is_open, days_late, is_overdue, closed, to_dict, from_dict.
  • Dataclass BorrowingPolicy; attributes: name, max_loans, fine_per_day, max_fine; methods: fine_for.
  • Class Member; attributes: _member_id, _name, _policy; methods: __init__, get_id, get_name, set_name, get_policy, set_policy, check_can_borrow, __str__, __eq__, __hash__, to_dict, from_dict.
  • Catalogue holds many LibraryItem in _items.
  • Library holds one Catalogue in catalogue.
  • Library holds many Member in _members.
  • Library holds many Loan in _loans.
  • Member holds one BorrowingPolicy in _policy.

You don't need to read every line of it now. Each lesson fills in one part.

A new rule: “members can reserve an item that's on loan.” What would reserve most likely become?

One module for each job

A program this size doesn't fit well in one file. It's split into modules (lesson 2.7), one for each job, inside a folder called library. A folder of modules with an __init__.py file in it is a package, and its modules are imported with a dot: from library.items import Book.

The modules, and the lesson that builds each one
ModuleWhat it holdsLesson
errors.pyEverything the library refuses to doC.4
items.pyBooks, DVDs, magazines and reference booksC.2
members.pyMembers and borrowing policiesC.3
loans.pyA loan, and its due dateC.4
clock.pyWhere “today” comes fromC.4
desk.pyThe library and its lending rulesC.4
catalogue.pyEvery item by id, with searchC.5
storage.pySaving and loadingC.6
cli.py, sample.pyThe menu, and a starting stockC.7
reports.pyOverdue, most borrowed, historyC.8

__init__.py can be empty. The reference's has only a docstring, the sentence in quotes that says what the package is:

How the reference does it library/__init__.py
"""A simple library management system: items, members, loans, fines, search and saving."""

A module imports only what it needs, and a module lower down the list never imports one higher up. items.py knows nothing about menus, and cli.py uses everything. That way, a change to the menu can't break an item.

Make the project

Now on your computer. Make a project folder with a virtual environment, and install pytest and ruff into it, as in lessons 2.9 and 2.10. On macOS or Linux, use python3 and source .venv/bin/activate.

Terminal
mkdir library-project
cd library-project
python -m venv .venv
.venv\Scripts\Activate.ps1
(.venv) $ python -m pip install pytest ruff
Successfully installed ... pytest-9.0.1 ruff-0.14.6

Then make this layout. The library folder is the package, and tests holds the tests:

The project folder
library-project/
  pyproject.toml
  README.md
  library/
    __init__.py
    __main__.py
    items.py   members.py   loans.py   ...
  tests/
    conftest.py
    test_items.py   ...
  .venv/

pyproject.toml describes the project: its name, which Python it needs, and settings for the tools. It's a TOML file, a plain-text format of [sections] and name = value lines. Here's the reference's:

pyproject.toml
[project]
name = "library"
version = "1.0.0"
description = "A simple library management system: the Simple Python capstone."
requires-python = ">=3.12"
dependencies = []

[dependency-groups]
dev = ["pytest", "ruff"]

[tool.pytest.ini_options]
testpaths = ["tests"]

[tool.ruff]
line-length = 100

requires-python says the package needs Python 3.12 or newer. [dependency-groups] lists the tools a developer needs. Nothing under dependencies means the program itself uses only the standard library. The last two sections tell pytest where the tests are, and let ruff allow lines up to 100 characters.

Run it as a package

A package runs with python -m and its name. Python then looks for a module called __main__.py inside it and runs that. The reference's is two lines:

How the reference does it library/__main__.py
"""Lets the package run with: python -m library"""
from library.cli import main

main()

Make __main__.py and a small cli.py with a main() that prints a line, and run it from the project folder:

Terminal
(.venv) $ python -m library
Library open on 2026-12-05, with 0 items. Type help for commands.
> quit
Saved. Goodbye.

The wrong way. Run the menu module as a script instead, by its path:

Terminal
(.venv) $ python library/cli.py
Traceback (most recent call last):
  File "library-project/library/cli.py", line 4, in <module>
    from library import reports, sample
ModuleNotFoundError: No module named 'library'

Read the bottom line first: No module named 'library'. The package is right there, so why? When Python runs a file by its path, it looks for imports in that file's folder, which is inside library/. From in there, there's no library folder to find. python -m library, run from the project folder, looks in the project folder, where library/ is. So always run the program with -m, from the folder that holds the package.

A misspelled name gives a near relative of that error. Press Run:

Step 5 code main.py
Edit the code, then run it again

ImportError: cannot import name 'Shelf' from 'library.items'. This time Python found the module, but nothing called Shelf inside it. ModuleNotFoundError means "no such module", and ImportError means "the module's there, but not that name". Take Shelf out and it runs.

Last, a first test, so the tools have something to check. Save this as tests/test_smoke.py:

import library


def test_package_imports():
    assert library.__doc__
Terminal
(.venv) $ pytest
=================== test session starts ===================
collected 1 item

tests/test_smoke.py .                                [100%]

==================== 1 passed in 0.02s ====================
(.venv) $ ruff check
All checks passed!

Check what you learned

What makes the folder library a package you can import from?
python library/cli.py stops with No module named 'library'. What should you type instead, from the project folder?
In the plan, why is “member” a class but “borrow” a method?

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