How to show instance attributes in sphinx doc?
30,720
Solution 1
Your variables are instance variables, not class variables.
Without attaching a docstring (or a #:
"doc comment") to the variables, they won't be documented. You could do as follows:
class MyClass(object):
"""
Description for class
"""
def __init__(self, par1, par2):
self.var1 = par1 #: initial value: par1
self.var2 = par2 #: initial value: par2
def method(self):
pass
But I would prefer to include variable documentation by using info fields:
class MyClass(object):
"""
Description for class
:ivar var1: initial value: par1
:ivar var2: initial value: par2
"""
def __init__(self, par1, par2):
self.var1 = par1
self.var2 = par2
def method(self):
pass
See also:
- http://www.sphinx-doc.org/ext/autodoc.html#directive-autoattribute
- How can I make Python/Sphinx document object attributes only declared in __init__?
- Problems with autodoc and explicitly specified instance attributes
Solution 2
For Python 3.9+ dataclass
style classes you can do
@dataclass
class MyClass:
#: Nice vars!
var1: int = 0
#: Life is beautiful, remember to buy flowers for your wife
var2: int = 0
Related videos on Youtube
Author by
Meloun
Updated on May 13, 2022Comments
-
Meloun about 2 years
Is there any way to automatically show variables var1 and var2 and their init-values in sphinx documentation?
class MyClass: """ Description for class """ def __init__(self, par1, par2): self.var1 = par1 * 2 self.var2 = par2 * 2 def method(self): pass
-
varunsinghal about 7 yearsAny setting required for #: doc comment to be visible in html pages by sphinx? I used sphinx-apidoc command to generate .rst files.
-
mzjn about 7 years@varunsinghal: is there a problem?
-
varunsinghal about 7 yearsI was using these doc comments #: for private class variables.
-
mzjn almost 7 years@varunsinghal: Perhaps you have been hit by this bug? github.com/sphinx-doc/sphinx/issues/1362
-
RayLuo over 5 yearsNice answer! You do not need to use
:ivar foo:
though, just:var foo
will do. -
c z over 3 years@RayLuo They're not synonyms though -
ivar
= instance variable,cvar
= class variable,var
= work it out yourself. While Sphinx doesn't care it informs a human reader. -
rv.kvetch about 2 yearsthese are actually class (static) variables, not dataclass fields. To be a dataclass field, you would need to annotate them, for ex. like
var1: int = 0