Home β€Ί Curriculum β€Ί Library System
Updated for Python 3.12+ Β· November 2026

πŸ“š Library System
in Python

Build a Library Management System in Python: books, members, loans, due dates, late fines and reports using classes, dataclasses and datetime.

Intermediate 7 lessonsβ‰ˆ 38 min read by Glenn Pansensoy

What this lesson is about

A library is one of the best practice projects in Python because the rules are familiar and rich enough to be interesting. A book can be on the shelf or on loan. A member can borrow only so many books. A late return costs a fine. Each of those rules becomes a small, testable piece of code.

In this project I build the system in layers. First a Book and a Member, then a Loan that connects them, then a Library that enforces the rules, then fines, search and a report. The goal is not only a working program but a design where each class has one clear job and the rules live in one place.

Every example runs in your browser and prints the same result every time, because I pass dates in explicitly instead of asking for today's date. That also happens to be how professionals test date logic: the current date is an input, not a hidden global.

What you will learn

  • βœ“Modelling books, members and loans as classes
  • βœ“Using dataclasses for simple data objects
  • βœ“Working with date and timedelta for due dates
  • βœ“Enforcing business rules with clear exceptions
  • βœ“Calculating late fines
  • βœ“Searching and filtering a collection
  • βœ“Producing a readable report
  • βœ“Testing date logic without waiting for real days to pass

Why programmers should learn this

  • β˜…Lending, booking and inventory systems all share this structure, so the skills carry over directly.
  • β˜…Business rules give a real reason for exceptions, validation and clear error messages.
  • β˜…Dates are a classic source of bugs, and this project teaches the safe way to handle them.
  • β˜…A multi-class project forces you to decide where logic belongs, which is the heart of design.
  • β˜…It makes a good portfolio piece because anyone can understand what it does at a glance.

Books and members as dataclasses

Start with the nouns. A book has an id, a title and an author. A member has an id and a name. Neither has much behaviour yet, so they are perfect for dataclasses. A dataclass writes the constructor, the representation and equality for you, which leaves the class body free for the parts that matter.

I mark both classes frozen=True so they cannot change after creation. A book's title does not change when it is lent out, and that idea is worth encoding. Anything that does change, such as who has the book, will live somewhere else.

Because dataclasses compare by value, two books with the same fields are equal, and a frozen dataclass can also be used as a dictionary key or placed in a set. Both facts become useful as the system grows.

Take a moment to notice what these two classes do not contain. There is no code for borrowing, no due dates and no fines. Keeping data classes plain means they stay reusable. Later, if you add a database, only the places that create books and members need to change, and everything built on top of them continues to work.

python
from dataclasses import dataclass


@dataclass(frozen=True)
class Book:
    book_id: int
    title: str
    author: str


@dataclass(frozen=True)
class Member:
    member_id: int
    name: str


dune = Book(1, "Dune", "Frank Herbert")
ana = Member(1, "Ana")
print(dune)
print(ana)
print(dune == Book(1, "Dune", "Frank Herbert"))

try:
    dune.title = "Other"
except Exception as error:
    print(type(error).__name__, "- frozen objects cannot change")
Expected output
Book(book_id=1, title='Dune', author='Frank Herbert')
Member(member_id=1, name='Ana')
True
FrozenInstanceError - frozen objects cannot change

Line by line

  1. 1-8@dataclass generates __init__, __repr__ and __eq__ from the annotated fields. frozen=True makes instances read-only.
  2. 11-14Member follows the same pattern.
  3. 17-20Create one book and one member and print them. The generated representation shows every field.
  4. 21Two books with the same values compare equal.
  5. 23-26Assigning to a frozen field raises an error, which protects the data.
πŸ’‘

Use a dataclass for data and a regular class for behaviour. When an object is mostly fields, a dataclass saves a lot of typing and mistakes.

Dates and due dates

Lending depends on dates, so I handle them carefully. The datetime.date class represents a calendar day and timedelta represents a length of time. Adding a timedelta to a date gives a new date, and subtracting two dates gives a timedelta, which is exactly what due dates and late days need.

I never call date.today() inside the rules. The date is always passed in as an argument. That way a test can say 'what happens ten days later' without waiting ten days, and the output here is identical on every run.

