python中wraps函数用法详情
  TEZNKK3IfmPf 2023年11月13日 23 0

        Python装饰器(decorator)在实现的时候,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变)。

        这样变化后对程序会造成一定的影响,如在flask框架中的一些函数添加自定义的decorator,添加后由于函数名和函数的doc发生了改变,这会对测试造成一定的影响。这是会可以使用functools包提供的wraps方法的decorator来消除这种副作用。写一个decorator的时候,在实现之前加上functools的wrap,它能保留原有函数的名称和docstring。 

        wraps是在装饰器中使用,保留原来函数的属性

functools.wraps

        使用装饰器可以极大的复用了代码,但它也有一个缺点就是原函数的元信息不见了,比如函数的docstring、__name__、参数列表等。

示例代码1:

def logged(func):
    def with_logging(*args, **kwargs):
        print(func.__name__ + 'was called')
        return func(*args, **kwargs)

    return with_logging


@logged
def test():
    """
    does some math
    :param x:
    :return:
    """
    x = 6
    return x ** 2


#  上述函数等价于
def test2():
    """
        does some math
        :param x:
        :return:
        """
    x = 5
    return x ** 2


a = test()
print(a)
b = logged(test2)
print(b())

print("*" * 100)

print(test.__name__)
print(test.__doc__)

print("*" * 100)

print(test2.__name__)
print(test2.__doc__)

运行结果:

python中wraps函数用法详情

        上述代码执行结果中不难看出,函数test被with_logging取代了,当然它的docstring,__name__等信息就变成了with_logging函数的信息了。

        出现上述问题有时候是问题是挺严重的,这时候我们可以使用functools.wraps库,wraps本身也是一个装饰器,它能够把原函数的元信息拷贝到装饰器函数中,这使用装饰器函数也有原函数一样的元信息了。

示例代码2:

from functools import wraps


def logged(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + 'was called')
        return func(*args, **kwargs)

    return with_logging


@logged
def test():
    """
    does some math
    :param x:
    :return:
    """
    x = 6
    return x ** 2


#  上述函数等价于
def test2():
    """
        does some math
        :param x:
        :return:
        """
    x = 5
    return x ** 2


a = test()
print(a)
b = logged(test2)
print(b())

print("*" * 100)

print(test.__name__)
print(test.__doc__)

print("*" * 100)

print(test2.__name__)
print(test2.__doc__)

 运行结果:

python中wraps函数用法详情

示例代码3:

from functools import wraps


def wrapper(func):
    @wraps(func)
    def inner(*args, **kwargs):
        res = func(*args, **kwargs)
        print("func.__name__:", func.__name__)
        print("func.__doc__:", func.__doc__)
        return res

    return inner


@wrapper
def funcs():
    """funcs functions"""
    pass


funcs()
print(funcs)  # <function funcs at 0x0000026852CB4438>

运行结果:

python中wraps函数用法详情

 示例代码4:

def wrapper(func):
    def inner(*args, **kwargs):
        res = func(*args, **kwargs)
        print("func.__name__:", func.__name__)
        print("func.__doc__:", func.__doc__)
        return res

    return inner


@wrapper
def funcs():
    """funcs functions"""
    pass


funcs()
print(funcs)  # <function wrapper.<locals>.inner at 0x0000021E46384438>

运行结果:

python中wraps函数用法详情

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   36   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   27   0   0 python
  TEZNKK3IfmPf   2024年05月31日   35   0   0 excelpython
  TEZNKK3IfmPf   2024年05月31日   28   0   0 python
TEZNKK3IfmPf