Creating Sphinx cross-references

Sphinx expands the cross-reference techniques available via RST. The most important set of cross-reference capabilities is the ability to directly refer to specific Python code features. These make use of the inline RST markup using the :role:`text` syntax. In this case, a large number of additional roles are part of Sphinx.

We have the following kinds of cross-reference roles available:

  • The :py:mod:`some_module` syntax will generate a link to the definition of this module or package.
  • The :py:func:`some_function` syntax will generate a link to the definition of the function. A qualified name with module.function or package.module.function can be used.
  • The :py:data:`variable` and :py:const:`variable` syntax will generate a link to a module variable that's defined with a .. py:data:: variable directive. A constant is simply a variable that should not be changed.
  • The :py:class:`some_class` syntax will link to the class definition. Qualified names such as module.class can be used.
  • The :py:meth:`class.method` syntax will link to a method definition.
  • The :py:attr:`class.attribute` syntax will link to an attribute that's defined with a .. py:attribute:: name directive.
  • The :py:exc:`exception` syntax will link to a defined exception.
  • The :py:obj:`some_object` syntax can create a generic link to an object.

If we use ``SomeClass`` in our docstring, we'll get the class name in a monospaced font. If we use :py:class:`SomeClass`, we get a proper link to the class definition, which is often far more helpful.

The :py: prefix on each role is there because Sphinx can be used to write the documentation about other languages in addition to Python. By using this :py: prefix on each role, Sphinx can provide proper syntax additions and highlighting.

Here's a docstring that includes explicit cross-references to other classes and exceptions:

def card(rank: int, suit: Suit) -> Card:
"""
Create a :py:class:`Card` instance from rank and suit.
Can raise :py:exc:`TypeError` for ranks out of the range 1 to 13, inclusive.

:param suit: Suit object
:param rank: Numeric rank in the range 1-13
:returns: :py:class:`Card` instance
:raises TypeError: rank out of range
"""

By using :py:class:`Card` instead of ``Card``, we're able to create explicit links between this comment block and the definition of the Card class. While it's a bit of typing overhead to include the role prefix, the resulting web of cross-references leads to very useful documentation.

When our projects get larger, we may need to use directories to organize the files. In the next section, we'll look at techniques for refactoring a long flat sequence of files into directories to impose some structure and organization.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset