How to show instance attributes in sphinx doc?

Meloun picture Meloun · Dec 27, 2011 · Viewed 23.7k times · Source

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

Answer

mzjn picture mzjn · Dec 28, 2011

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: