Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link to class method in python docstring

I want to add a link to a method in my class from within the docstring of another method of the same class. I want the link to work in sphinx and preferentially also in Spyder and other Python IDE's.

I tried several options and found only one that works, but it's cumbersome.

Suppose the following structure in mymodule.py

def class MyClass():     def foo(self):         print 'foo'     def bar(self):         """This method does the same as <link to foo>"""         print 'foo' 

I tried the following options for <link to foo>:

  • :func:`foo`
  • :func:`self.foo`
  • :func:`MyClass.foo`
  • :func:`mymodule.MyClass.foo`

The only one that effectively produces a link is :func:`mymodule.MyClass.foo`, but the link is shown as mymodule.MyClass.foo() and I want a link that is shown as foo() or foo.
None of the options above produces a link in Spyder.

Thanks for your help.

like image 747
saroele Avatar asked Jan 22 '14 17:01

saroele


People also ask

How do you write a docstring for a class in Python?

Declaring Docstrings: The docstrings are declared using ”'triple single quotes”' or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.

Should __ init __ have a docstring?

The class constructor should be documented in the docstring for its __init__ method. This is quite logical, as this is the usual procedure for functions and methods, and __init__() is not an exception. As a consequence, this puts the code and its documentation in the same place, which helps maintenance.

What is a class docstring?

A Python docstring is a string used to document a Python module, class, function or method, so programmers can understand what it does without having to read the details of the implementation. Also, it is a common practice to generate online (html) documentation automatically from docstrings.


1 Answers

The solution that works for Sphinx is to prefix the reference with ~.

Per the Sphinx documentation on Cross-referencing Syntax,

If you prefix the content with ~, the link text will only be the last component of the target. For example, :py:meth:~Queue.Queue.get will refer to Queue.Queue.get but only display get as the link text.

So the answer is:

class MyClass():     def foo(self):         print 'foo'     def bar(self):         """This method does the same as :func:`~mymodule.MyClass.foo`"""         print 'foo' 

This results in an html looking like this : This method does the same as foo(), and foo() is a link.

However, note that this may not display in Spyder as a link.

like image 171
saroele Avatar answered Oct 03 '22 06:10

saroele