Capstone · lesson 4 of 9
Parts in this lesson
ALoan(frozen=True)a loan that never changes
Bdataclasses.replace()a changed copy
CLibrary(clock)where “today” comes from
Dclass NotAvailable(LibraryError)4.8: an error family
Edate + timedelta(days=…)2.7: due dates

Loans and returns

Last updated

Now the heart of the system: lending and taking back. In this lesson you'll write a Loan that never changes, a clock that says what day it is, the library's family of errors, and Library itself, whose lend() and give_back() keep every rule: no item is lent twice, no member goes over their limit, and late returns pay their policy's fine.

By the end of this lesson you can

  • Record a loan with datetime.date due dates in a frozen dataclass
  • Pass a clock object in, so “today” can be fixed for examples and tests
  • Write a method that does every check before any change
  • Raise the library's own errors, and catch them all by their parent

A loan that never changes

A loan records four things: which item, which member, the day it was lent, and the day it's due. It also gets a fifth when the item comes back. In 4.P a Loan held the item and member objects themselves. Here it holds their ids, which are plain text. That makes a loan easy to save in C.6, and the library can always look the objects up from their ids.

How the reference does it library/loans.py, lines 7–30
@dataclass(frozen=True)
class Loan:
    item_id: str
    member_id: str
    lent_on: date
    due_on: date
    returned_on: date | None = None

    def __post_init__(self) -> None:
        if self.due_on < self.lent_on:
            raise ValueError("a loan can't be due before it starts")

    def is_open(self) -> bool:
        return self.returned_on is None

    def days_late(self, on: date) -> int:
        return max((on - self.due_on).days, 0)

    def is_overdue(self, on: date) -> bool:
        return self.is_open() and self.days_late(on) > 0

    def closed(self, on: date) -> Self:
        """The same loan, given back on that day. The loan itself never changes."""
        return replace(self, returned_on=on)

It's frozen, so once made, a loan's dates can't be moved. But a loan does need to change once, when the item comes back. closed() doesn't change the loan. It returns a new loan, the same but with returned_on set, made by dataclasses.replace. The library swaps the old loan for the new one.

Step 1 code
Edit the code, then run it again

Dates come from datetime (lesson 2.7). Subtracting two dates gives a timedelta, and .days is its length in days, so days_late is never negative thanks to max(…, 0). On the last line, the old loan is still open: closed() changed nothing.

Where today comes from

Lending needs today's date. date.today() gives it, but then every run of an example, and every test, would get a different date, and "4 days late" would be impossible to check. So the library doesn't ask the computer for the date. It's handed a clock when it's made, and asks the clock:

How the reference does it library/clock.py
"""Where the library gets today's date from."""
from datetime import date, timedelta
from typing import Protocol


class Clock(Protocol):
    def today(self) -> date: ...


class SystemClock:
    """The real date, from the computer."""

    def today(self) -> date:
        return date.today()


class FixedClock:
    """A date that only changes when you tell it to: for tests and examples."""

    def __init__(self, day: date) -> None:
        self._day = day

    def today(self) -> date:
        return self._day

    def advance(self, days: int) -> None:
        self._day += timedelta(days=days)

Clock is a protocol (lesson 4.14): anything with a today() method that returns a date will do. SystemClock asks the computer. FixedClock keeps a date of its own, and only moves when you call advance().

Step 2 code
Edit the code, then run it again

Handing an object what it needs, instead of letting it make its own, is called dependency injection. The real program gets a SystemClock (it's the default, so Library() uses one). Examples and tests get a FixedClock and can jump 25 days in one line.

Why does Library take a clock instead of calling date.today() itself?

Lend: every check before any change

Now desk.py and its Library. It holds the catalogue (C.5 builds it), the members, and one list of every loan, open and closed. Here's how the pieces fit:

desk.py and what it uses
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]
FixedClock in library/clock.py
  • #_day: date
  • +__init__(day: date)
  • +today(): date
  • +advance(days: int)
