The menu
Last updated
Everything so far is classes that nobody can use without writing Python. In this lesson you'll write cli.py: a command loop that reads what someone types, calls the library, saves after every change, and turns every refusal into a plain sentence instead of a traceback.
By the end of this lesson you can
- Run commands from a dictionary of names and methods, instead of a long
if/elif - Catch the library's errors by their family, and bad input by its own error
- Explain what happens when an error isn't caught by the menu
- Keep the menu apart from the rules, so the classes don't care what drives them
Names to methods
The menu reads a word, like lend, and runs the code for it. With ten commands, an if/elif chain would be twenty lines of elif command == "…":. There's a shorter way. Functions are values in Python (lesson 2.5), so a dictionary can map each command's name to the function that does it. This is often called a dispatch table:
commands[typed] looks the function up, and the () after it calls it. A word that isn't a key gets a polite answer. A new command is one function and one line in the dictionary.
The reference's Menu does the same with its own methods. self.find is the method already tied to this menu (a bound method), so calling it needs no arguments:
library/cli.py, lines 37–56class Menu: def __init__( self, library: Library, storage: Storage, ask: Callable[[str], str] | None = None ) -> None: self.library = library self.storage = storage self.ask = ask or input self.commands: dict[str, Callable[[], None]] = { "find": self.find, "lend": self.lend, "return": self.give_back, "loans": self.loans, "overdue": self.overdue, "popular": self.popular, "history": self.history, "add": self.add, "join": self.join, "help": self.help, } self.changes = {"lend", "return", "add", "join"}
ask is the function that reads a line. It's input unless something else is passed in, which lets tests type for it (C.9). changes names the commands that change the library, so the menu knows when to save.
The loop
library/cli.py, lines 58–81def run(self) -> None: today, count = self.library.today(), len(self.library.catalogue) print(f"Library open on {today}, with {count} items. Type help for commands.") while True: try: command = self.ask("> ").strip().lower() except EOFError: command = "quit" if command == "quit": self.storage.save(self.library) print("Saved. Goodbye.") return if command not in self.commands: print(f"Sorry: there's no command {command!r}. Type help for the list.") continue try: self.commands[command]() except LibraryError as e: print(f"Sorry: {e}.") except ValueError as e: print(f"Sorry: that didn't look right ({e}).") else: if command in self.changes: self.storage.save(self.library)
Each time round:
- Read a command. If input runs out (Ctrl+D, or the end of the input box),
inputraisesEOFError, and the menu treats it asquit, so nothing is lost. quitsaves and returns, which ends the loop.- An unknown word gets a Sorry and
continuegoes back to the top. - Run the command. Any refusal from the library is a
LibraryError(C.4), and oneexceptturns all of them into Sorry: …. AValueErroris bad input, likesoonfor a year, and gets its own message. elseruns only if nothing was raised. Then, if the command changed anything, save straight away. A refused loan changed nothing, so it isn't saved.
Each command method is short: ask for what it needs, call the library, print the answer. Here's lend:
library/cli.py, lines 94–98def lend(self) -> None: item_id, member_id = self.ask("Item id: "), self.ask("Member id: ") loan = self.library.lend(item_id, member_id) item, member = self.library.catalogue.get(item_id), self.library.member(member_id) print(f"Lent {item.title} to {member.get_name()}. Due back {loan.due_on}.")
It doesn't check whether the item is on loan, or the member is at their limit. Library.lend does, and raises. The menu only talks to people. The rules live in the classes, so a different front end, a web page or a window, would get the same rules for free.
An error the menu didn't expect
The wrong way. Suppose the menu caught only LibraryError. Here's what happens when someone types soon as a year. Press Run:
1965 works. Then ValueError: invalid literal for int() with base 10: 'soon'. int() raises ValueError, which isn't in the library's family, so except LibraryError lets it straight past, and the whole program stops. In the real menu that would lose the person's session.
That's why the menu has a second except for ValueError. It doesn't catch everything with a bare except Exception, though. A KeyError or AttributeError would mean a bug in the code, and a traceback is the right way to find it. Catch the errors you expect and know how to explain. Let the rest stop the program.
Use it
Here's the whole menu in the page, with a sample stock (from sample.py) and a storage in memory. The input box holds a session: lend, a refusal, a return of something that isn't out, a mistyped command, a bad year, and a new member. Press Run, then change the input and try your own.
Every refusal is one Sorry line, and the menu keeps going. soon as a year gives Python's own words in brackets. They're not the friendliest, but they say what was wrong.
On your computer, write library/cli.py with a main() like the reference's: it loads the library from library.json, fills an empty one with the sample stock, and runs the menu.
library/cli.py, lines 156–161def main(storage: Storage | None = None, clock: Clock | None = None) -> None: storage = storage or JsonStorage("library.json") library = storage.load(clock) if not len(library.catalogue): sample.fill(library) Menu(library, storage).run()
Then run python -m library, lend something, quit, and run it again. The loan is still there.
Check what you learned
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.
- The Python Tutorial: Handling Exceptions: several except clauses, and else
- Built-in Functions: input: raises EOFError when input ends
- Built-in Exceptions: exception hierarchy