Python Advanced Concepts: Creating Python Documentation with Pydoc


Understanding the significance of Python module documentation and the tools available can elevate your coding prowess. 'Pydoc' stands out as an invaluable utility in this regard, assisting developers in generating comprehensive module documentation.

a. What is Pydoc?

An integral Python tool that produces textual or webpage documentation from Python modules. This is achieved by reading the module's docstrings. Below is a simple bookstore class created to manage books. Incorporated are a number of comments that Pydoc will use to create the documentation. Therefore, if you are using Pydoc it is paramount to include these comments, otherwise Pydoc will output nothing!.

Code

class Bookstore:
    """
    A bookstore class to hold books' names, their authors, and costs.

    Attributes:
    -----------
    books : list
        A list containing the books in the bookstore. Each book is represented as a tuple containing
        its name, author, and cost.

    Methods:
    --------
    add_book(bookname: str, author: str, cost: float):
        Adds a new book to the bookstore.

    remove_book(bookname: str):
        Removes a book from the bookstore by its name.

    print_current_books():
        Prints the current list of books in the bookstore.

    search_for_book(bookname: str) -> list:
        Searches for a book by its name and returns a list of matching books.
    """

    def __init__(self):
        """Initializes an empty bookstore."""
        self.books = []

    def add_book(self, bookname: str, author: str, cost: float):
        """
        Adds a new book to the bookstore.

        Parameters:
        -----------
        bookname : str
            The name of the book.
        author : str
            The author of the book.
        cost : float
            The cost of the book.

        Returns:
        --------
        None
        """
        if not isinstance(cost, float):
            print("Value error: Cost must be a price i.e 9.99")
            return

        for book in self.books:
            if bookname == book[0]:
                print("Cannot add book. Book already exists")
                return
        else:
            self.books.append((bookname, author, cost))

    def remove_book(self, bookname: str):
        """
        Removes a book from the bookstore by its name.

        Parameters:
        -----------
        bookname : str
            The name of the book to be removed.

        Raises:
        -------
        ValueError
            If the book doesn't exist in the bookstore.
        """
        for book in self.books:
            if bookname == book[0]:
                self.books.remove(book)
                return
        raise ValueError("{} does not exist in the bookstore.".format(bookname))

    def print_current_books(self):
        """Prints the current list of books in the bookstore."""
        print("Books in Bookstore\n")
        for book in self.books:
            print("Bookname: {}\nAuthor: {}\n"
                  "Cost: {:.2f}\n".format(book[0], book[1], book[2]))

    def search_for_book(self, bookname: str) -> list:
        """
        Searches for a book by its name.

        Parameters:
        -----------
        bookname : str
            The name of the book to be searched.

        Returns:
        --------
        list
            A list of books that match the search.
        """
        books_found = []
        for book in self.books:
            if str(bookname).lower() in book[0].lower():
                books_found.append(book)
        return books_found

b. Viewing the Generated Documentation

Upon executing the pydoc command in a terminal (make sure the script you calling is local) it will generate a HTML page.

Command

pydoc -w module_name

Command

pydoc -w bookstore

I have uploaded the html page generated by the following command here.

c. Benefits of Pydoc:

- Automatic generation of documentation.
- Easily navigable text or HTML format.
- Utilises docstrings for a comprehensive overview.

Enquiries

[email protected]

Copyright © 2023 - slash-root.com