在python中使用装饰器(decorator)会使得被装饰函数的名称和帮助文档发生错乱,如下所示:
>>> def decorator(f):
... def wrapper(*args, **kwargs):
... """wrapper Docstring"""
... print('Calling decorated function')
... return f(*args, **kwargs)
... return wrapper
...
>>> @decorator
... def example():
... """example Docstring"""
... print('Called example function')
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'wrapper'
>>> example.__doc__
'wrapper Docstring'
从上例中可以看出,在使用装饰器后,函数example的name和doc都变成了wrapper的name和doc,名称和帮助文档发生了错乱。
在decorator中使用functools中的wraps可以很好的解决这个问题,上例改为:
>>> from functools import wraps
>>> def decorator(f):
... @wraps(f)
... def wrapper(*args, **kwargs):
... """wrapper Docstring"""
... print('Calling decorated function')
... return f(*args, **kwargs)
... return wrapper
...
>>> @decorator
... def example():
... """example Docstring"""
... print('Called example function')
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'example Docstring'
使用wraps之后,被装饰函数example的名称和帮助文档得以正确体现。