Just enjoy programming

python functools wraps (转)

When you use a decorator, you're replacing one function with another. In other words, if you have a decorator

  1. def logged(func):  
  2.     def with_logging(*args, **kwargs):  
  3.         print func.__name__ + " was called"  
  4.         return func(*args, **kwargs)  
  5.     return with_logging  

then when you say

  1. @logged  
  2. def f(x):  
  3.    """does some math"""  
  4.    return x + x * x  

it's exactly the same as saying

  1. def f(x):  
  2.     """does some math"""  
  3.     return x + x * x  
  4. f = logged(f)  

and your function f is replaced with the function with_logging. Unfortunately, this means that if you then say

  1. print f.__name__  

it will print with_logging because that's the name of your new function. In fact, if you look at the docstring for f, it will be blank because with_logging has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument x; instead it'll be listed as taking *args and **kwargs because that's what with_logging takes.

If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have functools.wraps. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since wraps is itself a decorator, the following code does the correct thing:

  1. from functools import wraps  
  2. def logged(func):  
  3.     @wraps(func)  
  4.     def with_logging(*args, **kwargs):  
  5.         print func.__name__ + " was called"  
  6.         return func(*args, **kwargs)  
  7.     return with_logging  
  8.  
  9. @logged  
  10. def f(x):  
  11.    """does some math"""  
  12.    return x + x * x  
  13.   
  14. print f.__name__  # prints 'f'  
  15. print f.__doc__   # prints 'does some math'  


    转自http://blog.csdn.net/wanghai__/article/details/7078792

posted on 2013-11-05 20:40 周强 阅读(350) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理