avatarAyşe Kübra Kuyucu

Summary

This context provides a comprehensive guide on writing and utilizing comments and docstrings in Python to enhance code readability, maintainability, and documentation.

Abstract

The provided content serves as an educational tutorial aimed at teaching Python programmers the importance and techniques of writing comments and docstrings. It covers the distinction between comments and docstrings, the syntax for single-line and multi-line comments, and the conventions for writing docstrings for various Python constructs such as modules, functions, classes, and methods. The tutorial emphasizes the role of docstrings in generating documentation through tools like Sphinx and Pydoc, and it demonstrates how to access docstrings using Python's built-in help() function and the __doc__ attribute. By integrating these practices, developers can create well-documented code, facilitating better understanding and easier collaboration within the programming community.

Opinions

  • Comments are crucial for explaining the purpose and logic of code, making it easier for others to understand and maintain.
  • Multi-line comments are preferred for longer explanations or to temporarily disable code blocks.
  • Docstrings are essential for documenting the specification of Python objects, as they are accessible by the interpreter and can be used by documentation generation tools.
  • Consistency and clarity are key when writing comments and docstrings to ensure they are helpful rather than redundant.
  • The use of tools like Sphinx and Pydoc is highly recommended for generating professional documentation from docstrings.
  • The tutorial encourages adherence to established style guides, such as PEP 257 and the Google style guide, for writing docstrings.
  • The author believes that investing time in writing good comments and docstrings can save time and effort in the long run.
  • The tutorial promotes the practice of regularly updating documentation alongside code changes to maintain accuracy and relevance.

Python Tutorial 4 — Understanding Python Comments and Docstrings

Learn how to write comments and documentation strings.

AI-Generated Image by Author

Table of Contents 1. Introduction 2. What are comments and why are they important? 3. How to write single-line and multi-line comments in Python 4. What are docstrings and how do they differ from comments? 5. How to write docstrings for modules, functions, classes, and methods in Python 6. How to access and use docstrings in Python 7. How to generate documentation from docstrings using tools like Sphinx and Pydoc 8. Conclusion

Subscribe for FREE to get your 42 pages e-book: Data Science | The Comprehensive Handbook

Get step-by-step e-books on Python, ML, DL, and LLMs.

1. Introduction

Welcome to this tutorial on understanding Python comments and docstrings. In this tutorial, you will learn:

  • What are comments and why are they important in Python programming
  • How to write single-line and multi-line comments in Python
  • What are docstrings and how do they differ from comments
  • How to write docstrings for modules, functions, classes, and methods in Python
  • How to access and use docstrings in Python
  • How to generate documentation from docstrings using tools like Sphinx and Pydoc

By the end of this tutorial, you will be able to write clear and concise comments and docstrings for your Python code, and use them to create professional documentation for your projects.

Let’s get started!

2. What are comments and why are they important?

Comments are lines of text in your code that are ignored by the Python interpreter. They are used to add notes, explanations, or instructions to your code, making it easier to understand and maintain. Comments can also be used to temporarily disable or debug parts of your code without deleting them.

Comments are important for several reasons:

  • They help you and other programmers to read and understand your code, especially if it is complex or involves many steps.
  • They document the purpose, functionality, and logic of your code, making it easier to reuse and modify.
  • They improve the readability and style of your code, making it more consistent and professional.
  • They can help you find and fix errors or bugs in your code, by testing different scenarios or inputs.

Therefore, writing good comments is an essential skill for any Python programmer, as it can save you time and effort in the long run.

3. How to write single-line and multi-line comments in Python

In Python, you can write comments in two ways: single-line comments and multi-line comments.

