3

What is the preferred way to document static variables in classes?

class Foo(object):
    """
    Foo doc.
    """

    bar = 'bar'
    """
    Bar doc.
    """


class Foo(object):
    """
    Foo doc.
    """

    # Bar doc.
    bar = 'bar'

Something else...?

Zong
  • 6,160
  • 5
  • 32
  • 46
morgoth84
  • 1,070
  • 2
  • 11
  • 25

3 Answers3

3

There is no way to associate docstrings with variables. The PEP to add attribute docstrings failed.

The best way for code documentation is probably a comment rather than a docstring, so that you aren't introducing ambiguity of the kinds that the PEP discusses. You can additionally document them in the class' docstring if you want them in help() and docs.

otus
  • 5,572
  • 1
  • 34
  • 48
1

I personally use the Google-style DocString format and my approach to static attributes is to include them in the class' DocString.

E.g.

class Bicycle:
    """
    A class defining a Bicycle

    Attributes:
        NUM_WHEELS (int): The number of wheels that a bicycle has: 2.
    """
    NUM_WHEELS = 2

This is definitely an opinionated topic though. Depending on how visible you want your attributes to be, it might also make sense to just document them using a normal comment above the attribute's definition. E.g.

class Bicycle:
    """
    A class defining a Bicycle
    """
    # The number of wheels that a bicycle has
    NUM_WHEELS = 2
Eric Le Fort
  • 2,571
  • 18
  • 24
  • I guess with google-style, both static and non-static attributes are listed under `Attributes:` then? – thayne May 13 '21 at 14:17
  • Class/static variables are documented here in the class. Instance/non-static variables would be documented in the \_\_init__ method's DocString. – Eric Le Fort May 23 '21 at 01:23
0

The Epydoc documentation tool does provide support for variable doc strings:

http://epydoc.sourceforge.net/manual-docstring.html#variable-docstrings

The format is just as you have suggested above:

if a variable assignment statement is immediately followed by a bare string literal, then that assignment is treated as a docstring for that variable

gambl
  • 1