Python decorator definition and application example explanation

Source: Internet
Author: User
Tags wrapper python decorator
In the following article, let's look at what a python decorator is. Learn about Python adorners and how Python adorners are used. Well, don't say much nonsense, let's get into the next article.

Python decorator

In short, the Python adorner is a function that extends the function of the original function, which is special because its return value is also a function, the advantage of using the Python adorner is to add new functionality to the function without changing the code of the original function.

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.

>>> def now (): ...     Print (' 2015-3-25 ') ...>>> F = now>>> f () 2015-3-25

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

>>> now.__name__ ' Now ' >>> f.__name__ ' now '

Now, let's say we're going to enhance the function of the present () function, for example, to automatically print the log before and after a function call, but you don't want to modify the definition of the now () function, which is called an "adorner" (Decorator) in a way that dynamically adds functionality during code execution.

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

Look at the log above because it is a decorator, so take 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:

@logdef now ():    print (' 2015-3-25 ')

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

>>> now () Call Now (): 2015-3-25

Placing the @log at the definition of the now () function is equivalent to executing the statement:

now = log (now)

Since log () is a decorator that returns a function, the original now () function is still present, except that today's variable with the same name is pointing to the new function, and then calling right will execute the new function, the wrapper () function returned in the log () function.

The parameter definition of the wrapper () function is (*args, **kw), so the wrapper () function can accept calls of arbitrary arguments. Within the wrapper () 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__)) Return                    func (*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:

>>> now () Execute now (): 2015-3-25

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

>>> now = log (' Execute ') (now)

Let's parse the above statement, first execute log (' Execute '), return the Decorator function, and then call the returned function, the parameter is now function, the return value is finally the wrapper function.

There is no problem with the definitions of the two decorator, but the last step is not the case. Because we are talking about functions and objects, which have __name__ properties, but you go to see the functions after the decorator decoration, their __name__ has changed from the original ' now ' to ' wrapper ':

>>> now.__name__ ' wrapper '

Because the name of the wrapper () function returned is ' wrapper ', it is necessary to copy attributes such as the __name__ of the original function into the wrapper () function, otherwise some code that relies on the function signature will be executed in error.

No need to write code like wrapper.__name__ = func.__name__, Python's built-in Functools.wraps is doing 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 functoolsdef 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

The

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

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.