Part 2: decorator

Source: Internet
Author: User

As mentioned before, the internal function of the decorator has replaced the original function (new function), so this function will missing many attributes.

 1 def is_admin(f): 2     def wrapper(*args, **kwargs): 3         if kwargs.get(‘usrename‘) != ‘admin‘: 4             raise Exception("Now allow") 5         return f(*args, **kwargs) 6     return wrapper 7  8 def foobar(username="soneone"): 9     """ DOcarzy stuff """10     pass11 12 13 >>> foobar.func_doc14 ‘ DOcarzy stuff ‘15 >>> foobar.__name__16 ‘foobar‘17 >>> @is_admin18 def foobar(username="someone"):19     """Do carzy stuff"""20     pass21 22 >>> foobar.__doc__23 >>> foobar.__name__24 ‘wrapper‘25 >>> 

 

We can use functools to solve this problem.

 1 import functools  2 def is_admin(f): 3     @functools.wraps(f) 4     def wrapper(*args, **kwargs): 5         if kwargs.get(‘usrename‘) != ‘admin‘: 6             raise Exception("Now allow") 7         return f(*args, **kwargs) 8     return wrapper 9 10 def foobar(username="soneone"):11     """ DOcarzy stuff """12     pass13 14 15 >>> foobar.__name__16 ‘foobar‘17 >>> foobar.__doc__18 ‘ DOcarzy stuff ‘19 >>> 

 

In our example, we always input the username keyword as a parameter to the decorator function to build a better solution.

UseInspect

 1 import functools 2 import inspect 3  4 def is_admin(f): 5     @functools.wraps(f) 6     def wrapper(*args, **kwargs): 7  8         func_args = inspect.getcallargs(f,*args,**kwargs) 9         print func_args10         if func_args.get(‘username‘) != ‘admin‘:11             raise Exception("Now allow")12         return f(*args, **kwargs)13     return wrapper14 15 @is_admin16 def foobar(username, type="chocolate"):17     """ DOcarzy stuff """18     pass19 20 >>> foobar(username=‘admin‘)21 {‘username‘: ‘admin‘, ‘type‘: ‘chocolate‘}22 >>> 

 

Part 2: decorator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.