What does .. testcode:: or .. doctest:: do in *.rst files?

I see some .. testcode:: or .. doctest:: blocks in the *.rst files in cpython source code. They seem to be doctests, but I am not sure how to run these tests. Are there any instructions please?

It’s super handy for embedding code examples that double as tests. For e.g:

.. testcode::

   def add(a, b):
       return a + b

   result = add(2, 3)
   print(result)

.. testoutput::

   5

This snippet not only shows how the add function works but also serves as a test. When you run doctest, it’ll execute the code and compare the output to what’s in the testoutput block.

If you’re in the Doc/ directory, you should be able to run make venv && make doctest to run the doctests locally (not sure how to do it on Windows).

This should probably be documented in the devguide somewhere (not sure if it is already or not, I haven’t checked).