Reports
Last updated
A library keeps every loan, so it can answer questions about them: what's overdue, what's popular, what has this member borrowed? In this lesson you'll write reports.py with generators, functions that hand back results one at a time with yield, and Counter from the standard library.
By the end of this lesson you can
- Write a generator with
yield, and say when its code runs - Explain why a generator has no
len()and can only be looped over once - Count things with
collections.Counter - Write a report that works on any iterable of loans (duck typing)
Three reports
The library keeps every loan, open and closed (C.4), so a report is a question asked of that list. reports.py has three for the menu:
- overdue: every open loan past its due date, with how many days late, longest overdue first;
- most borrowed: the items lent most often;
- history: everything one member has borrowed, newest first.
Here's a month at the library: three loans, a DVD back late and lent again, then 17 more days. Press Run:
Most borrowed is a count, and the standard library has a class for counting. Counter takes anything you can loop over and counts each value. most_common(2) gives the top two as (value, count) pairs. The DVD d1 was lent twice.
History goes newest first. reversed() walks the loans from the end without copying them.
Generators: one at a time
Look at overdue and history. There's no list and no return: they yield instead.
library/reports.py, lines 10–29def overdue(library: Library) -> Iterator[tuple[Loan, int]]: """Every open loan that's late today, with how many days late, longest overdue first.""" today = library.today() late = (loan for loan in library.open_loans() if loan.is_overdue(today)) for loan in sorted(late, key=lambda loan: loan.due_on): yield loan, loan.days_late(today) def most_borrowed(library: Library, how_many: int = 3) -> list[tuple[str, int]]: """The item ids lent most often, with their counts.""" counts = Counter(loan.item_id for loan in library.loans()) return counts.most_common(how_many) def history(library: Library, member_id: str) -> Iterator[Loan]: """Every loan a member has had, newest first.""" library.member(member_id) for loan in reversed(library.loans()): if loan.member_id == member_id: yield loan
A function with yield in it is a generator. Calling it doesn't run its code. It hands back a generator object, and the code runs only as something asks for values: up to a yield, which hands one value out and pauses there, then on to the next yield when the next value is wanted.
This small one prints a line each time it makes a value, so you can see when its code runs. Press Run:
Line 7 calls numbered, and nothing prints: no code has run yet. next(lines) asks for one value, and (making line 1) prints just before it. The for loop then asks for the rest, one at a time, making each line just before it's used.
That's why reports are generators. The menu prints each line as it comes, and a library with a million loans never builds a million-line list. One more thing happens late: history checks the member id on its first line, so a wrong id raises NotFound when the loop starts, not when history() is called.
A generator isn't a list
The last line of that example printed []. The for loop had already taken every value, and a generator can't go back to the start. Loop over it again and you get nothing, with no error. The wrong way: ask how many overdue loans there are. Press Run:
Read the bottom line: TypeError: object of type 'generator' has no len(). A generator doesn't know how many values it will make until it has made them all.
When you need a count, or to loop twice, make a list first: late = list(reports.overdue(library)). Change line 14 and run it again: Overdue: 1. The menu's overdue command does exactly that, because it needs to know whether to print Nothing is overdue.
Any loans will do
lent_between finds loans that started between two dates. It doesn't take a library: it takes any loans you can loop over, typed Iterable[Loan].
library/reports.py, lines 32–36def lent_between(loans: Iterable[Loan], start: date, end: date) -> Iterator[Loan]: """Loans that started between two dates. Works on any iterable of loans.""" for loan in loans: if start <= loan.lent_on <= end: yield loan
So it works on a list, a tuple, another generator, or library.loans(). That's duck typing (lesson 4.10): it only needs something it can for over, holding things with a lent_on.
The third call passes a generator expression, (… for … in … if …), the round-bracket cousin of a list comprehension. Generators chain: the inner one hands out loans that aren't Sam's, one at a time, and lent_between passes on the ones from March. No list is made until the outer […].
Try a report of your own: fines_due(library), yielding each overdue loan with what it would cost if it came back today. You'll need the member's policy (C.3).
Check what you learned
On your computer, write library/reports.py and add the menu commands that use it. The reference's tests are in tests/test_reports.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.