首页  >  文章  >  后端开发  >  如何在Python中保留修饰函数的签名?

如何在Python中保留修饰函数的签名?

Patricia Arquette
Patricia Arquette原创
2024-10-17 17:02:02574浏览

How to Preserve the Signature of Decorated Functions in Python?

保留装饰函数的签名

装饰器是 Python 中用于扩展现有函数行为的强大工具。然而,当应用于函数时,所得的修饰函数通常会丢失其原始文档和签名。这可能会出现问题,尤其是在使用执行日志记录或参数转换等常见任务的通用装饰器时。

常见解决方法

一些常见解决方法包括:

  • 在装饰函数的文档字符串中包含签名。
  • 为每个特定签名创建专门的装饰器。

使用装饰器模块

一个更健壮的解决方案是使用装饰器模块,它提供了一个名为@decorator.decorator的装饰器函数。通过将此装饰器应用到您自己的装饰器函数中,您可以保留原始函数的签名。

<code class="python">import decorator

@decorator.decorator
def args_as_ints(f, *args, **kwargs):
    args = [int(x) for x in args]
    kwargs = dict((k, int(v)) for k, v in kwargs.items())
    return f(*args, **kwargs)

@args_as_ints
def funny_function(x, y, z=3):
    """Computes x*y + 2*z"""
    return x*y + 2*z

print(funny_function("3", 4.0, z="5"))  # 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
#     Computes x*y + 2*z</code>

Python 3.4

在 Python 3.4 及更高版本中, functools.wraps() 函数可用于保留签名。

<code class="python">import functools

def args_as_ints(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args = [int(x) for x in args]
        kwargs = dict((k, int(v)) for k, v in kwargs.items())
        return func(*args, **kwargs)
    return wrapper

@args_as_ints
def funny_function(x, y, z=3):
    """Computes x*y + 2*z"""
    return x*y + 2*z

print(funny_function("3", 4.0, z="5"))  # 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
#     Computes x*y + 2*z</code>

以上是如何在Python中保留修饰函数的签名?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn