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:

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
Share:
30,720

Related videos on Youtube

Meloun
Author by

Meloun

Updated on May 13, 2022

Comments

  • Meloun
    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
    varunsinghal about 7 years
    Any setting required for #: doc comment to be visible in html pages by sphinx? I used sphinx-apidoc command to generate .rst files.
  • mzjn
    mzjn about 7 years
    @varunsinghal: is there a problem?
  • varunsinghal
    varunsinghal about 7 years
    I was using these doc comments #: for private class variables.
  • mzjn
    mzjn almost 7 years
    @varunsinghal: Perhaps you have been hit by this bug? github.com/sphinx-doc/sphinx/issues/1362
  • RayLuo
    RayLuo over 5 years
    Nice answer! You do not need to use :ivar foo: though, just :var foo will do.
  • c z
    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
    rv.kvetch about 2 years
    these 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