views:

91

answers:

3

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?

+1  A: 

__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
Ignacio Vazquez-Abrams
+2  A: 

There is no obvious way to do this as far as I know (at least not without explicitely reassigning __doc__ as Ignacio suggests).

But I think this would be a terrible thing to do. Consider this:

What if I am navigating through your code and reading this docstring on the 300-th line of your file? You really want me to go search for the argument?

ChristopheD
+2  A: 

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
interjay
+1 For the use of decorators, may need some tweeting of the stuff that gets replaced. That should somehow make clear what gets inserted their and were to look for it when browsing the code.
Ivo Wetzel
I like the idea of using decorators. However, if I insert a newline into the new strings, e.g. "'a: a very\ncommon argument'" then it looks like there is an indentation issue when I type help test (The two first lines are indented one block too much). Any idea as to why this may be?
astrofrog
@Morgoth: That's because the original docstring already contains indentation. So when you add the argument you get: `"____Arguments:\n____a very\ncommon argument"`. I suppose you can manually add indentation in your docstring for arg_a, but then it won't work right with functions that are indented differently. A more complete (but complicated) solution is to have the fixdocstring function determine the original indentation and automatically add it in the replacement strings.
interjay