A tiny helper function computes how many days late a return is. It returns zero for on-time returns, because a negative number of late days makes no sense and would cause confusing fines.

A good habit with dates is to print them in the ISO format, year then month then day. It sorts correctly as text, it is unambiguous across countries and it is what most databases and web services expect. Show friendlier formats only at the very edge, when a human is going to read the result.

python
from datetime import date, timedelta

LOAN_DAYS = 14


def due_date(borrowed_on):
    return borrowed_on + timedelta(days=LOAN_DAYS)


def days_late(due, returned_on):
    return max(0, (returned_on - due).days)


borrowed = date(2026, 3, 1)
due = due_date(borrowed)
print("borrowed:", borrowed.isoformat())
print("due:     ", due.isoformat(), due.strftime("(%A)"))
print("late if returned 2026-03-12:", days_late(due, date(2026, 3, 12)))
print("late if returned 2026-03-20:", days_late(due, date(2026, 3, 20)))
Expected output
borrowed: 2026-03-01
due:      2026-03-15 (Sunday)
late if returned 2026-03-12: 0
late if returned 2026-03-20: 5

Line by line

  1. 1-3Import the date tools and set a constant for the loan length.
  2. 6-7A due date is the borrow date plus fourteen days.
  3. 10-11Subtracting two dates gives a timedelta; .days is its whole number of days. max(0, ...) removes negatives.
  4. 14-19Compute and print a due date, its weekday name and two example returns.
ℹ️

Pass dates into functions instead of calling date.today() inside them. Code that depends on the hidden current date is hard to test.

The Loan: connecting a book and a member

A loan is an event that links one book, one member and a date. It also records whether the book has been returned. Because it changes, when the book is returned, it is a regular class rather than a frozen dataclass.

I give the loan the small calculations that only concern itself: its due date, whether it is overdue on a given day, and the fine for returning on a given day. The library will use these methods, so the rules are written once and read in one place.

The fine is a simple rule: a fixed amount per late day, capped so a forgotten book never costs more than a sensible limit. A cap is a business decision, so I make it a named constant, easy to find and change.

Properties are a good fit here because the value is derived. Whenever a number can be calculated from other fields, calculate it when asked rather than storing it. Stored copies must be kept in sync by hand, and sooner or later one of them will be forgotten.

A loan is also a natural place to grow. Renewals, reservations and notes can all be added as fields or methods on the loan without touching books or members, because the loan is the only class that cares about the relationship between them.

python
from dataclasses import dataclass
from datetime import date, timedelta

LOAN_DAYS = 14
FINE_PER_DAY = 0.25
MAX_FINE = 5.00


@dataclass(frozen=True)
class Book:
    book_id: int
    title: str


@dataclass(frozen=True)
class Member:
    member_id: int
    name: str


class Loan:
    def __init__(self, book, member, borrowed_on):
        self.book, self.member = book, member
        self.borrowed_on = borrowed_on
        self.returned_on = None

    @property
    def due(self):
        return self.borrowed_on + timedelta(days=LOAN_DAYS)

    def is_overdue(self, today):
        return self.returned_on is None and today > self.due

    def fine(self, returned_on):
        late = max(0, (returned_on - self.due).days)
        return min(MAX_FINE, round(late * FINE_PER_DAY, 2))


loan = Loan(Book(1, "Dune"), Member(1, "Ana"), date(2026, 3, 1))
print("due", loan.due)
print("overdue on Mar 10?", loan.is_overdue(date(2026, 3, 10)))
print("overdue on Mar 20?", loan.is_overdue(date(2026, 3, 20)))
print("fine Mar 20:", loan.fine(date(2026, 3, 20)))
print("fine Jun 20:", loan.fine(date(2026, 6, 20)))
Expected output
due 2026-03-15
overdue on Mar 10? False
overdue on Mar 20? True
fine Mar 20: 1.25
fine Jun 20: 5.0

Line by line

  1. 4-6Business rules as named constants: loan length, fine per day and the maximum fine.
  2. 21-25A Loan stores the book, the member, the borrow date and None for the return date until the book comes back.
  3. 27-29due is a property computed from the borrow date, so it can never disagree with it.
  4. 31-32A loan is overdue only if it has not been returned and today is after the due date.
  5. 34-36The fine is late days times the daily rate, capped at the maximum.
  6. 39-44A short demonstration: not overdue on March 10, overdue on March 20, a small fine, and the cap applied to a very late return.

The Library class and its rules

Now the part that ties everything together. The Library keeps the catalogue, the members and the current loans, and it enforces the rules: only available books can be borrowed, a member can have at most three books, and a member with unpaid fines cannot borrow.

Each rule that fails raises a specific exception with a helpful message. I define small exception classes that inherit from one base class, LibraryError. Callers can catch the base class for any library problem or a specific one when they care about the reason.

Keep the rules in the library, not scattered across the program. When the maximum number of books changes from three to five, there is exactly one line to edit, and every caller automatically follows the new rule.

Think of the exception classes as part of the library's public language. The program using the library can say exactly what it means: if the book is not available, tell the member; if the limit is reached, suggest returning something first. Generic errors would force every caller to read message text to find out what happened.

The final test of any rule is what happens at its edges. Borrow exactly three books and the third works; try a fourth and it fails. Return a book on its due date and there is no fine; return it a day later and there is. Walk through these boundary cases by hand, because boundaries are where almost every real bug in a system like this hides.

python
from dataclasses import dataclass
from datetime import date, timedelta

LOAN_DAYS, MAX_BOOKS = 14, 3


class LibraryError(Exception): pass
class NotAvailable(LibraryError): pass
class LimitReached(LibraryError): pass


@dataclass(frozen=True)
class Book:
    book_id: int
    title: str


@dataclass(frozen=True)
class Member:
    member_id: int
    name: str


class Library:
    def __init__(self):
        self.books, self.members, self.loans = {}, {}, []

    def add_book(self, book):
        self.books[book.book_id] = book

    def join(self, member):
        self.members[member.member_id] = member

    def on_loan(self, book_id):
        return any(l["book"].book_id == book_id and l["returned"] is None for l in self.loans)

    def count_for(self, member):
        return sum(1 for l in self.loans if l["member"] == member and l["returned"] is None)

    def borrow(self, book_id, member_id, today):
        book, member = self.books[book_id], self.members[member_id]
        if self.on_loan(book_id):
            raise NotAvailable(f"'{book.title}' is already on loan")
        if self.count_for(member) >= MAX_BOOKS:
            raise LimitReached(f"{member.name} already has {MAX_BOOKS} books")
        self.loans.append({"book": book, "member": member, "borrowed": today, "returned": None})
        return today + timedelta(days=LOAN_DAYS)


lib = Library()
for i, title in enumerate(["Dune", "Emma", "Ulysses", "Hamlet"], start=1):
    lib.add_book(Book(i, title))
lib.join(Member(1, "Ana"))
lib.join(Member(2, "Ben"))

today = date(2026, 3, 1)
print("due", lib.borrow(1, 1, today))
for attempt in [(1, 2), (2, 1), (3, 1), (4, 1)]:
    try:
        print("due", lib.borrow(attempt[0], attempt[1], today))
    except LibraryError as error:
        print(type(error).__name__ + ":", error)
Expected output
due 2026-03-15
NotAvailable: 'Dune' is already on loan
due 2026-03-15
due 2026-03-15
LimitReached: Ana already has 3 books

Line by line

  1. 6-8A base exception and two specific ones. Callers can catch LibraryError for everything or a subclass for one reason.
  2. 27-42Setup methods store books and members by id. The two helpers answer 'is this book out?' and 'how many books does this member hold?'
  3. 44-51borrow checks each rule in turn and raises a clear error if one fails; otherwise it records a loan and returns the due date.
  4. 54-59Create four books and two members.
  5. 61-67Ana borrows Dune. Ben cannot take Dune. Ana takes two more and then hits her limit of three.
πŸ’‘

Specific exception classes make code readable: except NotAvailable says exactly what you expect to go wrong.

Returning books and charging fines

Returning a book closes the loan and, if the book is late, produces a fine. The library finds the open loan for the book, writes the return date and returns the fine amount to the caller. The caller can then show it, charge it or store it.

I keep the calculation in one small function that takes the due date and the return date, so it is easy to test with a handful of dates. A return of a book that is not on loan raises a clear error, because quietly ignoring it would hide a mistake somewhere else.

The example borrows a book, returns it on time, borrows it again and returns it nineteen days late. The first fine is zero and the second is the cap-limited late fee.

Real libraries often waive small fines or have a grace period. Try adding a constant for grace days and changing the late calculation in the single function that owns it. Because the rule lives in one place, the change is tiny, and that is the clearest proof the design is working.

Notice that the fine function knows nothing about books or members. It takes two dates and returns a number. Small pure functions like this are the easiest code to trust, because you can test them with a few lines and they never depend on anything that might change underneath them.

python
from datetime import date, timedelta

LOAN_DAYS, FINE_PER_DAY, MAX_FINE = 14, 0.25, 5.0


def fine_for(due, returned):
    late = max(0, (returned - due).days)
    return min(MAX_FINE, round(late * FINE_PER_DAY, 2))


class Shelf:
    def __init__(self):
        self.open_loans = {}
        self.total_fines = 0.0

    def borrow(self, title, member, day):
        if title in self.open_loans:
            raise ValueError(f"{title} is already on loan")
        self.open_loans[title] = (member, day + timedelta(days=LOAN_DAYS))

    def give_back(self, title, day):
        if title not in self.open_loans:
            raise ValueError(f"{title} is not on loan")
        member, due = self.open_loans.pop(title)
        fine = fine_for(due, day)
        self.total_fines += fine
        return member, fine


shelf = Shelf()
shelf.borrow("Dune", "Ana", date(2026, 3, 1))
print(shelf.give_back("Dune", date(2026, 3, 10)))
shelf.borrow("Dune", "Ben", date(2026, 3, 11))
print(shelf.give_back("Dune", date(2026, 3, 11) + timedelta(days=14 + 19)))
print("fines collected:", shelf.total_fines)
try:
    shelf.give_back("Dune", date(2026, 4, 1))
except ValueError as error:
    print("error:", error)
Expected output
('Ana', 0.0)
('Ben', 4.75)
fines collected: 4.75
error: Dune is not on loan

Line by line

  1. 5-7fine_for is the whole fine rule in three lines, easy to test on its own.
  2. 10-24Shelf tracks open loans by title. give_back removes the loan, calculates the fine and adds it to a running total.
  3. 27-33Ana returns on time and pays nothing. Ben returns nineteen days late and pays the capped fine.
  4. 34-38Returning a book that is not on loan raises a clear error.

Searching the catalogue

A library is only useful if you can find things. Search is a good example of filtering with comprehensions. I normalise case with lower() so that 'dune' finds 'Dune', and I search both title and author so one box serves two needs.

Return the results in a predictable order, for example sorted by title, so the output is the same every time and users are not surprised. Sorting with a key function keeps this a one-liner.

You can extend the idea easily: filter only available books, search by several words, or rank title matches above author matches. Each of those is a small change to the same function.

Search is also where small details create a good feeling. Lower-casing, trimming spaces and returning results in a stable order are tiny touches, but they are the difference between a tool that feels reliable and one that feels random. Users notice stability more than they notice features.

python
books = [
    {"id": 1, "title": "Dune", "author": "Frank Herbert", "out": False},
    {"id": 2, "title": "Dune Messiah", "author": "Frank Herbert", "out": True},
    {"id": 3, "title": "Emma", "author": "Jane Austen", "out": False},
    {"id": 4, "title": "Persuasion", "author": "Jane Austen", "out": False},
]


def search(text, only_available=False):
    text = text.lower()
    found = [
        b for b in books
        if text in b["title"].lower() or text in b["author"].lower()
    ]
    if only_available:
        found = [b for b in found if not b["out"]]
    return sorted(found, key=lambda b: b["title"])


for query, flag in [("dune", False), ("dune", True), ("austen", False), ("zzz", False)]:
    titles = [b["title"] for b in search(query, flag)]
    print(f"{query!r} available_only={flag}: {titles}")
Expected output
'dune' available_only=False: ['Dune', 'Dune Messiah']
'dune' available_only=True: ['Dune']
'austen' available_only=False: ['Emma', 'Persuasion']
'zzz' available_only=False: []

Line by line

  1. 1-6A small catalogue as a list of dictionaries, with an out flag for books on loan.
  2. 9-17search lower-cases the text, keeps books whose title or author contains it, optionally removes books on loan and returns them sorted by title.
  3. 20-22Four queries, including one that finds nothing. An empty result is a normal answer, not an error.

