开发者

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 wri开发者_高级运维te 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?


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


__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


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?


The well documented docrep package might be what you are looking for.

It is based on decorators, just like interjay suggested, but intelligently documents the dependencies of reused docstrings nicely in your code. This addresses the issue raised by ChritopheD that somebody actually looking at your implementation would have to search for the actual definition of your arguments when digging through your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