Reputation:
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")
Upvotes: 12
Views: 10811
Reputation: 3819
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.
Upvotes: 11
Reputation: 16249
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
Upvotes: 8