python functools wraps

把被封装函数的namemoduledocdict复制到封装函数中,这样在未来排错或者函数自省的进修能够获得正确的源函数的对应属性,所以使用wraps。

In [1]: import functools

# 不加wraps
In [2]: def deco(f):
   ...:     def wrapper(*args, **kwargs):
   ...:         return f(*args, **kwargs)
   ...:     return wrapper
   ...:

In [3]: @deco
   ...: def func():
   ...:     return 1
   ...:

In [4]: func.__name__
Out[4]: 'wrapper'

# 加wraps
In [5]: def deco2(f):
   ...:     @functools.wraps(f)
   ...:     def wrapper(*args, **kwargs):
   ...:         return f(*args, **kwargs)
   ...:     return wrapper
   ...:

In [6]: @deco2
   ...: def func():
   ...:     return 1
   ...:

In [7]: func.__name__
Out[7]: 'func'

Ref: 1.python web开发实战