9.2 创建装饰器时保留函数元信息

问题

你写了一个装饰器作用在某个函数上,但是这个函数的重要的元信息比如名字、文档字符串、注解和参数签名都丢失了。

解决方案

任何时候你定义装饰器的时候,都应该使用 functools 库中的 @wraps 装饰器来注解底层包装函数。例如:

  1. import time
  2. from functools import wraps
  3. def timethis(func):
  4. '''
  5. Decorator that reports the execution time.
  6. '''
  7. @wraps(func)
  8. def wrapper(*args, **kwargs):
  9. start = time.time()
  10. result = func(*args, **kwargs)
  11. end = time.time()
  12. print(func.__name__, end-start)
  13. return result
  14. return wrapper

下面我们使用这个被包装后的函数并检查它的元信息:

  1. >>> @timethis
  2. ... def countdown(n):
  3. ... '''
  4. ... Counts down
  5. ... '''
  6. ... while n > 0:
  7. ... n -= 1
  8. ...
  9. >>> countdown(100000)
  10. countdown 0.008917808532714844
  11. >>> countdown.__name__
  12. 'countdown'
  13. >>> countdown.__doc__
  14. '\n\tCounts down\n\t'
  15. >>> countdown.__annotations__
  16. {'n': <class 'int'>}
  17. >>>

讨论

在编写装饰器的时候复制元信息是一个非常重要的部分。如果你忘记了使用 @wraps ,那么你会发现被装饰函数丢失了所有有用的信息。比如如果忽略 @wraps 后的效果是下面这样的:

  1. >>> countdown.__name__
  2. 'wrapper'
  3. >>> countdown.__doc__
  4. >>> countdown.__annotations__
  5. {}
  6. >>>

@wraps 有一个重要特征是它能让你通过属性 wrapped 直接访问被包装函数。例如:

  1. >>> countdown.__wrapped__(100000)
  2. >>>

wrapped 属性还能让被装饰函数正确暴露底层的参数签名信息。例如:

  1. >>> from inspect import signature
  2. >>> print(signature(countdown))
  3. (n:int)
  4. >>>

一个很普遍的问题是怎样让装饰器去直接复制原始函数的参数签名信息,如果想自己手动实现的话需要做大量的工作,最好就简单的使用 @wraps 装饰器。通过底层的 wrapped 属性访问到函数签名信息。更多关于签名的内容可以参考9.16小节。

原文:

http://python3-cookbook.readthedocs.io/zh_CN/latest/c09/p02_preserve_function_metadata_when_write_decorators.html