Misunderstandings about the execution sequence of the Python decorator

Source: Internet
Author: User
Exploring how to execute the sequential decorator with multiple decorator is a Python tool for encapsulating functions or code. you can find many articles on the Internet to learn, here I will discuss a myth about the execution sequence of multiple decorator. In most cases, the calling sequence of functions involving decoration of multiple decorators will be described.

The decorator is a Python tool used to encapsulate functions or code. you can find many articles on the Internet to learn. here I will discuss the misunderstandings about the execution sequence of multiple decorator.

Question

The call sequence of most functions involving decoration of multiple decorers indicates that they are top-down, for example, the following example:

def decorator_a(func):    print 'Get in decorator_a'    def inner_a(*args, **kwargs):        print 'Get in inner_a'        return func(*args, **kwargs)    return inner_adef decorator_b(func):    print 'Get in decorator_b'    def inner_b(*args, **kwargs):        print 'Get in inner_b'        return func(*args, **kwargs)    return inner_b@decorator_b@decorator_adef f(x):    print 'Get in f'    return x * 2f(1)

The code above first defines two functions: decotator_a and decotator_ B. the two functions implement the function of receiving a function as a parameter and then returning the created function, call the received function in the created function (text is better than code ). The final defined function f uses the decotator_a and decotator_ B defined above as the decoration function. After we call the decorated function f with 1 as the parameter, what is the order of decotator_a and decotator_ B (here, to indicate the order of function execution, use the print output method to view the execution sequence of the function )?

If, without thinking about the bottom-up principle, execute decorator_a and then decorator_ B, then Get in decotator_a, Get in inner_a, and then output Get in decotator_ B, Get in inner_ B. However, this is not the case.

The actual running result is as follows:

Get in decorator_aGet in decorator_bGet in inner_bGet in inner_aGet in f
Differences between a function and a function call

Why is inner_ B first and then inner_a? To thoroughly understand the problem above, we must first distinguish between two concepts: Functions and function calls. In the above example, f is called a function, and f (1) is called a function call. The latter is the result of evaluating the input parameters of the former. In Python, a function is also an object, so f refers to a function object. its value is the function itself, and f (1) is the call to the function, its value is the result of the call. Here we define the value of f (1) 2. Similarly, taking the decorator_a function above, it returns a function object inner_a, which is defined internally. The function func is called in inner_a and the call result of func is returned as a value.

The decorator function is executed immediately after being defined by the decorator function.

The second question to be clarified is what happened when the decorator decorated a function. Now let's simplify our example, assuming the following:

def decorator_a(func):    print 'Get in decorator_a'    def inner_a(*args, **kwargs):        print 'Get in inner_a'        return func(*args, **kwargs)    return inner_a@decorator_adef f(x):    print 'Get in f'    return x * 2

As mentioned in many articles about decorator:

@ Decorator_adef f (x): print 'get in f' return x * 2 # equivalent to def f (x): print 'get in f' return x * 2f = decorator_a (f)

Therefore, when the interpreter executes this code, decorator_a has already called and uses function f as a parameter to return a function generated internally, therefore, f then refers to inner_a returned by decorater_a. Therefore, when f is called in the future, it is actually equivalent to calling inner_a. the parameter passed to f is passed to inner_a. when inner_a is called, the received parameter is passed to func in inner_a, that is, f, the final returned value is the value of f call, so it looks like calling f directly on the outermost side.

Explanation of questions

When we clarify the above two concepts, we can clearly see what happened in the original example.
When the interpreter executes the following code, decorator_a and decorator_ B are called sequentially in the descending order. this will output the corresponding Get in decorator_a and Get in decorator_ B. At this time, f is equivalent to inner_ B in decorator_ B. However, because f is not called, inner_ B is not called, and inner_a in inner_ B is not called, so Get in inner_a and Get in inner_ B will not be output.

@decorator_b@decorator_adef f(x):    print 'Get in f'    return x * 2

Then the last line is called when we call the f input parameter 1, inner_ B is called, it prints Get in inner_ B first, then inner_a is called inside inner_ B, so Get in inner_a is printed, and then the original f called inside inner_a is returned as the final result. At this time, you should know why the output result is like that, and have some knowledge about the actual execution sequence of the decorator.

When we remove the call from the last line of f in the above example and put it in repl for demonstration, we can naturally see the order problem:

➜  test git:(master) ✗ pythonPython 2.7.11 (default, Jan 22 2016, 08:29:18)[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> import test13Get in decorator_aGet in decorator_b>>> test13.f(1)Get in inner_bGet in inner_aGet in f2>>> test13.f(2)Get in inner_bGet in inner_aGet in f4>>>

In actual application scenarios, when we use the above method to write two decoration methods, such as first verifying whether there is a login @ login_required, and then verifying that the permissions are insufficient @ permision_allowed, we use the following sequence to describe the function:

@login_required@permision_alloweddef f()  # Do something  return

For more Python decorator execution sequence misunderstandings, refer to PHP Chinese network!

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.