Python装饰器保持函数元数据

Python装饰器保持函数元数据

Question #

Python中装饰后的函数的元数据与原函数没有关联,如果要让装饰后的函数与原函数有着一致的元数据,应如何操作?

Answer #

内置的装饰器@functools.wrap,它会帮助保留原函数的元信息(也就是将原函数的元信息,拷贝到对应的装饰器函数里)。

import functools
def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('wrapper of decorator')
        func(*args, **kwargs)
    return wrapper

@my_decorator
def greet(message):
    print(message)
greet.__name__
# 输出
'greet'

类装饰器 #

From #

17 | 强大的装饰器