A single-line comment is a line of text that starts with a hash symbol (#) and ends with a newline character (\n). The Python interpreter ignores everything after the hash symbol until the end of the line. You can use single-line comments to add short notes or explanations to your code, or to temporarily disable a line of code.

For example, the following code snippet uses single-line comments to explain what each line does:

# This is a single-line comment
    print("Hello, World!") # This prints a message to the screen
    # print("This line is commented out and will not run")

A multi-line comment is a block of text that spans multiple lines and is enclosed by three single quotes (‘’’) or three double quotes (“””). The Python interpreter ignores everything between the opening and closing quotes. You can use multi-line comments to add longer descriptions or instructions to your code, or to temporarily disable a block of code.

For example, the following code snippet uses multi-line comments to describe the purpose of a function:

"""
    This is a multi-line comment
    This function takes a name as an argument and returns a greeting message
    """
    def greet(name):
        return "Hello, " + name + "!"

As you can see, writing comments in Python is simple and straightforward. However, you should follow some best practices when writing comments, such as:

  • Write clear and concise comments that explain the what, why, and how of your code.
  • Write comments that are relevant and helpful to the reader, not obvious or redundant.
  • Write comments that are consistent and follow a standard format or style.
  • Write comments that are updated and maintained along with your code.

In the next section, you will learn about another way of writing comments in Python: docstrings.

4. What are docstrings and how do they differ from comments?

Docstrings are a special type of comment that are used to document the functionality and usage of modules, functions, classes, and methods in Python. Docstrings are enclosed by three single quotes (‘’’) or three double quotes (“””) at the beginning and end of the definition of the object they document. Docstrings can be accessed and used by the Python interpreter, as well as by external tools that generate documentation from your code.

Docstrings differ from comments in several ways:

  • Docstrings are intended to describe the specification of the object they document, such as its purpose, parameters, return value, exceptions, etc. Comments are intended to explain the implementation of the code, such as its logic, steps, or algorithms.
  • Docstrings are placed inside the definition of the object they document, immediately after the header line. Comments can be placed anywhere in the code, before or after the object they refer to.
  • Docstrings can be accessed and used by the Python interpreter, using the built-in functions help() and __doc__. Comments are ignored by the Python interpreter and cannot be accessed or used by it.
  • Docstrings can be used by external tools, such as Sphinx and Pydoc, to generate documentation from your code. Comments cannot be used by these tools and are not included in the documentation.

Therefore, docstrings are a powerful and convenient way of writing documentation for your Python code, as they can be accessed and used by both the Python interpreter and external tools. In the next section, you will learn how to write docstrings for different types of objects in Python.

5. How to write docstrings for modules, functions, classes, and methods in Python

In this section, you will learn how to write docstrings for different types of objects in Python, such as modules, functions, classes, and methods. You will also learn about some common conventions and formats for writing docstrings, such as the PEP 257 and the Google style guide.

A module is a file that contains Python code, such as definitions, statements, and imports. A module docstring is a docstring that appears at the top of the module file, before any other code. A module docstring should provide a brief overview of the module, its purpose, and its contents. It can also include information such as the author, the license, the dependencies, and the usage examples.

For example, the following code snippet shows a module docstring for a module named greet.py that defines a function to greet a person:

"""
    This is a module docstring for greet.py
    This module defines a function to greet a person with a message.
    Author: John Doe
    License: MIT
    Dependencies: None
    Usage: import greet
           greet.greet("World")
    """

    def greet(name):
        """This is a function docstring for greet."""
        print("Hello, " + name + "!")

A function is a block of code that performs a specific task and can be reused. A function docstring is a docstring that appears immediately after the function header line, before the function body. A function docstring should describe the functionality and usage of the function, such as its parameters, return value, exceptions, and examples.

For example, the following code snippet shows a function docstring for the greet function defined in the previous module:

def greet(name):
        """
        This is a function docstring for greet.
        This function takes a name as an argument and prints a greeting message to the screen.
        Parameters:
            name (str): The name of the person to greet.
        Returns:
            None
        Raises:
            TypeError: If name is not a string.
        Examples:
            >>> greet("World")
            Hello, World!
            >>> greet(42)
            TypeError: name must be a string
        """
        if not isinstance(name, str):
            raise TypeError("name must be a string")
        print("Hello, " + name + "!")

A class is a blueprint for creating objects that have attributes and methods. A class docstring is a docstring that appears immediately after the class header line, before the class body. A class docstring should describe the purpose and functionality of the class, such as its attributes, methods, inheritance, and examples.

For example, the following code snippet shows a class docstring for a class named Person that inherits from the built-in class object and has a name attribute and a greet method:

class Person(object):
        """
        This is a class docstring for Person.
        This class represents a person with a name and a greet method.
        Attributes:
            name (str): The name of the person.
        Methods:
            greet(): Prints a greeting message to the screen.
        Inheritance:
            This class inherits from the built-in class object.
        Examples:
            >>> p = Person("John")
            >>> p.name
            'John'
            >>> p.greet()
            Hello, John!
        """
        def __init__(self, name):
            """This is a method docstring for __init__."""
            self.name = name

        def greet(self):
            """This is a method docstring for greet."""
            print("Hello, " + self.name + "!")

A method is a function that is defined inside a class and belongs to an object. A method docstring is a docstring that appears immediately after the method header line, before the method body. A method docstring should describe the functionality and usage of the method, similar to a function docstring. However, a method docstring can also include information about the self parameter, which refers to the object itself, and the class parameter, which refers to the class of the object.

For example, the following code snippet shows method docstrings for the __init__ and greet methods defined in the previous class:

class Person(object):
        # Class docstring omitted for brevity

        def __init__(self, name):
            """
            This is a method docstring for __init__.
            This method initializes a new Person object with a name attribute.
            Parameters:
                self (Person): The object itself.
                name (str): The name of the person.
            Returns:
                None
            """
            self.name = name

        def greet(self):
            """
            This is a method docstring for greet.
            This method prints a greeting message to the screen using the name attribute.
            Parameters:
                self (Person): The object itself.
            Returns:
                None
            """
            print("Hello, " + self.name + "!")

As you can see, writing docstrings for different types of objects in Python is not very difficult, as long as you follow some basic rules and conventions. However, there are different styles and formats for writing docstrings, such as the PEP 257 and the Google style guide, which have different preferences and recommendations for the content and structure of docstrings. You can choose the style and format that suits your needs and preferences, as long as you are consistent and clear.

In the next section, you will learn how to access and use docstrings in Python, using the built-in functions help() and __doc__.

6. How to access and use docstrings in Python

In this section, you will learn how to access and use docstrings in Python, using the built-in functions help() and __doc__.

The help() function is a useful tool that displays the documentation of any object in Python, such as modules, functions, classes, methods, variables, etc. You can use the help() function in two ways: by passing the object as an argument, or by entering an interactive help mode.

For example, if you want to see the documentation of the greet function defined in the previous section, you can pass it as an argument to the help() function:

>>> import greet # Import the greet module
    >>> help(greet.greet) # Pass the greet function as an argument to the help function
    Help on function greet in module greet:

    greet(name)
        This is a function docstring for greet.
        This function takes a name as an argument and prints a greeting message to the screen.
        Parameters:
            name (str): The name of the person to greet.
        Returns:
            None
        Raises:
            TypeError: If name is not a string.
        Examples:
            >>> greet("World")
            Hello, World!
            >>> greet(42)
            TypeError: name must be a string

As you can see, the help() function displays the docstring of the greet function, along with some additional information, such as the module name, the function name, and the function signature.

If you want to enter an interactive help mode, you can call the help() function without any argument. This will open a prompt where you can type the name of any object and see its documentation. You can also use keywords such as modules, keywords, topics, and quit to navigate the help system.

For example, if you want to see the documentation of the Person class defined in the previous section, you can enter the interactive help mode and type the name of the class:

>>> help() # Call the help function without any argument to enter the interactive help mode

    Welcome to Python 3.9's help utility!

    If this is your first time using Python, you should definitely check out
    the tutorial on the Internet at https://docs.python.org/3.9/tutorial/.

    Enter the name of any module, keyword, or topic to get help on writing
    Python programs and using Python modules. To quit this help utility and
    return to the interpreter, just type "quit".

    To get a list of available modules, keywords, symbols, or topics, type
    "modules", "keywords", "symbols", or "topics". Each module also comes
    with a one-line summary of what it does; to list the modules whose name
    or summary contain a given string such as "spam", type "modules spam".

    help> Person # Type the name of the class to see its documentation
    Help on class Person in module __main__:

    class Person(builtins.object)
     |  This is a class docstring for Person.
     |  This class represents a person with a name and a greet method.
     |  Attributes:
     |      name (str): The name of the person.
     |  Methods:
     |      greet(): Prints a greeting message to the screen.
     |  Inheritance:
     |      This class inherits from the built-in class object.
     |  Examples:
     |      >>> p = Person("John")
     |      >>> p.name
     |      'John'
     |      >>> p.greet()
     |      Hello, John!
     |  
     |  Methods defined here:
     |  
     |  __init__(self, name)
     |      This is a method docstring for __init__.
     |      This method initializes a new Person object with a name attribute.
     |      Parameters:
     |          self (Person): The object itself.
     |          name (str): The name of the person.
     |      Returns:
     |          None
     |  
     |  greet(self)
     |      This is a method docstring for greet.
     |      This method prints a greeting message to the screen using the name attribute.
     |      Parameters:
     |          self (Person): The object itself.
     |      Returns:
     |          None
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)

    help> quit # Type quit to exit the interactive help mode
    You are now leaving help and returning to the Python interpreter.
    If you want to ask for help on a particular object directly from the
    interpreter, you can type "help(object)".  Executing "help('string')"
    has the same effect as typing a particular string at the help> prompt.
    >>>

