I want to document Python object attributes with Sphinx. I understand I should use
:ivar varname: description
:ivar type varname: description
However I'm seeing a weird behaviour, that is Sphinx searches my project for the variable name and tries to create symlinks. E.g. this code:
class A(object):
"""
:ivar x: some description
"""
def __init__(self, x):
self.x = x
class B(object):
def x(self):
return 1
class C(object):
def x(self):
return 2
will cause this error:
module1.py:docstring of mylibrary.module1.A:None: WARNING: more than one target found for cross-reference u'x': mylibrary.module1.C.x, mylibrary.module1.B.x
Did I understand incorrectly the purpose or usage of :ivar?
As mzjn referred there is an open issue for this SO post. In that thread there is also already a work-around for the issue posted. In sum, you use inline comments
#:
instead of the docstring.Take a look at the
python.py
file in the commit referred by the user here. The docstring entries were removed (red lines), and he added inline comments in the constructor (green lines).I have been looking for documentation on this but could not find it. For instance:
As noted by Nick Bastin this work-around renders completely differently from
:ivar:
. There is no type support, and it always renders the default value.Here is a monkey patch (based on Sphinx 1.5.1) that disables
ivar
cross-references. I'm not sure what the best solution is, so consider the patch an experimental suggestion. To try it out, add the code below toconf.py
.The original
TypedField.make_field
method is here: https://github.com/sphinx-doc/sphinx/blob/master/sphinx/util/docfields.py.Here is a workaround provided by
@acrisci
on github: prefix your variable name with~.
. For example replacewith this:
Source: https://github.com/sphinx-doc/sphinx/issues/2549#issuecomment-488896939
There's an alternative with other advantages. Just define you member variables at class scope and document them with plain docstring. Later you can reference them with
py:attr:
role. It's more readable, self-documented (yeah, I know this is under python-sphinx, but anyway) and introspection-friendly approach.module.py
README.txt
conf.py
Build like
PYTHONPATH=. sphinx-build . html
.