复制签名,转发包装函数中的所有参数

Nic*_*mer 1 python function signature

我在一个类中有两个函数,plot()show().show()作为便捷的方法,没有别的,而不是两行添加到的代码plot()一样

def plot(
        self,
        show_this=True,
        show_that=True,
        color='k',
        boundary_color=None,
        other_color=[0.8, 0.8, 0.8],
        show_axes=True
        ):
    # lots of code
    return

def show(
        self,
        show_this=True,
        show_that=True,
        color='k',
        boundary_color=None,
        other_color=[0.8, 0.8, 0.8],
        show_axes=True
        ):
    from matplotlib import pyplot as plt
    self.plot(
        show_this=show_this,
        show_that=show_that,
        color=color,
        boundary_color=boundary_color,
        other_color=other_color,
        show_axes=show_axes
        )
    plt.show()
    return
Run Code Online (Sandbox Code Playgroud)

这一切都有效.

我的问题是,这似乎这样的代码太多show()的包装.我真正想要的是:让我们show()拥有相同的签名和默认参数plot(),并将所有参数转发给它.

任何提示?

Ser*_*sta 7

Python 3提供了使用inspect模块实际复制包装函数签名的功能:

def show(self, *args, **kwargs):
    from matplotlib import pyplot as plt
    self.plot(*args, **kwargs)
    plt.show()
show.__signature__ = inspect.signature(plot)
Run Code Online (Sandbox Code Playgroud)

现在,如果您在提供IDLE等自动完成功能的shell中使用show,您将看到正确的参数show而不是密码*args, **kwargs


Der*_*Weh 6

扩展Serge的答案,我提出以下建议:

from inspect import signature

# create a decorator to copy signatures
def copy_signature(source_fct): 
    def copy(target_fct): 
        target_fct.__signature__ = signature(source_fct) 
        return target_fct 
    return copy 

# create a short test function as example
def test(a, /, b, c=2, *, d, e): 
    print(a, b, c, d, e)

# now wrap it
@copy_signature(test)
def forwards(*args, **kwds):
    # assert that arguments are correct
    signature(forwards).bind(*args, **kwds) 
    # now do potentially complicated and obscuring tasks
    print('Just wrapping') 
    test(*args, **kwds)
Run Code Online (Sandbox Code Playgroud)

调用signature(forwards).bind(*args, **kwds)可确保使用正确的参数调用该函数。如果您有复杂的函数,在调用函数之前检查参数可以使错误更清晰。

我故意没有将支票包含在装饰器中。否则我们将需要另一个函数调用,这使得调试更加复杂。


Ara*_*Fey 3

您可以使用参数打包/解包:

def show(self, *args, **kwargs):
    from matplotlib import pyplot as plt
    self.plot(*args, **kwargs)
    plt.show()
Run Code Online (Sandbox Code Playgroud)