简体   繁体   English

如何使函数docstring根据python中的另一个函数自动更新?

[英]how to make function docstring automatically updated according to another function in python?

Suppose I have some functions (say B1,B2,B3,etc...) which call the same function A, I want to put in docstrings of B1,B2,B3 some texts explaining parameter that are used by function A, and these are already explained in the docstring of function A. But I don't want to copy A's docstring to B1, then B2, then B3, and later if I change the docstring of function A, then I have to change B1,B2,B3... again, so I wonder if there is some way I can link part of the docstring of B1 to that of A, so that when the docstring of A is updated, the corresponding part of B1 will be updated as well. 假设我有一些调用相同函数A的函数(比如B1,B2,B3等...),我想在函数A中使用一些解释参数的文本来放入B1,B2,B3的文档字符串,这些已经在函数A的文档字符串中解释了。但是我不想将A的文档字符串复制到B1,然后是B2,然后是B3,稍后如果我更改函数A的文档字符串,那么我必须更改B1,B2,B3 ...再次,所以我想知道是否有某种方法可以将B1的文档字符串的一部分链接到A的文档字符串,这样当更新A的文档字符串时,B1的相应部分也会更新。 By this way, the users can directly refer to docstring of function B1 for help information without bothering to check the docstring of A. (Actually A's parameters are all kwargs). 通过这种方式,用户可以直接引用函数B1的docstring获取帮助信息,而无需检查A的文档字符串。(实际上A的参数都是kwargs)。 A simple example might be like below: 一个简单的例子可能如下:

def A():
    '''
    I am doctring for function A
    '''
    pass

def B1():
    '''
    I am doctring for function B1,

    followed by the same docstring as function A, which is:

    ** I would like someway I can put the docstring of A here**
    '''
    pass

thanks for any help or referring me to some other link, I tried googling it but no targeted information is found. 感谢任何帮助或引用我的其他链接,我尝试谷歌搜索但没有找到有针对性的信息。

You could write a decorator to do this: 你可以写一个装饰器来做到这一点:

def append_doc_of(fun):
    def decorator(f):
        f.__doc__ += fun.__doc__
        return f

    return decorator


def A():
    '''
    I am doctring for function A
    '''
    pass


@append_doc_of(A)
def B1():
    '''
    I am doctring for function B1,

    followed by the same docstring as function A, which is:

    '''
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM