# pydoc > doctest

---
type: CommandReference
command: doctest
mode: pydoc
section: ""
source: pydoc3
---

## Quick Reference

- `doctest.testmod()` — run doctests in the current module; prints failures only
- `python M.py -v` — run module with verbose flag to show all test results
- `doctest.testfile("example.txt")` — test examples in a text file
- `doctest.DocTestSuite(module)` — convert module doctests to a unittest suite
- `doctest.run_docstring_examples(f, globs)` — test examples in a single function's docstring
- `doctest.debug(module, name)` — debug a single docstring's tests
- `doctest.script_from_examples(text)` — convert doctest text to a Python script with comments
- `doctest.set_unittest_reportflags(flags)` — set reporting flags for unittest integration

## Name

Module doctest — a framework for running examples in docstrings.

## Synopsis

python
import doctest
doctest.testmod()   # test the current module
Run from command line:

shell
python M.py -v       # verbose mode
## Options

### Option flags (integer constants, OR together)

- `DONT_ACCEPT_TRUE_FOR_1` (1) — do not treat `True` as `1` in output comparison
- `DONT_ACCEPT_BLANKLINE` (2) — do not treat `<BLANKLINE>` as a blank line
- `NORMALIZE_WHITESPACE` (4) — ignore whitespace differences
- `ELLIPSIS` (8) — allow `...` to match any substring
- `SKIP` (16) — skip this example entirely
- `IGNORE_EXCEPTION_DETAIL` (32) — ignore exception detail (e.g., module names)
- `REPORT_UDIFF` (64) — use unified diff for failures
- `REPORT_CDIFF` (128) — use context diff
- `REPORT_NDIFF` (256) — use ndiff
- `REPORT_ONLY_FIRST_FAILURE` (512) — stop after first failure in each test
- `FAIL_FAST` (1024) — exit after first failure (global)

### Common keyword arguments for `testmod()` and `testfile()`

- `verbose` — bool, print detailed output (default: `True` if `-v` in `sys.argv`)
- `report` — bool, print summary at end (default: `True`)
- `globs` — dict, initial globals for examples (default: `{}` or `module.__dict__`)
- `extraglobs` — dict, extra globals merged into `globs`
- `optionflags` — integer, OR of option flags
- `raise_on_error` — bool, raise exception on first failure (for debugging)
- `module_relative` — bool for `testfile()`: treat path as module-relative (default: `True`)
- `package` — package name for module-relative paths
- `parser` — `DocTestParser` subclass (default: `DocTestParser`)
- `encoding` — file encoding for `testfile()` and `DocFileSuite`

## Examples

### Basic usage: test a module

python
# mymodule.py
def add(a, b):
    """
    >>> add(2, 3)
    5
    >>> add(-1, 1)
    0
    """
    return a + b

if __name__ == "__main__":
    import doctest
    doctest.testmod()
Run: `python mymodule.py` (no output if all pass) or `python mymodule.py -v` (verbose).

### Using `testfile()`

python
import doctest
doctest.testfile("examples.txt", verbose=True)
### Creating a unittest suite

python
import doctest
import mymodule
suite = doctest.DocTestSuite(mymodule)
# use with unittest runner
### Debugging a single docstring

python
import doctest
doctest.debug("mymodule", "add")   # debug the docstring of mymodule.add
### Extracting script from examples

python
>>> from doctest import script_from_examples
>>> text = '''
...     >>> 2 + 2
...     5
... '''
>>> print(script_from_examples(text))
# Expected:
# 5
2 + 2
## Classes

### `DocTest(examples, globs, name, filename, lineno, docstring)`

A collection of doctest examples to run in a single namespace.

- `examples` — list of `Example` objects
- `globs` — namespace dict
- `name` — name of the test (e.g., function name)
- `filename` — source file path or `None`
- `lineno` — starting line number (0‑based)
- `docstring` — original docstring or `None`

### `Example(source, want, exc_msg=None, lineno=0, indent=0, options=None)`

A single doctest example.

- `source` — Python statement (ends with newline)
- `want` — expected output (ends with newline or empty)
- `exc_msg` — expected exception message or `None`
- `lineno` — line number in docstring
- `indent` — indentation before prompt
- `options` — dict of per‑example option flags

### `DocTestFinder(verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True)`

