5

处理文档字符串中重复内容的好方法是什么?我有许多采用“标准”参数的函数,这些参数必须在文档字符串中进行解释,但最好只编写一次文档字符串的相关部分,因为这样更容易维护和更新。我天真地尝试了以下方法:

arg_a = "a: a very common argument"

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

但这不起作用,因为当我这样做时,我help(test)看不到文档字符串。有没有好的方法来做到这一点?

4

4 回答 4

6

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
于 2010-04-04T21:41:21.717 回答
4

__doc__可在大多数用户定义的类型上赋值:

arg_a = "a: a very common argument"

def test(a):
    pass

test.__doc__ = '''
    Arguments:
    %s
    ''' % arg_a
于 2010-04-04T21:35:29.090 回答
2

据我所知,没有明显的方法可以做到这一点(至少没有__doc__像 Ignacio 建议的那样明确地重新分配)。

但我认为这将是一件可怕的事情。考虑一下:

如果我正在浏览您的代码并在文件的第 300 行阅读此文档字符串怎么办?你真的要我去寻找论据吗?

于 2010-04-04T21:36:49.047 回答
0

据可查的 docrep包可能是您正在寻找的。

它基于装饰器,就像interjay 建议的那样,但智能地在您的代码中很好地记录重用文档字符串的依赖关系。这解决了ChritopheD 提出的问题,即在挖掘代码时,实际查看您的实现的人必须搜索参数的实际定义。

于 2020-12-26T21:33:34.500 回答