11

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")
Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
  • You have answers here https://stackoverflow.com/questions/21289806/link-to-class-method-in-python-docstring, and more here : https://stackoverflow.com/questions/11168178/how-do-i-reference-a-documented-python-function-parameter-using-sphinx-markup – Laurentourte Jul 24 '17 at 13:56
  • Possible duplicate of [Link to class method in python docstring](https://stackoverflow.com/questions/21289806/link-to-class-method-in-python-docstring) – billc.cn Apr 10 '19 at 19:49

2 Answers2

11

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.

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
8

You can write:

class ABC:
  def foo(self):
    """
    See docstring of :py:meth:`bar() <XYZ.bar>` in :py:mod:`module_2`.
    """
    print("foo")

The shown markup uses a role to link to a documented element. If Python is the default domain for your documentation, then :py can be omitted. The role meth links to a method name. A dotted name can be used. Likewise, mod links to a module name. The content of a role is written wetween ``. The content (logical link name can have a differnet visual content. Therefore the logical link name is written in <>. Example: :role:`text <logical name>`.

Further information: http://www.sphinx-doc.org/en/stable/domains.html#role-py:meth

mzjn
  • 48,958
  • 13
  • 128
  • 248
Paebbels
  • 15,573
  • 13
  • 70
  • 139
  • I don't see the path to `bar()` in it's docstring. Suppose you prohibited to write `in :py:mod:`module_2`` – Dims Jan 25 '19 at 09:50