What Is Documentation in Python? 

Documentation in Python refers to the written text that accompanies a Python software project. This text explains the purpose and use of the code, making it easier for others (and often yourself in the future) to understand and maintain. Python documentation can come in many forms, from inline comments and docstrings within the code itself, to external documentation like user manuals and API references.

Python is particularly well-suited for good documentation practices due to its clean, readable syntax and strong support for docstrings—in-code explanations of functions, methods, and classes. Even Python’s philosophy, expressed in the Zen of Python, encourages code readability and hence, good documentation.

Another meaning of the term “documentation in Python” is the official documentation of the Python language. Here is a link to the documentation for the latest version of Python 3.

This is part of a series of articles about code documentation

In this article:

Why Documenting Your Python Code Is Important 

Code Maintainability

As a project grows, keeping track of every piece of code becomes increasingly challenging. Well-written documentation serves as a map, guiding you or other developers through the codebase. It’s particularly useful when hunting down bugs or implementing new features. Without documentation, you’re effectively lost in a sea of code.

Furthermore, documentation in Python also serves as a form of ‘defensive programming’. It helps catch and prevent errors. For instance, Python’s docstrings can include information about a function’s expected input and output types. This helps ensure that the function is used correctly, reducing the likelihood of bugs.

Onboarding New Developers

Documentation also plays a crucial role in onboarding new developers onto a project. Comprehensive documentation enables new developers to quickly understand the system’s architecture, the purpose of various parts of the code, and how they interact. This accelerates the onboarding process, reducing the time it takes for new developers to become productive members of the team.

Moreover, well-documented code fosters an environment of self-reliance. New developers can consult the documentation to answer their questions, rather than relying on others. This not only speeds up their learning process but also minimizes disruptions to the rest of the team.

Code Collaboration

In a team setting, developers are often working on different parts of a project simultaneously. Good documentation ensures that everyone understands not just their own code, but the entire codebase. This shared understanding facilitates effective collaboration, preventing conflicts and misunderstandings.

Good documentation also smoothens the code review process. Reviewers can refer to the documentation to better understand the code changes, enabling them to provide more valuable feedback. Consequently, this leads to higher code quality and fewer bugs.

Quality Assurance

Lastly, documentation plays a pivotal role in quality assurance. It provides a clear understanding of how the system is supposed to work, which is invaluable when testing. Testers can refer to the documentation to ensure that the system behaves as expected.

In addition, documentation can also guide the creation of automated tests. For instance, function docstrings can provide information about the expected inputs and outputs, which can be used to generate unit tests automatically. This not only improves the testing process but also helps maintain high code quality.

Related content: Read our guide to documentation as code

4 Ways to Document Python Code 

1. Inline Comments

One of the simplest ways to document your Python code is through inline comments. These are brief notes written directly into the code, typically on the same line or directly above the code they refer to. Here is the syntax for comments in Python:

#Example of a comment

print("Python program at work")

Inline comments are great for explaining the rationale behind certain code decisions, or for providing a quick summary of what a complex piece of code does.

However, it’s important to use inline comments judiciously. Overuse can clutter the code and make it harder to read. As a general rule, your code should be self-explanatory. Use comments to explain the ‘why’ (the reasoning behind the code), not the ‘what’ (what the code is doing).

2. Docstrings

Docstrings, or documentation strings, are a more powerful documentation tool in Python. They’re multi-line strings placed at the start of functions, classes, and modules that describe what these components do. Here is an example of the use of Docstrings:

def add(a: int, b: int) -> int:


    Add two integers together.


    a (int): The first integer to be added

    b (int): The second integer to be added


    int: The sum of a and b


    return a + b

if __name__ == “__main__”:

   print( f”Output: {add(5,10)}”

Docstrings can include information about the purpose of the function, its inputs and outputs, exceptions it may raise, and more.

Python has a built-in help() function that can display the docstring for any function, class, or module. This makes docstrings a highly accessible form of documentation.

3. Type Annotations and Type Checking

Python 3.5 introduced optional type hints, which allow you to specify the expected type of function arguments and return values. Here is an example of type hints:

from typing import List, Tuple

def get_even_and_odd(numbers: List[int]) -> Tuple[List[int], List[int]]:


    Takes a list of integers and separates them into two lists: one of even numbers and one of odd numbers.


    numbers (List[int]): The list of integers to be separated


    Tuple[List[int], List[int]]: A tuple containing a list of even numbers and a list of odd numbers


    even = [n for n in numbers if n % 2 == 0]

    odd = [n for n in numbers if n % 2 != 0]

    return (even, odd)

if __name__ == “__main__”:

    print(f”Even: {get_even_and_odd([1,2,3,4,5,6,7,8])}”)

    print(f”Odd:  {get_even_and_odd([1,2,3,4,5,6,7,8])}”)

In the example above, the type hints, indicated by List[int] and Tuple[List[int], List[int]], inform the developer that the function expects a list of integers as an argument and will return a tuple of two lists of integers. 

These type hints act as documentation and can also be used for type checking, either at runtime or statically (i.e., without running the code). Type checking can help catch certain types of bugs before the code is even run.

4. Documentation Generators

Documentation generators are tools that automatically create documentation from your code. In Python, the most popular documentation generator is Sphinx. It can generate documentation in various formats (including HTML and PDF) from reStructuredText, a lightweight markup language.

Sphinx can also auto-generate API documentation from your code’s docstrings. This makes it a powerful tool for creating comprehensive, professional-quality documentation with minimal effort.

Best Practices for Documenting Python Code 

Write Clear and Concise Docstrings

A good docstring should be clear, concise, and informative. It should quickly convey what the function does, without going into too much detail. Avoid jargon and complex language—your goal is to make the function’s purpose understandable to anyone who reads the docstring.

It’s also good practice to include information about the function’s inputs, outputs, and any exceptions it might raise. If your function has side effects (i.e., it changes some state outside its own scope), be sure to document these as well.

Include Examples in Documentation

Examples are a powerful way to illustrate how to use a function or class. They provide a concrete demonstration of the code in action, making it easier for others to understand how to use it. Including examples in your docstrings or external documentation can significantly improve their usefulness.

When writing examples, ensure they are simple, clear, and representative of typical use cases. Avoid complex or contrived examples, as they can be confusing rather than helpful.

Maintain Readable and Organized External Documentation

External documentation is just as important as inline comments and docstrings. It provides a high-level overview of your project, including its architecture, dependencies, setup instructions, usage guide, and more.

Keep your external documentation well-organized and easy to read. Use clear headings and subheadings, maintain a logical flow, and ensure it’s up-to-date. An out-of-date documentation can be worse than no documentation at all, as it can mislead users and developers.

Document All Public Interfaces

As a rule of thumb, all public interfaces of your code should be documented. This includes all public functions, methods, classes, and modules. These are the parts of your code that other people will interact with, so it’s crucial that they understand how to use them.

Private interfaces (i.e., parts of your code that are meant to be used only within their own module or class) don’t necessarily need to be documented, although it can still be helpful to do so.

Localize Documentation If Needed

If your project is intended for a global audience, consider localizing your documentation. This means translating it into multiple languages. While English is the lingua franca of the programming world, not all developers are comfortable with it. Providing localized documentation can make your project more accessible to a global audience.

Documentation in Python with Swimm

Documentation in Python is an indispensable aspect of any software project. It not only enhances code maintainability, making it easier to navigate and understand, but also plays a crucial role in onboarding new developers. With comprehensive documentation, teams can collaborate more effectively, leading to higher code quality and improved productivity. 

Swimm’s solution, designed for distinguished engineers, staff engineers, developers, and DevOps teams, offers code-coupled documentation that adapts as code changes, simplifying the documentation process and enhancing the onboarding experience. By combining code knowledge with Swimm’s capabilities, you can elevate your Python project’s documentation to new heights, ensuring your team’s success and efficient coding practices.

Learn more about Swimm