Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repetitive content in docstrings

What are good ways to deal with repetitive content in docstrings? I have many functions that take 'standard' arguments, which have to be explained in the docstring, but it would be nice to write the relevant parts of the docstring only once, as this would be much easier to maintain and update. I naively tried the following:

arg_a = "a: a very common argument"

def test(a):
    '''
    Arguments:
    %s
    ''' % arg_a
    pass

But this does not work, because when I do help(test) I don't see the docstring. Is there a good way to do this?

like image 254
astrofrog Avatar asked Apr 04 '10 21:04

astrofrog


People also ask

What should be included in docstrings?

The docstring for a function or method should summarize its behavior and document its arguments and return values. It should also list all the exceptions that can be raised and other optional arguments.

What are the three types of docstrings?

Docstrings can be further broken up into three major categories: Class Docstrings: Class and class methods. Package and Module Docstrings: Package, modules, and functions. Script Docstrings: Script and functions.

How are docstrings different from regular comments?

A quick recap on comments vs docstrings: Use comments to explain how code works. Comments are great for leaving notes for people working on your program. Docstrings provide documentation about functions, classes, and modules. Use docstrings to teach other developers how to use your program.

Which of the following is a feature of docstrings?

Which of the following is a feature of DocString? Options are : Provide a convenient way of associating documentation with Python modules, functions, classes, and methods. All functions should have a docstring.


2 Answers

As the other answers say, you need to change the __doc__ member of the function object. A good way to do this is to use a decorator that will perform the formatting on the docstring:

def fixdocstring(func):
    func.__doc__ = func.__doc__.replace('<arg_a>', 'a: a very common argument')
    #(This is just an example, other string formatting methods can be used as well.)
    return func

@fixdocstring
def test(a):
    '''
    Arguments:
    <arg_a>
    ''''
    pass
like image 78
interjay Avatar answered Sep 22 '22 13:09

interjay


__doc__ is assignable on most user-defined types:

arg_a = "a: a very common argument"

def test(a):
    pass

test.__doc__ = '''
    Arguments:
    %s
    ''' % arg_a
like image 40
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 13:09

Ignacio Vazquez-Abrams