xdoctest is a powerful and flexible rewrite of Python's builtin `doctest` module, designed for better integration with modern development workflows, especially pytest. It offers enhanced features like static analysis, improved error reporting, and dynamic code execution. The current version is 1.3.2, and it maintains an active release cadence with frequent updates addressing features and bug fixes.
Warnings
breaking xdoctest dropped support for Python 3.6 and 3.7.
Fix: Ensure your project uses Python 3.8 or newer. For projects requiring Python 3.6 or 3.7, pin xdoctest to version `<=1.1.6`.
breaking The deprecated CLI flags `--xdoc-force-dynamic` and `--allow-xdoc-dynamic` were removed.
Fix: Update your CLI commands to remove these flags. xdoctest's dynamic behavior is now handled by default or through other mechanisms. Refer to the official documentation for current CLI options.
gotcha When using `xdoctest` with `pytest`, its integration mechanism changed.
Fix: xdoctest now uses the standard pytest plugin system to disable the stdlib `doctest` module instead of monkey patching. This generally means better compatibility and fewer conflicts, but might affect highly customized test setups. Standard usage (e.g., `pytest --xdoctest`) should continue to work as expected.
gotcha Discovering doctests in `async def` functions and using top-level `await` or the `ASYNC` directive.
Fix: Ensure you are on xdoctest version 1.3.2 or later for full and robust support for `async def` function discovery and correct line number reporting. Version 1.3.0 introduced the `ASYNC` directive for managing the asyncio event loop within tests, and 1.2.0 added support for top-level awaits.
gotcha Issues with module path resolution, especially for packages installed in editable mode.
Fix: Multiple fixes for `modname_to_modpath` were applied in versions 1.1.3, 1.1.4, and 1.1.5. If you encounter errors related to module discovery, particularly with editable installs or when module names differ from package names, ensure you are using xdoctest version 1.1.5 or newer.
Install
pip install xdoctestInstall core library
pip install xdoctest[all]Install with all optional dependencies
Automatically loaded by pytest when xdoctest is installed.
Quickstart
Create a Python file with doctests, then run them directly using the xdoctest CLI or programmatically. If pytest is installed, simply running `pytest --xdoctest` will discover and run xdoctests.
# my_module.py
def add_one(x):
"""
>>> add_one(1)
2
>>> add_one(0)
1
"""
return x + 1
# Run tests from the command line
# In your terminal:
# python -m xdoctest my_module.py
# Or programmatically:
import xdoctest
# For doctesting a specific module (e.g., 'my_module')
xdoctest.doctest_module('my_module')