Project
Stage 2 Project: Library Manager (CLI)
Goal: Build a real command-line library system that stores books, members and loans in SQLite, applies the library's rules (loan limit, due dates, late fees) and is covered by pytest tests. Time: ~8–10 hours · Uses: Parts 9–12 (plus everything from Stage 1). Standard library + pytest only.
Project brief
A small school or society library still runs on a register: who took which book, when is it due, who owes a fine. In this project you replace that register with a tool you run from the terminal.
The library has three rules:
| Rule | Value |
|---|---|
| Books one member can have at the same time | 3 |
| Loan period | 14 days |
| Late fee | ₹5 per day late |
A short demo on the sample data (the full list is in tests_manual.md):
$ python main.py --db demo.db --today 2026-11-26 borrow 1 1
Loan #4: 'Malgudi Days' to Aarav Sharma, due 2026-12-10.
$ python main.py --db demo.db --today 2026-11-26 return 1
Returned 'Godaan' (loan #1): 11 days late, fee ₹55.
$ python main.py --db demo.db --today 2026-11-26 borrow 1 6
Loan #5: 'The Guide' to Aarav Sharma, due 2026-12-10.
$ python main.py --db demo.db --today 2026-11-26 borrow 1 8
Loan #6: 'Swami and Friends' to Aarav Sharma, due 2026-12-10.
$ python main.py --db demo.db --today 2026-11-26 borrow 1 7
Error: Aarav Sharma already has 3 books on loan (limit 3).
Files
| File | What it is |
|---|---|
README.md |
This brief and the step-by-step build guide |
library/__init__.py |
Makes library a package (Part 7) |
library/models.py |
Dataclasses Book, Member, Loan and the BookStatus enum |
library/errors.py |
LibraryError and its child exceptions |
library/database.py |
SQLite tables and the Repository class (all the SQL) |
library/service.py |
The Library class: business rules (borrow, return, fees) |
main.py |
The command-line interface (argparse) |
sample_data.sql |
8 books, 4 members and 3 loans to play with |
tests/ |
pytest tests: conftest.py, test_models.py, test_service.py, test_database.py |
tests_manual.md |
CLI commands to try, with the exact expected output |
How to run
Open a terminal in this folder (Python 3.13+). On macOS/Linux type python3 instead of python:
python main.py --help # see all commands
python main.py --db demo.db load-sample # a test file with sample data
python main.py --db demo.db list-books
python main.py --db demo.db borrow 1 6 # member 1 borrows book 6
By default your data is saved in library.db next to main.py. The file is created the first time you run a command.
Global options go before the command:
| Option | What it does |
|---|---|
--db PATH |
Use another SQLite file, e.g. --db demo.db for testing |
--today YYYY-MM-DD |
Pretend today is this date. Makes due dates and fees reproducible |
--verbose |
Show the log messages (Part 11) |
Run the tests (you need pytest: pip install pytest inside your venv, Part 7):
python -m pytest -q tests
Features
| Command | What it does | Example |
|---|---|---|
add-book TITLE AUTHOR YEAR |
Add a book | add-book "Gora" "Rabindranath Tagore" 1910 |
add-member NAME EMAIL |
Add a member (each email only once) | add-member "Kabir Khan" [email protected] |
list-books [--available] |
Show all books, or only the ones on the shelf | list-books --available |
search TEXT |
Find books by title or author (any letter case) | search narayan |
borrow MEMBER_ID BOOK_ID |
Lend a book. Due 14 days later. Max 3 books per member | borrow 1 6 |
return LOAN_ID |
Take a book back. ₹5 per day late | return 1 |
overdue |
Loans past their due date, with the fee so far | --today 2026-12-20 overdue |
report |
Totals: books, members, loans, fees collected | report |
load-sample |
Load sample_data.sql into an empty file |
--db demo.db load-sample |
Error handling: a mistake prints one clear Error: ... line and exits with code 1. Wrong usage (missing command, two instead of a number) is caught by argparse: exit code 2.
| Bad input | Message |
|---|---|
borrow 1 7 (Aarav already has 3) |
Error: Aarav Sharma already has 3 books on loan (limit 3). |
borrow 2 6 (book is out) |
Error: 'The Guide' is already on loan. |
borrow 9 1 |
Error: No member with id 9. |
return 99 |
Error: No loan with id 99. |
add-member "Riya Das" riya.example.com |
Error: Email must contain '@', got 'riya.example.com'. |
Architecture
Each layer only talks to the one below it. The CLI never writes SQL; the database never knows the rules.
you type a command
│
▼
┌───────────────────────────┐
│ main.py (CLI) │ argparse, prints tables, "Error: ..." + exit codes
└────────────┬──────────────┘
│ calls methods like library.borrow(1, 6, today)
▼
┌───────────────────────────┐
│ library/service.py │ Library class: the RULES
│ │ (3 books max, 14 days, ₹5/day)
└────────────┬──────────────┘
│ calls repo.add_loan(loan), repo.get_book(6) ...
▼
┌───────────────────────────┐
│ library/database.py │ Repository class: all the SQL, with ? placeholders
└────────────┬──────────────┘
▼
library.db (SQLite file)
models.py (Book, Member, Loan) and errors.py (LibraryError ...)
are used by every layer.
Why split it like this?
- Easy to test:
test_service.pytests the rules with an in-memory database, no CLI needed. - Easy to change: a web page (Stage 4) could call the same
Libraryclass. Onlymain.pywould change.
Which Parts each piece uses
| Piece | Skills | Part |
|---|---|---|
Book, Member, Loan |
@dataclass, __post_init__, @property, frozen=True |
Part 9 |
BookStatus |
Enum |
Part 9 |
LibraryError and children |
custom exceptions, inheritance, super().__init__() |
Part 6, Part 9 |
Library, Repository |
classes, self, methods, one job per class |
Part 9 |
connect() |
context manager with @contextmanager |
Part 10 |
iter_active_loans(), overdue() |
generators (yield), sum(1 for _ in ...) |
Part 10 |
@command("borrow") |
a decorator that registers a function | Part 10 |
tests/ |
pytest, fixtures, parametrize, pytest.raises, tmp_path |
Part 11 |
caplog in tests/test_service.py |
capturing log messages in a test — new in this project, explained in the Tests section below | this project |
logger.info(...), --verbose |
logging |
Part 11 |
def borrow(self, member_id: int, ...) -> Loan |
type hints | Part 11 |
tables, ? placeholders, UNIQUE, REFERENCES |
SQL, sqlite3, parameterised queries |
Part 12 |
argparse, Path(__file__).parent, datetime |
from the Stage 1 project | Stage 1 project |
Small new tools you will meet
| Tool | What it does | Example |
|---|---|---|
timedelta(days=14) |
a length of time; add it to a date |
date(2026, 11, 26) + timedelta(days=14) → 2026-12-10 |
(d2 - d1).days |
two dates minus each other give a timedelta; .days is the number |
days late |
date.fromisoformat("2026-11-15") |
text YYYY-MM-DD → date |
reading dates back from SQLite |
cur.lastrowid |
the id SQLite gave the row you just inserted | book.id = cur.lastrowid |
sqlite3.Row |
rows you can read by column name | row["title"] |
raise X from None |
raise a new error and hide the old one in the traceback | turn IntegrityError into LibraryError |
argparse.ArgumentTypeError |
error a type= function raises; argparse prints it as a usage error |
a bad --today |
Build it step by step
Build in small steps. Run your tests after every step. Do not open the solution files until you have tried each step yourself.
Create the folders first:
project-library-manager/
├── library/
│ └── __init__.py ← can hold just a docstring
├── tests/
└── main.py
Step 1: Errors first (Parts 6, 9)
What and why: decide what can go wrong before writing the logic. One base class means main.py needs only one except.
Each child error builds its own message, so every "not found" message looks the same.
class LibraryError(Exception):
"""Base class: any problem the user can fix."""
class BookNotFoundError(LibraryError):
"""No book with this id."""
def __init__(self, book_id: int) -> None:
super().__init__(f"No book with id {book_id}.")
self.book_id = book_id # keep the id for code that needs it
try:
raise BookNotFoundError(99)
except LibraryError as e: # the parent catches the child
print(e) # No book with id 99.
Add the same for MemberNotFoundError, LoanNotFoundError, BookNotAvailableError(title) and LoanLimitError(member_name, limit).
✅ Test: issubclass(LoanLimitError, LibraryError) → True.
Step 2: Models as dataclasses (Part 9)
What and why: a Book with named fields is clearer than a dict or a tuple, and @dataclass writes __init__, __repr__ and __eq__ for you.
Put checks in __post_init__: it runs right after __init__, so a bad Book can never exist.
from dataclasses import dataclass
from enum import Enum
class BookStatus(Enum):
AVAILABLE = "available"
ON_LOAN = "on loan"
@dataclass
class Book:
title: str
author: str
year: int
status: BookStatus = BookStatus.AVAILABLE
id: int | None = None # None until the database saves it
def __post_init__(self) -> None:
self.title = self.title.strip()
if not self.title:
raise ValueError("Title cannot be empty.") # the app uses LibraryError
@property
def is_available(self) -> bool:
return self.status is BookStatus.AVAILABLE
book = Book(" Godaan ", "Munshi Premchand", 1936)
print(book.title, book.is_available) # Godaan True
print(book.status.value) # available
Member(name, email, id=None) cleans the email with .strip().lower() and needs an @.
Loan holds book_id, member_id, borrowed_on, due_on, returned_on=None, fee=0, id=None, plus:
from datetime import date
def days_late(due_on: date, today: date) -> int: # Loan.days_late(self, today)
return max(0, (today - due_on).days)
print(days_late(date(2026, 11, 15), date(2026, 11, 26))) # 11
print(days_late(date(2026, 11, 15), date(2026, 11, 10))) # 0
✅ Test: write tests/test_models.py now (see Step 6 for how), or check in the REPL that Book(" ", "x", 2000) raises.
🔍 Going deeper: the default values (
status,id) must come after the fields without defaults, the same rule as function parameters (Part 5).@dataclass(frozen=True)(used forOverdueLoan) makes objects read-only, good for report rows nobody should change.
Step 3: The database layer (Part 12, Part 10)
What and why: the data must outlive the program. SQLite keeps it in one file and checks rules for you (NOT NULL, UNIQUE, REFERENCES).
Three tables. A loan points to a book and a member by their ids (a foreign key: a column that holds the id of a row in another table).
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY, -- SQLite picks the next id for you
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'available'
);
CREATE TABLE IF NOT EXISTS members (
id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS loans (
id INTEGER PRIMARY KEY,
book_id INTEGER NOT NULL REFERENCES books(id),
member_id INTEGER NOT NULL REFERENCES members(id),
borrowed_on TEXT NOT NULL, -- 'YYYY-MM-DD'
due_on TEXT NOT NULL,
returned_on TEXT, -- NULL while the book is out
fee INTEGER NOT NULL DEFAULT 0
);
Open the connection with a context manager, so it is always committed (or rolled back) and closed:
import sqlite3
from collections.abc import Iterator
from contextlib import contextmanager
@contextmanager
def connect(path: str) -> Iterator[sqlite3.Connection]:
conn = sqlite3.connect(path)
conn.row_factory = sqlite3.Row # read columns by name: row["title"]
conn.execute("PRAGMA foreign_keys = ON")
try:
with conn: # commit on success, rollback on error
yield conn
finally:
conn.close()
with connect(":memory:") as conn: # ":memory:" = a database in RAM
conn.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT)")
cur = conn.execute("INSERT INTO books (title) VALUES (?)", ("Gitanjali",))
print(cur.lastrowid) # 1
row = conn.execute("SELECT * FROM books WHERE id = ?", (1,)).fetchone()
print(row["title"]) # Gitanjali
Then a Repository class holds the connection and has one method per query: add_book, get_book, list_books(available_only), search_books, set_book_status, add_member, get_member, add_loan, get_loan, close_loan, count_active_loans(member_id), iter_active_loans() and a few count_* methods. Each one turns rows into dataclasses, so the rest of the app never sees SQL.
- Always use
?placeholders. Search usesLIKE ?withf"%{text}%"as the value, not inside the SQL. - Store dates as
d.isoformat()and read them back withdate.fromisoformat(text). - In
add_member, catchsqlite3.IntegrityError(theUNIQUErule) and raiseLibraryError("Email ... is already registered."). iter_active_loans()is a generator: ityields oneLoanat a time instead of building a list.
✅ Test: tests/test_database.py: save a book, read it back, compare with ==.
🔍 Going deeper: never build SQL with f-strings.
f"... WHERE title LIKE '%{text}%'"lets a user type' OR 1=1 --and change your query (SQL injection).test_search_text_is_a_parameter_not_sqlproves the?version is safe. Also:sqlite3's built-in date converters are deprecated since Python 3.12, which is why we convert dates ourselves.
Step 4: The rules in a service class (Part 9)
What and why: "3 books max", "14 days", "₹5 per day" are the library's rules. Keep them in one class, with constants at the top, so a rule change is a one-line change.
MAX_LOANS = 3
LOAN_DAYS = 14
LATE_FEE_PER_DAY = 5 # rupees
Library.borrow(member_id, book_id, today) checks in this order, raising the matching error:
- the member exists →
MemberNotFoundError - the book exists →
BookNotFoundError - the book is available →
BookNotAvailableError - the member has fewer than
MAX_LOANSactive loans →LoanLimitError
Then it saves the loan (due_on = today + timedelta(days=LOAN_DAYS)) and marks the book ON_LOAN.
Library.return_book(loan_id, today) finds the loan, refuses a loan already returned, sets returned_on and fee, and marks the book AVAILABLE again:
from datetime import date, timedelta
LOAN_DAYS = 14
LATE_FEE_PER_DAY = 5
borrowed_on = date(2026, 11, 1)
due_on = borrowed_on + timedelta(days=LOAN_DAYS)
returned_on = date(2026, 11, 26)
days_late = max(0, (returned_on - due_on).days)
print(due_on, days_late, days_late * LATE_FEE_PER_DAY) # 2026-11-15 11 55
✅ Test: tests/test_service.py: borrow sets the due date, the 4th book raises LoanLimitError, a return 11 days late costs 55.
🔍 Going deeper: why is
todaya parameter instead ofdate.today()insideborrow()? A test written on 26 November would fail on 27 November. Passing the date in (dependency injection: giving a function what it needs instead of letting it fetch it) makes the tests and--todayreproducible forever.
Step 5: Overdue report and totals (Part 10)
What and why: the librarian's daily question is "Who is late and how much do they owe?"
overdue(today) is a generator: loop over repo.iter_active_loans(), skip loans with days_late == 0 (continue), and yield an OverdueLoan(loan, book_title, member_name, days_late, fee).
def numbers_over(limit: int, numbers: list[int]):
for n in numbers:
if n <= limit:
continue
yield n
late = numbers_over(0, [0, 11, 0, 3])
print(list(late)) # [11, 3]
print(sum(1 for _ in numbers_over(0, [0, 5]))) # 1 (count without a list)
report(today) returns a frozen LibraryReport dataclass with the totals. It counts overdue loans with sum(1 for _ in self.overdue(today)).
✅ Test: borrow on 2026-11-26, then list(library.overdue(date(2026, 12, 13))) has one item with days_late == 3 and fee == 15.
Step 6: Tests with pytest (Part 11)
What and why: the rules are money. A test suite proves they work and keeps working after every change.
conftest.py holds fixtures: functions that prepare what a test needs. pytest runs a fixture for every test that names it as a parameter.
import pytest
@pytest.fixture
def repo():
"""A fresh, empty database in memory for every test."""
with connect(":memory:") as conn:
repository = Repository(conn)
repository.create_schema()
yield repository # the test runs here, then it closes
@pytest.fixture
def library(repo): # a fixture can use another fixture
lib = Library(repo)
lib.add_book("Malgudi Days", "R. K. Narayan", 1943)
lib.add_member("Aarav Sharma", "[email protected]")
return lib
A test is a function named test_... that uses assert:
TODAY = date(2026, 11, 26)
@pytest.mark.parametrize(("days_late", "fee"), [(1, 5), (11, 55), (30, 150)])
def test_late_fee(library, days_late, fee):
loan = library.borrow(1, 1, TODAY)
returned = library.return_book(loan.id, loan.due_on + timedelta(days=days_late))
assert returned.fee == fee
def test_return_unknown_loan(library):
with pytest.raises(LoanNotFoundError, match="No loan with id 7."):
library.return_book(7, TODAY)
Other tools used in the tests: tmp_path (a temporary folder, for a real .db file), and caplog (captures log messages).
✅ Test: python -m pytest -q tests → 34 passed.
🔍 Going deeper:
conftest.pyadds the project folder tosys.path, soimport libraryworks whether you run pytest from this folder or from the repo root. In Stage 3 (Part 16: Packaging) apyproject.tomlandpip install -e .do this properly.
Step 7: Logging (Part 11)
What and why: print is for the user. Log messages are for you, the developer: what happened, when, and in which module. You can turn them on and off without changing code.
import logging
logger = logging.getLogger(__name__) # in service.py the name is "library.service"
logger.info("Loan #%s: book #%s to member #%s", 6, 9, 5)
main.py sets the level once: WARNING by default (quiet), INFO with --verbose.
✅ Test: python main.py --db demo.db --verbose borrow 5 9 shows an INFO library.service: ... line.
🔍 Going deeper:
logger.info("... %s", value)(not an f-string) only builds the text if the message is actually shown. Logs go to stderr, sopython main.py list-books > books.txtsaves only the table.
Step 8: The CLI with argparse and a decorator (Stage 1 project, Part 10)
What and why: the same argparse subcommands as the expense tracker, plus three global options: --db, --today, --verbose.
Instead of a long match, each handler registers itself with a small decorator:
COMMANDS = {} # command name -> function
def command(name):
"""Decorator: remember the function below it under `name`."""
def register(func):
COMMANDS[name] = func
return func # the function itself is unchanged
return register
@command("report")
def handle_report(library, args):
print("report for", args)
COMMANDS["report"](None, "today") # report for today
run(args) opens the database once, creates the tables, and calls the handler: COMMANDS[args.command](Library(repo), args). Because the whole command runs inside one with connect(...), it is one transaction: if borrow failed after saving the loan but before marking the book, SQLite would undo both.
For --today, give argparse a type= function that raises argparse.ArgumentTypeError for a bad date (2026-02-30), so argparse prints a usage error with exit code 2.
✅ Test: python main.py --help lists all 9 commands.
Step 9: Errors and exit codes (Part 6)
What and why: one place turns every error into one clear line.
def main() -> int:
args = build_parser().parse_args()
try:
run(args)
except LibraryError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
except sqlite3.Error as e: # broken file, folder missing ...
print(f"Error: database problem with {args.db} ({e}).", file=sys.stderr)
return 1
return 0
✅ Test: run every command in tests_manual.md. The output must match exactly.
🔍 Going deeper: a real bug (say a
TypeError) is not caught here, so it still crashes with a full traceback you can fix. CatchingExceptionwould hide your bugs behind a friendly message.
Step 10: Sample data (Part 12)
What and why: a demo needs data. sample_data.sql is plain SQL INSERT statements; repo.run_script(path) runs it with conn.executescript().
It uses fixed ids (so the manual tests can say "book 6"), so load-sample refuses a file that already has books or members.
✅ Test: python main.py --db demo.db load-sample → Loaded sample data: 8 books, 4 members, 2 active loans.
Stretch goals
- 🟢
list-memberscommand: id, name, email and how many books each one has. - 🟢
history MEMBER_ID: every loan of one member, with dates and fees. - 🟡 More than one copy of a book: add a
copiescolumn and count active loans instead of usingstatus. - 🟡
renew LOAN_ID: add 14 more days, but only once and only if the loan is not overdue. - 🟡 Members pay fees: a
paymentstable and abalanceper member; block borrowing above ₹100 owed. - 🔴 Export the overdue report to CSV (Part 8) and test it with
tmp_path. - 🔴 Check your types with
mypy library main.pyand your style withruff check .(Part 11).
Checklist
- I can model data with
@dataclass,__post_init__checks and anEnum. - I can build a family of custom exceptions with one base class.
- I can write SQLite tables with
PRIMARY KEY,UNIQUEandREFERENCES. - I always use
?placeholders, never f-strings, in SQL. - I can write a context manager that commits, rolls back and closes.
- I can keep business rules in a service class and pass
todayin. - I can write pytest tests with fixtures,
parametrizeandpytest.raises. - I can add logging and turn it on with a
--verboseflag. -
python -m pytest -q testspasses and every command intests_manual.mdgives the expected output.
Next
🎉 Stage 2 done! Go back to the roadmap and get ready for Stage 3: Advanced (concurrency, Python internals, advanced typing, packaging).