Skip to content

Commit bcc941b

Browse files
Unique-UsmanMariattaJacobCoffeehugovkCAM-Gerlach
authored
gh-109510: Clearly explain "Which Docstrings Are Examined" (#109696)
Co-authored-by: Mariatta <[email protected]> Co-authored-by: Jacob Coffee <[email protected]> Co-authored-by: Hugo van Kemenade <[email protected]> Co-authored-by: C.A.M. Gerlach <[email protected]>
1 parent 63acf78 commit bcc941b

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

Doc/library/doctest.rst

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -277,13 +277,34 @@ Which Docstrings Are Examined?
277277
The module docstring, and all function, class and method docstrings are
278278
searched. Objects imported into the module are not searched.
279279

280-
In addition, if ``M.__test__`` exists and "is true", it must be a dict, and each
280+
In addition, there are cases when you want tests to be part of a module but not part
281+
of the help text, which requires that the tests not be included in the docstring.
282+
Doctest looks for a module-level variable called ``__test__`` and uses it to locate other
283+
tests. If ``M.__test__`` exists and is truthy, it must be a dict, and each
281284
entry maps a (string) name to a function object, class object, or string.
282285
Function and class object docstrings found from ``M.__test__`` are searched, and
283286
strings are treated as if they were docstrings. In output, a key ``K`` in
284-
``M.__test__`` appears with name ::
287+
``M.__test__`` appears with name ``M.__test__.K``.
285288

286-
<name of M>.__test__.K
289+
For example, place this block of code at the top of :file:`example.py`:
290+
291+
.. code-block:: python
292+
293+
__test__ = {
294+
'numbers': """
295+
>>> factorial(6)
296+
720
297+
298+
>>> [factorial(n) for n in range(6)]
299+
[1, 1, 2, 6, 24, 120]
300+
"""
301+
}
302+
303+
The value of ``example.__test__["numbers"]`` will be treated as a
304+
docstring and all the tests inside it will be run. It is
305+
important to note that the value can be mapped to a function,
306+
class object, or module; if so, :mod:`!doctest`
307+
searches them recursively for docstrings, which are then scanned for tests.
287308

288309
Any classes found are recursively searched similarly, to test docstrings in
289310
their contained methods and nested classes.

0 commit comments

Comments
 (0)