Python 3 Decorator Detailed

Source: Internet
Author: User

------------ Decorator -----------------------------------------------------

What is an adorner?

adorners are a way of specifying management code for functions and classes. The adorner itself is the form of a callable object (such as a function) that handles other callable objects. As we have seen earlier in this book, the Python adorner is presented in two related ways:

    • function Decorators perform name re-binding at function definition, providing a logical layer to manage functions and methods, or to invoke them later.

    • The class decorator makes name rebinding at the time of class definition, provides a logical layer to manage classes, or manages the instances that are subsequently invoked to say that they were created.

In short, adorners provide a way to insert Autorun code at the end of a function and class definition statement-for a function adorner, at the end of a Def, and for a class decorator, at the end of classes. This code can play a different role, as described in the following subsections.

Managing calls and instances

For example, in a common usage, this Autorun code might be used to enhance calls to functions and classes by installing Wrapper objects for subsequent calls:

    • The function adorner installs the wrapper object to intercept subsequent function calls and process them when needed.

    • The class adorner installs wrapper objects to intercept subsequent instance creation calls and process them when needed.

adorners achieve these effects by automatically binding functions and class names to other callable objects, at the end of the DEF and classes statements. When subsequently invoked, these callable objects can be themselves such tasks as tracking and timing function calls, managing access to class instance properties, and so on.

Management functions and classes

Although most instances of this article use wrappers to intercept subsequent calls to functions and classes, this is not the only way to use adorners:

    • function Decorators can also be used to manage function objects instead of subsequent calls to them-for example, registering a function with an API. However, here we focus primarily on the more common use of invoking wrapper applications.

    • class Decorators can also be used to directly manage class objects, rather than instance creation calls-for example. Extend the class in a new way. Because these usages are very much coincident with the Meta class (in fact, they are all run at the end of the class creation process), we will see more examples later.

In other words, function decorators can be used to manage function calls and function objects, and class decorators can be used to manage class instances and classes themselves. By returning the decorated object itself instead of a wrapper, the adorner becomes a simple post-creation step for functions and classes.

Regardless of the role played, adorners provide a convenient and clear way to write tools that are useful in both the program development phase and the real-world product system.

Using and defining adorners

Depending on your work style, you may become a user or provider of adorners. As we can see, Python itself has a built-in adorner with a specific role ... static method adorners, property decorators, and more. In addition, many popular Python tools include adorners that perform tasks such as managing databases or user interface logic. In such cases, we do not need to know how the adorner can be coded to complete the task.

For more general tasks, programmers can write their own arbitrary adorners. For example, a function decorator might extend a function by adding trace calls, executing parameter validation tests at debug time, automatically fetching and releasing the lock, counting the number of calls to the function for optimization, and so on. You can imagine any behavior that you add to a function call as an alternative to a custom function adorner.

On the other hand, the function decorator is designed to only enhance a particular function or method invocation , rather than a complete object interface . class decorators better serve as the latter role-because they can intercept instance creation calls, which can be used to implement arbitrary object interface extensions or administrative tasks. For example, a custom class decorator can track or validate each property reference to an object. They can also be used to implement proxy objects, monomer classes, and other common patterns of becoming. In fact, we'll find that many of the class decorators have a lot in common with the delegate programming pattern we saw earlier.

Why use adorners

Like the vicious European advanced Python tools, from a purely technical point of view, it is not strictly required adorners: Their functionality can often be implemented using simple helper function calls or other techniques (and triggering from a basic level, we can always manually write the adorner says auto-execute name rebinding).

In other words, adorners provide an explicit way for such tasks to be explicit, to minimize the redundancy of extension code, and to help ensure the correct API usage:

    • Adorners have a very clear syntax, which makes them easier to find than those that can be arbitrarily removed from the principal function or class of auxiliary function calls.

    • When a principal function or class is defined, the adorner is applied once, and no additional code (which may have to be changed in the future) is added to each invocation of the class or function.

    • Because of the previous two points, adorners make it less likely for an API user to forget to extend a function or class based on API requirements.

In other words, in addition to its technical model, adorners provide some of the benefits associated with code maintainability and aesthetics. In addition, as a structured tool, adorners naturally facilitate the encapsulation of code, which reduces redundancy and makes the future easier.

Adorners do have some potential drawbacks ... When they insert the logic of the wrapper class, they can modify the type of the adorned object, and they may throw additional calls. On the other hand, the same considerations apply to any technology that is the object wrapper logic.

We will explain these tradeoffs in the real code that follows in this article. While it is still somewhat subjective to choose to use adorners, their advantages are compelling enough to make them fast to be the best time in the Python world. To help you make a decision, let's look at some details.

Basic knowledge

Let's first look at the decorative behavior from the point of view of a symbol. We will soon be writing real code, but it is important to understand this mapping first, since many of the magic of adorners can be attributed to automatic rebinding operations.

function Adorner

The function adorner has been available since Python 2.5. As we heard earlier in this book, they are primarily a syntactic sugar: by running another function at the end of a function's Def statement, the original function name is re-bound to the new result.


A function adorner is a run-time declaration of a red Origin function, which is defined by a function that requires compliance with this declaration. The adorner is written next to the DEF statement that defines a function or method, and it consists of the @ symbol and a reference to the meta function immediately following it ... This is a function (or other callable object) that is customary for another function.

In terms of coding, the function decorator automatically adds the following syntax

@decoratordef F (ARG): ... F (99)

Mapped to this equivalent form, where the adorner is a single-parameter callable object that returns a callable object with the same number of arguments as F:

This article from "Professor elder brother" blog, declined reprint!

Python 3 Decorator Detailed

Related Article

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: 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.