Python方式,使用其他参数包装函数并更改输出

问题描述 投票:1回答:1

我正在使用来自外部库的函数(例如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的文档字符串。

有没有一种方法可以编写此函数,使用户可以同时了解wrapperinner_function(并可以使用自动补全等功能)

谢谢

python wrapper args kwargs functools
1个回答
0
投票

使用@deceze的想法,我构建了一个装饰器来格式化包装函数的指令:

def merge_docstrings(other):
    def decorator(func):
        func.__doc__.format(other.__doc__)
        return func
    return decorator

它确实使用wrapper之一格式化inner_function格式但是,例如在PyCharm中显示文档字符串时,它不能很好地工作,很显然,您不会使用inner_function的参数来自动完成。我不确定自动完成的工作方式,以及是否有可能实现我想要的目标。

© www.soinside.com 2019 - 2024. All rights reserved.