Python's Decorator

Source: Internet
Author: User

Because a function is also an object, and a function object can be assigned to a variable, the function can also be called through a variable.

A function object has a __name__ property that can get the name of the function:

Now, suppose we want to enhance now() the function of functions, for example, to automatically print the log before and after a function call, but do not want to modify the definition of the now() function, this way of dynamically adding functionality during the run of the code, called "Adorner" (Decorator).

Essentially, decorator is a higher-order function that returns a function. So, we want to define a decorator that can print the log, which can be defined as follows:

def log (func):     def Wrapper (*args, * *kw)        :print('call%s ():' % func.  __name__)        return func (*args, * *kw    )return Wrapper

Observe the above log , because it is a decorator, so accept a function as an argument and return a function. We will use the Python @ syntax to place the decorator at the definition of the function:

@log def Now ():     Print ('2015-3-25')

Calling now() a function will not only run the now() function itself, but will also now() print a line of logs before running the function:

Put @log to now() the definition of the function, the equivalent of executing a statement:

now = log (now)

Since log() it is a decorator that returns a function, the original now() function still exists, but now the variable with the same name points to the new function, and the now call executes the now() new function, which is the log() function returned in the function wrapper() .

wrapper()The function's parameter definition is (*args, **kw) , therefore, the wrapper() function can accept calls of arbitrary arguments. wrapper()inside the function, the log is printed first and then the original function is called.

If the decorator itself needs to pass in parameters, it is necessary to write a higher-order function that returns decorator, which is more complex to write. For example, to customize the text of a log:

def log (text):     def Decorator (func):         def Wrapper (*args, * *kw)            :print('%s%s ():' % (text, Func. __name__                ) returnfunc (*args, * * kw) return wrapper              return Decorator

This 3-level nested decorator usage is as follows:

@log ('execute')def now ():    print(' 2015-3-25 ')

The results of the implementation are as follows:

Compared to the two-layer nested decorator, the 3-layer nesting effect is this:

Let's parse the above statement, execute it first, log(‘execute‘) return the decorator function, call back the function, the argument is the now function, the return value is the wrapper function.

There is no problem with the definitions of the two decorator, but the last step is not the case. Because we're talking about functions and objects, and it has __name__ properties like that, but you see the functions after the decorator decoration, and they __name__ have changed from the original ‘now‘ ‘wrapper‘ :

Because the name of the function returned is the same, wrapper() ‘wrapper‘ so you need to copy the properties of the original function __name__ into the wrapper() function, otherwise, some code that relies on the function signature will be executed with an error.

There is no need to write wrapper.__name__ = func.__name__ such code, Python functools.wraps is built to do this, so a complete decorator is written as follows:

Import Functools def log (func):    @functools. Wraps (func)    def Wrapper (*args, * *kw)        :Print ('call%s ():' % func.  __name__)        return func (*args, * *kw    )return Wrapper

or for decorator with parameters:

 import   functools  def   log (text):  def   Decorator (func): @functools. Wraps (func)  def Wrapper (*args, **kw):  print  ( " %s%s ():  " % ( Text, Func. __name__   return  func (*args, **kw)  return   wrapper  return  decorator 

Import Functools is the importing functools module. The concept of the module is explained later. Now, just remember to add it to the wrapper() front of the definition @functools.wraps(func) .

Python's 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.