A report for the librarian

The librarian needs answers: which books are overdue, who has them and how much they owe. A report function walks the open loans for a given day and builds those lines. Like every function in this project, it takes the day as an argument.

Formatting matters here. Aligned columns turn a pile of data into something a person can scan in seconds. Python's format specifiers, such as :<14 for left alignment and >6.2f for a right-aligned money amount, do the work.

At the end the report prints a total. A total is a built-in check: if the number looks wrong, there is probably a bug in one of the lines above it.

Before you build your own version, write three sentences describing what a librarian wants to know each morning. Each sentence becomes a function or a report line. Starting from the questions people ask, instead of the classes you imagine, keeps the project focused and prevents it from growing into a pile of features nobody uses.

python
from datetime import date, timedelta

FINE_PER_DAY, MAX_FINE = 0.25, 5.0
today = date(2026, 4, 1)

loans = [
    ("Dune", "Ana", date(2026, 3, 1)),
    ("Emma", "Ben", date(2026, 3, 20)),
    ("Hamlet", "Cora", date(2026, 3, 5)),
]

print(f"{'Book':<10}{'Member':<8}{'Due':<12}{'Late':>5}{'Fine':>8}")
total = 0.0
for title, member, borrowed in sorted(loans):
    due = borrowed + timedelta(days=14)
    late = max(0, (today - due).days)
    fine = min(MAX_FINE, round(late * FINE_PER_DAY, 2))
    total += fine
    flag = "  <- overdue" if late else ""
    print(f"{title:<10}{member:<8}{due.isoformat():<12}{late:>5}{fine:>8.2f}{flag}")
print(f"{'Total fines':<30}{total:>8.2f}")
Expected output
Book      Member  Due          Late    Fine
Dune      Ana     2026-03-15     17    4.25  <- overdue
Emma      Ben     2026-04-03      0    0.00
Hamlet    Cora    2026-03-19     13    3.25  <- overdue
Total fines                       7.50

Line by line

  1. 4The report day is fixed so the output never changes.
  2. 6-10Three open loans as tuples of title, member and borrow date.
  3. 12A header line using the same widths as the rows below, so columns line up.
  4. 14-21For each loan compute the due date, late days and capped fine, add to the total and flag overdue rows.
  5. 22Print the total on its own line.
πŸ’‘

Always print a total or a count in a report. It gives you a quick way to check that the details add up.

Common mistakes

❌ Calling date.today() inside the rules

Hidden dates make code impossible to test. Pass the day in as an argument.

❌ Scattering rules across the program

Put the loan limit and fine rules in one place, such as the Library class, so a change is a one-line edit.

❌ Raising generic exceptions

Exception('error') tells callers nothing. Define specific classes like NotAvailable with clear messages.

❌ Allowing negative late days

Subtracting dates can give negative numbers. Clamp with max(0, ...) so early returns never create fines or credits.

❌ Storing a computed value that can go stale

A due date saved separately can disagree with the borrow date. Compute it from the borrow date in a property.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. What does subtracting two date objects return?

Q2. Why pass the current date into functions?

Q3. What does frozen=True do for a dataclass?

Q4. Why define a base exception like LibraryError?

Q5. What does max(0, days) protect against?

Q6. Where should the maximum books rule live?

Frequently asked questions

It is a solid core. A real system would add a database, reservations and user accounts, but the rules and structure you built here stay the same.

Convert books, members and loans to dictionaries and write them with the json module, or use sqlite3 for a proper database.

Books and members are mostly data. A dataclass gives you a constructor, a readable representation and equality without writing them by hand.

Yes. Wrap the Library in a loop that reads commands with input() on your own computer. The browser runner here does not support input().

Call fine_for with several pairs of dates and use assert to check the expected amounts. Because dates are arguments, no waiting is needed.

Key takeaways

  • βœ“Use dataclasses for data objects and regular classes for behaviour.
  • βœ“Represent time with date and timedelta, and pass the date in.
  • βœ“Keep business rules in one class and raise specific exceptions.
  • βœ“Clamp values such as late days so impossible numbers never appear.
  • βœ“Search with comprehensions and sort results for predictable output.
  • βœ“Format reports with aligned columns and always print a total.