Search code examples
pythonimagepython-sphinxrestructuredtextautodoc

How to insert images after some specific functions in Sphinx docs?


I'm new to Sphinx. I generated .rst files using autodoc. The following is the .rst file for one of the modules:

Building things
=====================

Actions
----------------------------------

.. automodule:: acat.build.actions
    :members: func1, func2, func3
    :undoc-members:
    :show-inheritance:

Patterns
----------------------------------

.. automodule:: acat.build.patterns
    :members: func4, func5
    :undoc-members:
    :show-inheritance:

Orderings
----------------------------------

.. automodule:: acat.build.orderings
    :members: func6
    :undoc-members:
    :show-inheritance:

Now I want to insert images after func1, func3 and func5, I know the image can be embedded by

.. image:: func1_example.png

But where should I put these lines to make the images appear right under the corresponding functions?


Solution

  • Lets say you have 1 module with 2 functions and 3 docstrings, e.g:

    acat.build.actions.py

    """
    The module docstring.
    """
    
    def func1():
    """
    Docstring of func1.
    """
    
    
    def func2():
    """
    Docstring of func2.
    """
    

    In order to insert the image exactly where you want it you have to declare the image in the exact position in the .rst file. So you would write the acat.build.actions.rst like this:

    Building things
    =====================
    
    Actions
    ----------------------------------
    
    .. automodule:: acat.build.actions
        :members:
        :exclude-members: func1
        :undoc-members:
        :show-inheritance:
        
        .. autofunction:: func1
            
            You can write some text here.
            
            .. image:: func1_example.png 
    

    You exclude func1 explicitly from the module using the :exclude-members: func1 option because you want to include the image right underneath it. This allows you to write the documentation of func1 in a customized way, the .. autofunction:: directive will extract the docstring of func1 from the .py file but you are able to write the reStructuredText you want inside it. If you want to do this for more functions apply the same technique.