Search code examples
pythondocstring

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?


Solution

  • 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