我正在使用外部库中的函数(例如scipy.optimize.minimize),为了方便起见,我将它们包装起来以对参数进行预处理和后处理。我知道 functools 中的 wraps 装饰器,但我找不到正确使用它的方法。
这是我所做的基本示例:
def wrapper(outer_arg, **inner_arguments):
inner_arg = prepare_inputs(outer_arg)
inner_output = inner_function(inner_arg, **inner_arguments)
outer_output = prepare_outputs(inner_output)
return outer_output
这样做的问题是,在调用 help 时,我从 inner_function 中丢失了文档字符串,并且我不想复制包装器声明中的所有参数。 我尝试添加 wraps 装饰器,如下所示:
@wraps(inner_function)
def wrapper(outer_arg, **inner_arguments):
inner_arg = prepare_inputs(outer_arg)
inner_output = inner_function(inner_arg, **inner_arguments)
outer_output = prepare_outputs(inner_output)
return outer_output
但是当调用 help 时,我丢失了 wrapper 的文档字符串。
有没有一种方法可以编写这个函数,让用户了解包装器和内部函数(并且能够使用自动完成等功能) ..) ?
最佳答案
使用@deceze idea我构建了一个装饰器来格式化包装函数的文档:
def merge_docstrings(other):
def decorator(func):
func.__doc__ = f'{func.__doc__}'.format(other.__doc__)
return func
return decorator
它确实使用 inner_function
之一格式化 wrapper
文档字符串
但它在 PyCharm 中显示文档字符串时效果不佳,显然您无法使用 inner_function
的参数进行自动补全。我不确定自动完成是如何工作的以及是否有可能实现我想要的。
关于使用附加参数包装函数并更改输出的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58768487/