Repetitive content in docstrings

牧云@^-^@ 提交于 2020-12-29 13:16:05

问题


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:


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



回答2:


__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



回答3:


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?




回答4:


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.



来源:https://stackoverflow.com/questions/2575959/repetitive-content-in-docstrings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!