如何覆盖python函数上的默认帮助消息

时间:2013-11-13 19:55:34

标签: python function built-in

我有一个包含许多参数和详细帮助信息的函数,例如:

def worker_function(arg1, arg2, arg3):
    """ desired help message:
    arg1 - blah
    arg2 - foo
    arg3 - bar
    """
    print arg1, arg2, arg3

我还有一个包装函数,它执行一些会计,然后调用我的worker_function,将所有参数传递给它,就像一样。

def wrapper_function(**args):
    """ this function calls worker_function """
    ### do something here ...
    worker_function(**args)

我希望包装函数的帮助消息(由python内置的help()函数显示)具有来自worker函数的参数列表帮助消息。

我能得到的最接近的解决方案是:

wrapper_function.__doc__ += "\n\n" + worker_function.__doc__

这导致:

>>? help(wrapper_function)
Help on function wrapper_function in module __main__:

wrapper_function(**args)
    this function calls worker function

    desired help message:
       arg1 - blah
       arg2 - foo
       arg3 - bar

但是这个描述缺少必要部分 - 参数列表,即:

worker_function(arg1, arg2, arg3)

(在现实生活中,参数列表很长,告诉默认值,我希望自动显示)。

有没有办法在wrapper_function的帮助消息中添加参数列表或worker_function?

2 个答案:

答案 0 :(得分:6)

help()在内部使用inspect模块查找函数数据。除非你默认覆盖函数元数据(如果可能的话),我认为你不能摆脱包装函数的定义。

然而,您可以使用包装函数的信息填充包装函数的帮助文本。您可以自己使用inspect模块(尤其是getfullargspec方法),也可以使用pydoc模块(help内部使用的模块)来生成它对你而言。

import pydoc
def wrappedHelpText (wrappedFunc):
    def decorator (f):
         f.__doc__ = 'This method wraps the following method:\n\n' + pydoc.text.document(wrappedFunc)
         return f
    return decorator

@wrappedHelpText(worker_function)
def wrapper_function(**args):
    worker_function(**args)

在其上调用help将生成更有用的输出,包括原始签名。

>>> help(wrapper_function)
Help on function wrapper_function in module __main__:

wrapper_function(**args)
    This method wraps the following method:

    worker_function(arg1, arg2, arg3)
        desired help message:
        arg1 - blah
        arg2 - foo
        arg3 - bar

答案 1 :(得分:2)

要保留argspec,您可以使用decorator模块。或者模仿its implementation

相关问题