Sphinx: Link to a method of a class in another module in Python docstring

Viewed 7147

I want to add a link to a method of a class in one module (say module_2.py) in another method in another module ( say module_1.py). I want the link to work in Sphinx.

Suppose:

module_1.py

class ABC:
   def foo(self):
      """
      See docstring of module_2.py bar():<link to bar() in module_2.py>
      """
      print("foo")

module_2.py

class XYZ:
    def bar(self):
    """
    This function prints hello.
    """
    print("hello")
2 Answers

To truly get a hyperlink, your method reference needs to contain a complete path. The simplest way to create any link is using the :obj: cross-reference:

"""See docstring of :obj:`path.to.module_2.XYZ.bar`."""

See docstring of path.to.module_2.XYZ.bar.

You can shorten the anchor text to just the last element of the path with the tild ~:

"""See docstring of :obj:`~path.to.module_2.XYZ.bar`."""

See docstring of bar.

Or specify custom text like so:

"""See docstring of :obj:`XYZ.bar <path.to.module_2.XYZ.bar>`."""

See docstring of XYZ.bar.

This is perhaps the most reader-friendly solution.

For completeness, note that :obj: is a general untyped reference, but Sphinx provides several other categories of cross-reference with some specific behaviours.

Related