6

I'm working on a module with many small functions but whose docstrings tend to be quite long. The docstrings make working on the module irritating as I have to constantly scroll over a long docstring to find a little bit of actual code.

Is there a way to keep docstrings separate from the functions they document? I'd really like to be able to specify the docstrings at the end of the file away from the code or, even better, in a separate file.

hwiechers
  • 14,583
  • 8
  • 53
  • 62
  • Do you want the docstrings for online help (ie. `help(func)` in a Python console) or for generated API docs (eg. via Sphinx)? – detly Jan 19 '11 at 08:20

1 Answers1

12

The docstring for a function is available as the special attribute __doc__.

>>> def f(x):
...     "return the square of x"
...     return x * x
>>> f.__doc__
'return the square of x'
>>> help(f)
(help page with appropriate docstring)
>>> f.__doc__ = "Return the argument squared"
>>> help(f)
(help page with new docstring)

That demonstrates the technique, anyway. In practice you can:

def f(x):
    return x * x

f.__doc__ = """
Return the square of the function argument.

Arguments: x - number to square

Return value: x squared

Exceptions: none

Global variables used: none

Side effects: none

Limitations: none
"""

...or whatever you want to put in your docstrings.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 1
    Good tip. How about a `mymodule.docs` that sets the docstrings for the features in `mymodule`. I too find inline documentation anoying, unless it's minimal and relevant. Pythons own documentation is processed through Sphinx, which encourages out-of-code docs. – Apalala Jan 20 '11 at 06:17