On this page
  1. doctest
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Running Doctests Across a Module or Documentation File
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

doctest

Prev: dis | Up: stdlib_module | Next: email
Rel: typing, annotationlib, pydoc, pydoc_data, unittest
Ref: docs.python.org — doctest
Tags: #public #python3 #stdlib


Import

import doctest

Overview

Extracts and executes interactive Python REPL examples (>>> ...) embedded directly inside docstrings and Markdown/text files (testmod, testfile, python -m doctest). Ideal for keeping README and docstring examples guaranteed runnable in CI without duplicating them into separate test files.

Quick Start

import doctest

def double(n: int) -> int:
    '''Return twice n.

    >>> double(21)
    42
    '''
    return n * 2

res = doctest.run_docstring_examples(double, {"double": double}, verbose=False)

Implementation Walkthrough

1. Running Doctests Across a Module or Documentation File

python3 -m doctest -v my_module.py
import doctest
import sys

# Programmatic check returning (failure_count, test_count):
# result = doctest.testmod(sys.modules[__name__], optionflags=doctest.ELLIPSIS)

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes