Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I automatically link to a parameter type in ReST docstrings in Sphinx?

For example, I have the following code:

# Solve for coefficients of quadratic approximation
def quad(p, x):
    """Solves for the coefficients of the quadratic approximation of a
    polynomial ``p`` at points ``x``.

    :param :cls:`numpy.polynomial.Polynomial` p:
        The polynomial to be approximated by a quadratic function.
    :param list x:
        The three points along which the quadratic function is to be fitted.
    """

Notice the part where I say :cls:numpy.polynomial.Polynomial. How do I make that link directly to the documentation for the numpy.polynomial.Polynomial class?

like image 942
Kit Avatar asked Feb 15 '14 15:02

Kit


2 Answers

You can use intersphinx for this.

  1. Add these lines to conf.py:

    extensions = ["sphinx.ext.intersphinx"]        # Or edit existing 'extensions' list
    intersphinx_mapping = {'numpy': ('http://docs.scipy.org/doc/numpy/', None)}
    
  2. Use this reST markup in the docstring:

    :param p: The polynomial to be approximated by a quadratic function.
    :type p: :class:`~numpy:numpy.polynomial.polynomial.Polynomial`
    

This will result in a hyperlink (with the text "Polynomial") from the documentation of your quad() function to the documentation of numpy.polynomial.polynomial.Polynomial.

numpy.polynomial.Polynomial and numpy.polynomial.polynomial.Polynomial can be used interchangeably (see http://docs.scipy.org/doc/numpy/reference/routines.polynomials.classes.html#basics). The latter form is the one that is shown in the reference documentation and that is available as an intersphinx target.

If you want the link text to be the fully qualified class name, remove the tilde (~) character. See http://sphinx-doc.org/domains.html for more about "info field lists" and cross-references to Python objects.

like image 186
mzjn Avatar answered Sep 17 '22 22:09

mzjn


You use two different directives for the description and the type.

"""
...
:param p: The polynomial to be approximated by a quadratic function.
:type p: numpy.polynomial.Polynomial
...
:return: description of return value
:rtype: type of return value
"""

You can also use Python 3 annotations with the sphinx-autodoc-annotation plugin.

like image 26
davidism Avatar answered Sep 21 '22 22:09

davidism