首页 > 代码库 > functools.wraps

functools.wraps

我们在使用 Decorator 的过程中,难免会损失一些原本的功能信息。直接拿 stackoverflow 里面的栗子

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def logged(func):
    def with_logging(*args, **kwargs):
        print func.__name__ + " was called"
        return func(*args, **kwargs)
    return with_logging
 
@logged
def f(x):
   """does some math"""
   return x + x * x
 
def f(x):
    """does some math"""
    return x + x * x
f = logged(f)
 
In [24]: f.__name__
Out[24]: with_logging

而functools.wraps 则可以将原函数对象的指定属性复制给包装函数对象, 默认有 __module____name____doc__,或者通过参数选择。代码如下:

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 f(x):
   """does some math"""
   return x + x * x
 
print f.__name__  # prints ‘f‘

functools.wraps