As you can see, the interactive help mode displays the docstring of the Person class, along with some additional information, such as the module name, the class name, the inheritance, the methods, and the attributes.

The __doc__ attribute is another way of accessing the docstring of any object in Python. The __doc__ attribute is a string that contains the docstring of the object, or None if the object has no docstring. You can use the __doc__ attribute to print, store, or manipulate the docstring of any object.

For example, if you want to print the docstring of the greet function defined in the previous section, you can use the __doc__ attribute:

>>> import greet # Import the greet module
    >>> print(greet.greet.__doc__) # Print the docstring of the greet function using the __doc__ attribute
    This is a function docstring for greet.
    This function takes a name as an argument and prints a greeting message to the screen.
    Parameters:
        name (str): The name of the person to greet.
    Returns:
        None
    Raises:
        TypeError: If name is not a string.
    Examples:
        >>> greet("World")
        Hello, World!
        >>> greet(42)
        TypeError: name must be a string

As you can see, the __doc__ attribute returns the docstring of the greet function as a string, which you can print or use for other purposes.

As you can see, accessing and using docstrings in Python is very easy and convenient, as you can use the built-in functions help() and __doc__ to display, access, or manipulate the documentation of any object in Python. In the next section, you will learn how to generate documentation from docstrings using tools like Sphinx and Pydoc.

7. How to generate documentation from docstrings using tools like Sphinx and Pydoc

In this section, you will learn how to generate documentation from docstrings using tools like Sphinx and Pydoc. These tools can help you create professional and comprehensive documentation for your Python projects, using the docstrings that you have written in your code.

Sphinx is a tool that can generate HTML, PDF, ePub, and other formats of documentation from your docstrings and other sources, such as reStructuredText files. Sphinx can also integrate with other tools, such as autodoc, napoleon, and intersphinx, to automatically extract docstrings from your code, support different docstring styles and formats, and link to external documentation.

To use Sphinx, you need to install it using pip or conda, and then run the sphinx-quickstart command to create a basic configuration file and a source directory. You can then edit the configuration file to customize the options and settings for your documentation, such as the project name, the author, the theme, the extensions, etc. You can also add other sources of documentation, such as reStructuredText files, to the source directory, and use directives and roles to include your docstrings and other information. Finally, you can run the make command to build your documentation in the desired format.

For example, if you want to generate HTML documentation for the greet module and the Person class defined in the previous sections, you can follow these steps:

  1. Install Sphinx using pip or conda:
pip install sphinx # or conda install sphinx

2. Run the sphinx-quickstart command and answer the prompts to create a basic configuration file and a source directory:

sphinx-quickstart
    Welcome to the Sphinx 4.1.2 quickstart utility.

    Please enter values for the following settings (just press Enter to
    accept a default value, if one is given in brackets).

    Selected root path: .

    You have two options for placing the build directory for Sphinx output.
    Either, you use a directory "_build" within the root path, or you separate
    "source" and "build" directories within the root path.
    > Separate source and build directories (y/n) [n]: n

    The project name will occur in several places in the built documentation.
    > Project name: Greet and Person
    > Author name(s): John Doe
    > Project release []: 1.0

    If the documents are to be written in a language other than English,
    you can select a language here by its language code. Sphinx will then
    translate text that it generates into that language.

    For a list of supported codes, see
    https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.
    > Project language [en]: en

    Creating file ./conf.py.
    Creating file ./index.rst.
    Creating file ./Makefile.
    Creating file ./make.bat.

    Finished: An initial directory structure has been created.

    You should now populate your master file ./index.rst and create other documentation
    source files. Use the Makefile to build the docs, like so:
       make builder
    where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

