liveBook · Manning

Doctest

As explained in Learn AI-Assisted Python Programming, Second Edition

doctest is a Python standard-library module and testing mechanism that executes interactive examples embedded in documentation and checks their output.

doctest is Python’s built-in way to test examples written inside a function’s docstring. Each example shows a call and the output expected from that call, so the documentation also becomes an executable test. section 6.3.3 section 6.8

A basic doctest workflow has three parts:

  • Write representative calls after the >>> prompt in a function’s docstring, followed by the expected results. section 6.3.3
  • Import doctest and call doctest.testmod() so Python discovers and runs the examples in the file. section 6.3.3
  • Read the result: verbose=True reports every test, while the default reports output mainly when a test fails. section 6.3.3

Testing longest_word

A docstring can specify ordinary cases, a one-item list, and a tie: >>> longest_word(['cat', 'dog', 'me']) followed by 'cat'. Running doctest checks whether the function returns the documented value. If the implementation uses >= instead of >, the tie case can expose the error by returning 'dog' rather than the first longest word.

Use doctest while developing generated code: include tests in the prompt, inspect the suggested implementation, run the tests, and revise the prompt or code when a test fails. For file-processing functions, create artificial files so tests exercise known data. Compare output exactly; even an unintended trailing space can cause failure. section 6.4 section 6.6.4

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains docstrings, testmod, verbosity, failures, edge cases, and spacing pitfalls, but defers fuller production tools such as pytest.
Examples
Demonstrates longest-word selection, classroom seating, CSV statistics, artificial files, output mismatches, and test-coverage exercises.
What it assumes
Assumes basic Python functions and docstrings while introducing lightweight testing from the Python prompt and standard library.
What you can do after
Apply it via Python’s doctest module to write, run, interpret, and improve executable examples for functions.
How it connects
Connects docstrings, test cases, regression testing, pytest, prompt engineering, and code debugging.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.