Is there a way to keep docstrings separate from the functions they document?

StackOverflow https://stackoverflow.com/questions/4732850

  •  12-10-2019
  •  | 
  •  

Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top