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

StackOverflow https://stackoverflow.com/questions/14148210

  •  12-01-2022
  •  | 
  •  

質問

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. 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). 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帰属
所属していません StackOverflow
scroll top