Search code examples
pythonpython-sphinxdoctestautodoc

In Python Sphinx, is there a way to hide autodoc setup code?


I am using Sphinx autodoc to document my Python code. Examples in my documentation contain:

  • Uninteresting set up code I do not want rendered in the HTML documentation
  • Code that should appear in the documentation

For example:

Then you process file `example.txt` with `frobnicate()`:

    >>> with open('example.txt', 'w') as f:
    ...     _ = f.write("first boring line\\n")
    ...     _ = f.write("second boring line\\n")

    >>> frobnicate('example.txt')
    True

I want Sphinx autodoc to hide the uninteresting set up code so that the rendered HTML output from Sphinx contains only:

Then you process file example.txt with frobnicate():

    >>> frobnicate('example.txt')
    True

Obviously I still want doctest to execute the entire example as usual.


Solution

  • You can put the uninteresting setup code in a testsetup block.

    .. testsetup:: *
    
       with open('example.txt', 'w') as f:
           _ = f.write("first boring line\\n")
           _ = f.write("second boring line\\n")
    
    Then you process file `example.txt` with `frobnicate()`:
    
    >>> frobnicate('example.txt')
    True