How to document a module constant in Python?

skyler picture skyler · Nov 26, 2013 · Viewed 20.7k times · Source

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.

Answer

abarnert picture abarnert · Nov 26, 2013

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.