Extracts `DocTest` objects from modules, functions, classes, methods, etc.

- `find(obj, name=None, module=None, globs=None, extraglobs=None)` — returns list of `DocTest`

### `DocTestParser()`

Parses strings containing doctest examples.

- `parse(string, name='<string>')` — returns list of alternating `Example` and text strings
- `get_examples(string, name='<string>')` — returns list of `Example` objects
- `get_doctest(string, globs, name, filename, lineno)` — returns a `DocTest` object

### `DocTestRunner(checker=None, verbose=None, optionflags=0)`

Runs `DocTest` cases and accumulates statistics.

- `run(test, compileflags=None, out=None, clear_globs=True)` — run examples in `test`
- `summarize(verbose=None)` — print summary, return `(failures, attempts)`
- `merge(other)` — merge statistics from another runner
- `report_start(out, test, example)` — called before each example
- `report_success(out, test, example, got)` — called on success
- `report_failure(out, test, example, got)` — called on failure
- `report_unexpected_exception(out, test, example, exc_info)` — called on unexpected exception
- `tries` — attribute: total examples tried
- `failures` — attribute: total failures

### `DebugRunner(checker=None, verbose=None, optionflags=0)`

Subclass of `DocTestRunner` that raises `DocTestFailure` or `UnexpectedException` on first failure.

### `OutputChecker()`

Compares actual output to expected output.

- `check_output(want, got, optionflags)` — returns `True` if match
- `output_difference(example, got, optionflags)` — returns string describing differences

### `DocTestFailure(test, example, got)`

Exception raised when output does not match (in `DebugRunner`). Attributes: `test`, `example`, `got`.

### `UnexpectedException(test, example, exc_info)`

Exception raised on unexpected exception (in `DebugRunner`). Attributes: `test`, `example`, `exc_info`.

## Functions

- `testmod(m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False)` — test module docstrings; returns `(failures, tests)`
- `testfile(filename, module_relative=True, name=None, package=None, globs=None, extraglobs=None, verbose=None, report=True, optionflags=0, raise_on_error=False, parser=DocTestParser(), encoding=None)` — test examples in a file; returns `(failures, tests)`
- `DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options)` — return a `unittest.TestSuite` from module doctests
- `DocFileSuite(*paths, **kw)` — return a unittest suite from one or more doctest files
- `run_docstring_examples(f, globs, verbose=False, name='NoName', compileflags=None, optionflags=0)` — test examples in a single object's docstring
- `debug(module, name)` — debug a single docstring in a module
- `debug_src(src)` — debug a docstring from source string
- `testsource(module, name)` — return the test source from a docstring as a script
- `script_from_examples(text)` — convert text with examples to a Python script with comments
- `set_unittest_reportflags(flags)` — set reporting flags for unittest integration; returns old flags
- `register_optionflag(name)` — register a new option flag name

## Data

| Constant | Value | Description |
|----------|-------|-------------|
| `DONT_ACCEPT_TRUE_FOR_1` | 1 | Prevent `True` matching `1` |
| `DONT_ACCEPT_BLANKLINE` | 2 | Disable `<BLANKLINE>` |
| `NORMALIZE_WHITESPACE` | 4 | Ignore whitespace differences |
| `ELLIPSIS` | 8 | Use `...` as wildcard |
| `SKIP` | 16 | Skip the example |
| `IGNORE_EXCEPTION_DETAIL` | 32 | Ignore exception details |
| `REPORT_UDIFF` | 64 | Unified diff output |
| `REPORT_CDIFF` | 128 | Context diff output |
| `REPORT_NDIFF` | 256 | ndiff output |
| `REPORT_ONLY_FIRST_FAILURE` | 512 | Report only first failure |
| `FAIL_FAST` | 1024 | Exit on first failure |
| `COMPARISON_FLAGS` | 63 | All comparison flags (1+2+4+8+16+32) |
| `REPORTING_FLAGS` | 1984 | All reporting flags (64+128+256+512+1024) |

## See Also

- [Python documentation for doctest](https://docs.python.org/3.10/library/doctest.html)
- `unittest` — Python unit testing framework
- `pdb` — Python debugger (used by `debug()`)

## Exit Codes

Not documented. `doctest.testmod()` returns `(failures, attempts)`; no specific process exit code unless the script defines one.