Project: a library system
🌍 In real life. A school library lends books. A paper book can be with only one student at a time: once it's borrowed, the next student has to wait. An e-book is different: any number of students can read it at once. The librarian wants to add books, lend them, take them back, and print a list showing what's on the shelf.
In this project you'll build that system with everything from World 4: an Enum, a dataclass, inheritance with an overridden method, and a class that protects its rules.
The plan in one sentence: a Status Enum names the two states, a Book dataclass holds each book, an EBook child changes how lending works, and a Library class keeps the books and enforces the rules.
Its words:
- state: whether a book is
AVAILABLEorBORROWED - rule: a borrowed paper book can't be borrowed again; the
Libraryrefuses with aValueError - override:
EBookwrites its owncan_borrowandlend, so the same calls behave differently
Step by step, the plan:
Status(Enum): the only two states a book can be in.@dataclass Book: title, author, status, pluscan_borrow,lendandgive_back.class EBook(Book): always borrowable, and lending changes nothing.class Library: a dictionary of books by title, withadd,borrow,give_backandreport.
When the library asks a book can_borrow(), Python climbs the lookup tower. An e-book answers from its own class:
Steps 1 and 2: the data. A book's state is one of a fixed set of choices, so it's an Enum: Status.BORROWED can't be misspelt the way "borowed" could. The book is mostly data, so @dataclass writes __init__ and __repr__, and the default status = Status.AVAILABLE means a new book starts on the shelf.
Step 3: the e-book. An e-book is a book, so it inherits. It overrides two methods: can_borrow always says True, and lend does nothing, because there's no copy to take off the shelf.
Step 4: the rules. The Library is the only place that lends, so it's the place to check: a missing title or a book that can't be borrowed raises a ValueError with a clear message, and nothing changes.
from dataclasses import dataclass
from enum import Enum
class Status(Enum):
AVAILABLE = 1
BORROWED = 2
@dataclass
class Book:
title: str
author: str
status: Status = Status.AVAILABLE
def can_borrow(self):
return self.status == Status.AVAILABLE
def lend(self):
self.status = Status.BORROWED
def give_back(self):
self.status = Status.AVAILABLE
class EBook(Book):
"""An e-book has unlimited copies, so it can always be borrowed."""
def can_borrow(self):
return True
def lend(self):
pass
class Library:
def __init__(self):
self.books = {}
def add(self, book):
self.books[book.title] = book
def borrow(self, title):
if title not in self.books:
raise ValueError(f"No book called {title}")
book = self.books[title]
if not book.can_borrow():
raise ValueError(f"{title} is already borrowed")
book.lend()
def give_back(self, title):
self.books[title].give_back()
def report(self):
lines = []
for title in sorted(self.books):
book = self.books[title]
state = "available" if book.can_borrow() else "borrowed"
lines.append(f"{title} by {book.author}: {state}")
return lines
library = Library()
library.add(Book("Dune", "Herbert"))
library.add(EBook("Gitanjali", "Tagore"))
library.borrow("Dune")
library.borrow("Gitanjali")
try:
library.borrow("Dune")
except ValueError as e:
print("Refused:", e)
for line in library.report():
print(line)Why build it this way, and what it costs. Each class has one job, and the Library never asks "is this an e-book?": it just calls can_borrow() and lend(), and each kind of book answers for itself (polymorphism, Lesson 22.3). Adding an audiobook later means one new child class, with no change to Library. Lending and returning look a book up by title in a dictionary, which takes about the same time for 10 books or 10,000; only report() walks and sorts them all.
Mistakes and edge cases.
- Checking the type in Library.
if isinstance(book, EBook):insideborrowworks, but every new kind of book would need anotherif. - Changing status from outside.
library.books["Dune"].status = Status.AVAILABLEskips the rules; go throughgive_back. - Comparing with a string.
book.status == "AVAILABLE"is always False: compare withStatus.AVAILABLE. - A missing title.
self.books[title]on an unknown title raises a KeyError; checkinfirst and raise a clear ValueError instead.
Quiz
What does this print?
from dataclasses import dataclass from enum import Enum class Status(Enum): AVAILABLE = 1 BORROWED = 2 @dataclass class Book: title: str author: str status: Status = Status.AVAILABLE def can_borrow(self): return self.status == Status.AVAILABLE def lend(self): self.status = Status.BORROWED def give_back(self): self.status = Status.AVAILABLE b = Book("Dune", "Herbert") b.lend() print(b.status.name, b.can_borrow())Why is EBook a child class of Book instead of a separate class?
- An e-book is a book, and only its lending rules differ
- Because dataclasses can't be used twice
- So that it can't be borrowed
This should say the book is available, but it prints False. Which line has the mistake?
from enum import Enum class Status(Enum): AVAILABLE = 1 status = Status.AVAILABLE print(status == "AVAILABLE")What does this print?
from dataclasses import dataclass from enum import Enum class Status(Enum): AVAILABLE = 1 BORROWED = 2 @dataclass class Book: title: str author: str status: Status = Status.AVAILABLE def can_borrow(self): return self.status == Status.AVAILABLE def lend(self): self.status = Status.BORROWED def give_back(self): self.status = Status.AVAILABLE class EBook(Book): """An e-book has unlimited copies, so it can always be borrowed.""" def can_borrow(self): return True def lend(self): pass class Library: def __init__(self): self.books = {} def add(self, book): self.books[book.title] = book def borrow(self, title): if title not in self.books: raise ValueError(f"No book called {title}") book = self.books[title] if not book.can_borrow(): raise ValueError(f"{title} is already borrowed") book.lend() def give_back(self, title): self.books[title].give_back() lib = Library() lib.add(Book("Dune", "Herbert")) lib.borrow("Dune") try: lib.borrow("Dune") except ValueError as e: print(e)Where should the rule "a borrowed paper book can't be borrowed again" be checked?
- In Library.borrow, the one place that lends
- In every place that prints a book
- Nowhere: students will remember
Coding tasks
Step 1: books and their state. Write
Status, an Enum withAVAILABLE = 1andBORROWED = 2, andBook, a dataclass withtitle,authorandstatus(defaultStatus.AVAILABLE). GiveBookthree methods:can_borrow()(True when available),lend()(sets BORROWED) andgive_back()(sets AVAILABLE).Step 2: e-books and the library. Add
EBook(Book), whosecan_borrow()always returns True and whoselend()does nothing. Then addLibrary, with abooksdictionary (title → book) and three methods:add(book)borrow(title): raiseValueErrorif there's no such title or the book can't be borrowed; otherwise callbook.lend()give_back(title)
Step 3: the shelf report. Add
report()toLibrary. It returns a list of lines, one per book, sorted by title, likeDune by Herbert: borrowedorGitanjali by Tagore: available. An e-book is always available.