«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"
  • Class Catalogue; attributes: _items; methods: __init__, add, get, remove, __iter__, __len__, __contains__, search, sorted_by.
  • Class FixedClock; attributes: _day; methods: __init__, today, advance.
  • 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.
  • 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.
  • Library holds one FixedClock in _clock.
  • Library holds one Catalogue in catalogue.
  • Library holds many Member in _members.
  • Library holds many Loan in _loans.
  • Member holds one BorrowingPolicy in _policy.

lend() is the most careful method in the system:

How the reference does it library/desk.py, lines 58–70
    def lend(self, item_id: str, member_id: str) -> Loan:
        """Lends an item, or raises a LibraryError and changes nothing."""
        item = self.catalogue.get(item_id)
        member = self.member(member_id)
        if not item.can_lend():
            raise NotAvailable(f"{item.title} can't be borrowed")
        if self.loan_of(item_id):
            raise NotAvailable(f"{item.title} is already on loan")
        member.check_can_borrow(len(self.loans_of(member_id)))
        today = self.today()
        loan = Loan(item_id, member_id, today, today + timedelta(days=item.loan_days()))
        self._loans.append(loan)
        return loan

It finds the item and the member, and refuses if either id is unknown. Then three rules: the item can be lent at all, it isn't already out, and the member has room. Only after every check passes does anything change: one new Loan, appended on line 69. A refused loan leaves the library exactly as it was. Lesson 4.P showed what goes wrong otherwise.

There's no "on loan" flag on items. Whether an item is out is worked out from the loans (loan_of()), so the two can never disagree.

Refusals the library can name

The wrong way. Lend Dune to Sam, then try to lend it to Ana too. Press Run:

Step 4 code
Edit the code, then run it again

The traceback ends library.errors.NotAvailable: Dune is already on loan, raised from lend() in library/desk.py and reached from line 14. Nothing caught it, so the program stopped, and Lent twice? never printed. That's right: the library refused. But a menu can't stop every time someone asks for a book that's out.

The refusals are a family (lesson 4.8), in errors.py. Open its tab. Every one is a child of LibraryError, so code that drives the library can catch the parent once and handle them all:

Step 4 code
Edit the code, then run it again

One except LibraryError catches NotAvailable twice and NotFound once, and type(e).__name__ shows which. A ValueError, a bad value like a blank name, isn't in the family: it's a mistake in the code, not a refusal, so it isn't caught here.

Give back, and pay the fine

The end of that example moved the clock on 25 days and took both items back. give_back() finds the open loan, swaps it for its closed copy, and asks the member's policy for the fine:

How the reference does it library/desk.py, lines 72–81
    def give_back(self, item_id: str) -> int:
        """Takes an item back and returns the fine in cents, 0 if it's on time."""
        item = self.catalogue.get(item_id)
        loan = self.loan_of(item_id)
        if loan is None:
            raise NotOnLoan(f"{item.title} isn't on loan")
        today = self.today()
        self._loans[self._loans.index(loan)] = loan.closed(today)
        policy = self.member(loan.member_id).get_policy()
        return policy.fine_for(loan.days_late(today))

Dune was due back on 23 March and came back on 27 March: 4 days late, and Sam is a standard member, so 4 × 25 = 100 cents. The DVD was due on 9 March: 18 days late, and Ana is a student, so 18 × 10 = 180, under her $2 cap. Afterwards there are 0 open loans but 2 loans in all: closed loans stay, which C.8's reports need.

Try in lend.py: make Ana a staff member and run it again. Her fine is 0, and give_back() didn't change.

A standard member returns a book 30 days late. What does give_back return?

Check what you learned

On your computer, write clock.py, loans.py and desk.py. desk.py needs a Catalogue: until C.5, a small class with add() and get() over a dictionary will do. The reference's tests for this lesson are in tests/test_desk.py.

lend() refuses because the member is at their limit. What has changed in the library?
How does a loan get its returned_on date, when a Loan is frozen?
The menu has one except LibraryError. Which of these does it catch?

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