3. Edit the configuration file conf.py to enable the extensions that you need, such as sphinx.ext.autodoc, sphinx.ext.napoleon, and sphinx.ext.intersphinx. You can also customize other options and settings, such as the theme, the logo, the sidebar, etc. For example, you can add these lines to the end of the file:

# Add any Sphinx extension module names here, as strings. They can be
    # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
    extensions = [
        'sphinx.ext.autodoc', # to automatically extract docstrings from your code
        'sphinx.ext.napoleon', # to support Google and NumPy style docstrings
        'sphinx.ext.intersphinx', # to link to external documentation
    ]

    # Add any paths that contain templates here, relative to this directory.
    templates_path = ['_templates']

    # The suffix of source filenames.
    source_suffix = '.rst'

    # The master toctree document.
    master_doc = 'index'

    # General information about the project.
    project = 'Greet and Person'
    author = 'John Doe'

    # The version info for the project you're documenting, acts as replacement for
    # |version| and |release|, also used in various other places throughout the
    # built documents.
    #
    # The short X.Y version.
    version = '1.0'
    # The full version, including alpha/beta/rc tags.
    release = '1.0'

    # The name of the Pygments (syntax highlighting) style to use.
    pygments_style = 'sphinx'

    # A list of ignored prefixes for module index sorting.
    modindex_common_prefix = []

    # If true, keep warnings as "system message" paragraphs in the built documents.
    # keep_warnings = False

    # If true, `todo` and `todoList` produce output, else they produce nothing.
    todo_include_todos = False

    # The theme to use for HTML and HTML Help pages.  See the documentation for
    # a list of builtin themes.
    #
    html_theme = 'alabaster' # you can choose other themes, such as 'sphinx_rtd_theme'

    # Theme options are theme-specific and customize the look and feel of a     
    # theme. For example, you can add these lines to the end of the file:
    html_theme_options = {
        'logo': 'logo.png',
        'github_user': 'username',
        'github_repo': 'reponame',
        'github_banner': True,
        'show_related': False,
        'note_bg': '#FFF59C'
    }

    # The name of an image file (relative to this directory) to place at the top of
    # the sidebar.
    html_logo = 'logo.png'

    # These folders are copied to the documentation's HTML output
    html_static_path = ['_static']

    # These paths are either relative to html_static_path
    # or fully qualified paths (eg. https://...)
    html_css_files = [
        'css/custom.css',
    ]

    # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
    # using the given strftime format.
    html_last_updated_fmt = '%b %d, %Y'

    # If false, no module index is generated.
    html_domain_indices = False

    # If false, no index is generated.
    html_use_index = False

    # If true, the index is split into individual pages for each letter.
    html_split_index = False

    # If true, links to the reST sources are added to the pages.
    html_show_sourcelink = False

8. Conclusion

In this tutorial, you have learned how to write comments and docstrings in Python, and how to use them to document your code and generate documentation.

  • What are comments and why are they important in Python programming
  • How to write single-line and multi-line comments in Python
  • What are docstrings and how do they differ from comments
  • How to write docstrings for modules, functions, classes, and methods in Python
  • How to access and use docstrings in Python using the built-in functions help() and __doc__
  • How to generate documentation from docstrings using tools like Sphinx and Pydoc

By following these steps, you can write clear and concise comments and docstrings for your Python code, and use them to create professional and comprehensive documentation for your projects.

Thank you for reading and happy coding!

The complete tutorial list is here:

Subscribe for FREE to get your 42 pages e-book: Data Science | The Comprehensive Handbook

Get step-by-step e-books on Python, ML, DL, and LLMs.

Python
Comments
Docstrings
Documentation
Programming
Recommended from ReadMedium