Fundamentals 7 min read

Master Python Doctest: Embed Tests Directly in Your Docs

This guide explains how Python's built‑in doctest module lets you write test cases inside docstrings, run them from the command line or programmatically, handle common pitfalls like whitespace and floating‑point issues, and integrate doctests into larger projects for reliable documentation‑driven testing.

Code Mala Tang
Code Mala Tang
Code Mala Tang
Master Python Doctest: Embed Tests Directly in Your Docs

Did you know? doctest is a built‑in testing method in Python that allows you to write test code inside a function’s docstring. Python automatically runs these examples to verify that the code works as expected, which is especially useful for reusable functions.

What Is DocTest?

DocTest is a form of example code placed in a function’s docstring. Python executes these examples and checks that they produce the expected results. Below is a simple example:

<code>def add(a, b):
    """
    Return the sum of a and b.
    >>> add(2, 3)
    5
    >>> add(-1, 1)
    0
    """
    return a + b
</code>

The &gt;&gt;&gt; symbols represent input you would type at the Python interpreter, and the following line shows the expected output.

Running DocTests

To run DocTests, you need Python’s built‑in doctest module. After saving your script, execute:

<code>python -m doctest your_script.py</code>

If the command produces no output, all tests passed. For detailed output, use:

<code>python -m doctest -v your_script.py</code>

If a test fails, Python displays an error message showing the expected versus actual results.

Using DocTests in Classes

DocTests also work for class methods. For example:

<code>class Calculator:
    """A simple calculator class."""

    def multiply(self, x, y):
        """
        Return the product of x and y.
        >>> c = Calculator()
        >>> c.multiply(3, 4)
        12
        >>> c.multiply(-2, 5)
        -10
        """
        return x * y
</code>

Running the DocTest verifies that the class method behaves as documented.

Common Issues and Solutions

Issue 1: Extraneous Whitespace

DocTest checks whitespace strictly, which can cause unexpected failures. Example:

<code>def greet(name):
    """
    Return a greeting message.
    >>> greet("kiran")
    'Hello, kiran!'
    """
    return "Hello, kiran! "
</code>

To ignore extra whitespace, use the doctest.NORMALIZE_WHITESPACE option:

<code>import doctest

doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
</code>

Issue 2: Floating‑Point Precision

Minor differences in floating‑point rounding can cause failures. Example:

<code>def divide(a, b):
    """
    Return the result of division.
    >>> divide(5, 2)
    2.5
    """
    return a / b
</code>

Use the doctest.ELLIPSIS option to ignore tiny differences:

<code>import doctest

doctest.testmod(optionflags=doctest.ELLIPSIS)
</code>

Programmatically Running DocTests in a Script

If you want to run DocTests from within the script itself, call doctest.testmod() :

<code>if __name__ == "__main__":
    import doctest
    doctest.testmod()
</code>

Now each time the script runs, all embedded DocTests are executed automatically.

Skipping DocTests

Sometimes you may want to skip certain tests, such as those involving random numbers. Use the # doctest: +SKIP comment:

<code>def random_number():
    """
    Return a random number.
    >>> random_number()  # doctest: +SKIP
    42
    """
    import random
    return random.randint(1, 100)
</code>

Python will ignore this test.

Testing Edge Cases with DocTests

Always test edge cases, such as empty inputs or large numbers. Example:

<code>def factorial(n):
    """
    Return the factorial of n.
    >>> factorial(0)
    1
    >>> factorial(5)
    120
    >>> factorial(10)
    3628800
    """
    if n == 0:
        return 1
    return n * factorial(n - 1)
</code>

This ensures the function handles all edge conditions correctly.

Using DocTests in Real Projects

For small functions, DocTests are an excellent choice. In larger projects, developers often prefer unit‑testing frameworks like unittest or pytest , but DocTests can still be valuable for:

Testing simple functions.

Quickly verifying code examples in documentation.

Providing runnable examples in tutorials.

In large codebases, DocTests can be integrated into CI/CD pipelines to run automatically before deployment.

Why Use DocTests?

They serve as both documentation and tests.

They ensure code behaves exactly as described.

They are built into Python with no extra setup required.

They help catch simple errors early in development.

PythonTestingunit testingdocumentationcode examplesdoctest
Code Mala Tang
Written by

Code Mala Tang

Read source code together, write articles together, and enjoy spicy hot pot together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.