How to document a module constant in Python?

Python Programming

Question or problem about Python programming:

I have a module, errors.py in which several global constants are defined (note: I understand that Python doesn’t have constants, but I’ve defined them by convention using UPPERCASE).

"""Indicates some unknown error."""
API_ERROR = 1

"""Indicates that the request was bad in some way."""
BAD_REQUEST = 2

"""Indicates that the request is missing required parameters."""
MISSING_PARAMS = 3

Using reStructuredText how can I document these constants? As you can see I’ve listed a docstring above them, but I haven’t found any documentation that indicates to do that, I’ve just done it as a guess.

How to solve the problem:

Solution 1:

Unfortunately, variables (and constants) do not have docstrings. After all, the variable is just a name for an integer, and you wouldn’t want to attach a docstring to the number 1 the way you would to a function or class object.

If you look at almost any module in the stdlib, like pickle, you will see that the only documentation they use is comments. And yes, that means that help(pickle) only shows this:

DATA
    APPEND = b'a'
    APPENDS = b'e'
    …

… completely ignoring the comments. If you want your docs to show up in the built-in help, you have to add them to the module’s docstring, which is not exactly ideal.


But Sphinx can do more than the built-in help can. You can configure it to extract the comments on the constants, or use autodata to do it semi-automatically. For example:

#: Indicates some unknown error.
API_ERROR = 1

Multiple #: lines before any assignment statement, or a single #: comment to the right of the statement, work effectively the same as docstrings on objects picked up by autodoc. Which includes handling inline rST, and auto-generating an rST header for the variable name; there’s nothing extra you have to do to make that work.


As a side note, you may want to consider using an enum instead of separate constants like this. If you’re not using Python 3.4 (which you probably aren’t yet…), there’s a backport.enum package for 3.2+, or flufl.enum (which is not identical, but it is similar, as it was the main inspiration for the stdlib module) for 2.6+.

Enum instances (not flufl.enum, but the stdlib/backport version) can even have docstrings:

class MyErrors(enum.Enum):
    """Indicates some unknown error."""
    API_ERROR = 1

    """Indicates that the request was bad in some way."""
    BAD_REQUEST = 2

    """Indicates that the request is missing required parameters."""
    MISSING_PARAMS = 3

Although they unfortunately don’t show up in help(MyErrors.MISSING_PARAMS), they are docstrings that Sphinx autodoc can pick up.

Solution 2:

If you put a string after the variable, then sphinx will pick it up as the variable’s documentation. I know it works because I do it all over the place. Like this:

FOO = 1
"""
Constant signifying foo.

Blah blah blah...
"""  # pylint: disable=W0105

The pylint directive tells pylint to avoid flagging the documentation as being a statement with no effect.

Solution 3:

This is an older question, but I noted that a relevant answer was missing.

Or you can just include a description of the constants in the docstring of the module via .. py:data::. That way the documentation is also made available via the interactive help. Sphinx will render this nicely.

"""
Docstring for my module.

.. data:: API_ERROR

    Indicates some unknown error.

.. data:: BAD_REQUEST

    Indicates that the request was bad in some way.

.. data:: MISSING_PARAMS

    Indicates that the request is missing required parameters.
"""

Solution 4:

You can use hash + colon to document attributes (class or module level).

#: Use this content as input for moo to do bar
MY_CONSTANT = "foo"

This will be picked up by some document generators.

An example here, could not find a better one: Sphinx document module properties

Solution 5:

I think you’re out of luck here.


Python don’t support directly docstrings on variables: there is no attribute that can be attached to variables and retrieved interactively like the __doc__ attribute on modules, classes and functions.

Source.

Solution 6:

Writing only because I haven’t seen this option in the answers so far:

You can also define your constants as functions that simply return the desired constant value when called, so for example:

def get_const_my_const() -> str: """Returns 'my_const'.""" return "my_const" 

This way they’ll be a bit “more constant” on one hand (less worrying about reassignment) and they’ll also provide the opportunity for regular documentation, as with any other function.

Solution 7:

The Sphinx Napoleon Python documentation extension allows to document module-level variables in an Attributes section.

Per https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_numpy.html :

Attributes ---------- module_level_variable1 : int Module level variables may be documented in either the ``Attributes`` section of the module docstring, or in an inline docstring immediately following the variable. Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it. 

Solution 8:

the following worked for me with Sphinx 2.4.4:

in foo.py :

API_ERROR = 1 """int: Indicates some unknown error.""" 

then to document it:

.. automodule:: foo.py :members: 

Hope this helps!