Search code examples
pythonpython-sphinx

What is the difference between var, cvar and ivar in python's sphinx?


I was reading through the sphinx documentation pages and ironically found that the documentation on the difference between var, ivar, and cvar very lacking. I was wondering if someone could explain the difference between each of the different name spaces in inline code.

Example:

class foo(object):
    """
      :var str first:
      :ivar str last:
      :cvar str middle:
    """

How are each of these sphinx tags different from each other and how do I know which one is the correct one to use correctly as designed?


Solution

  • var is a generic variable, of course. Use this when you don't care to make any further distinction about the variable you are documenting.

    ivar is an "instance variable", or a variable that is set on an instance object (an instance of a class). Typically these would be defined (in Python) inside of an __init__ method.

    cvar is a "class variable", or a variable that is set on a class object directly. Typically, this would be set inside a class statement, but outside of any particular method in the class.

    Here's an example:

    class SomeClass(object):
    
        cvar = 'I am a class variable'
    
        def __init__(self):
            self.ivar = 'I am an instance variable'