Python decorator Explained

Source: Internet
Author: User
Tags scream python decorator

Transferred from: http://www.cnblogs.com/rollenholt/archive/2012/05/02/2479833.html

The article is first caused by a problem above StackOverflow, if the following code is used:

@makebold @makeitalicdef Say ():   return "Hello"

Print out the following output:

<b><i>Hello<i></b>

What would you do? The final answer is:

def makebold (FN):    def wrapped ():        return "<b>" + fn () + "</b>"    return wrapped def makeitalic (FN):    def wrapped ():        return "<i>" + fn () + "</i>"    return wrapped @makebold @makeitalicdef hello (): return    "Hello World" Print Hello () # # returns <b><i>hello world</i></b>

Now let's look at how to understand Python's adorners from some of the most basic ways. The English discussion is here.

The adorner is a well-known design pattern, which is often used in scenes where there is a demand for facets, with the classic insert log, performance test, transaction processing, and so on. Decorators are a great design for solving such problems, and with adorners, we can pull out a lot of the same code that is not relevant to the function itself and continue to reuse it. In summary, the function of an adorner is to add additional functionality to an already existing object.

1.1. How is the demand coming?

The definition of adorners is very abstract, let's look at a small example.

def foo ():    print ' in foo () ' foo ()

This is a very boring function, yes. But suddenly there is a more boring person, we call him B-June, said I want to see how long it takes to execute this function, OK, then we can do this:

Import timedef foo ():    start = Time.clock ()    print ' in foo () '    end = Time.clock ()    print ' used: ', End-start Foo ()

Very well, the features look impeccable. But the egg-ache B-June suddenly don't want to see this function, he to another called Foo2 's function produced a more intense interest.

What do we do? If the above new additions to the code to copy into the Foo2, which made a big taboo ~ Copy what is not the most annoying it! And what if B-June continues to look at the other functions?

1.2. Status quo, is change also

Remember, the function is a one-time citizen in Python, so we can consider redefining a function Timeit, passing the Foo reference to him, then calling Foo in Timeit and timing it so that we do not have to change the Foo definition, and, No matter how many functions B has seen, we don't have to modify the function definition!

Import Time Def foo ():    print ' in foo () ' Def Timeit (func):    start = Time.clock ()    func ()    end =time.clock () C8/>print ' used: ', End-start Timeit (foo)

There seems to be no logical problem, everything is fine and functioning properly! ...... Wait, we seem to have modified the code for the calling section. Originally we called this: Foo (), modified to become: Timeit (foo). In this case, if Foo is called at N, you will have to modify the code in the N place. Or, to be more extreme, consider that the code in which it is called cannot modify the situation, for example: This function is something you give to someone else.

1.3. Minimize Changes!

That being the case, we'll try to figure out how to do this without modifying the calling code, which means that calling Foo () requires the effect of calling Timeit (foo). We can think of assigning Timeit to Foo, but Timeit seems to have a parameter ... Think of ways to unify the parameters! If Timeit (foo) does not directly produce a call effect, but instead returns a function that is consistent with the Foo argument list ... It's good to have the return value of Timeit (foo) assigned to Foo, and then the code that calls Foo () doesn't have to be modified at all!

#-*-coding:utf-8-*-import Time def foo ():    print ' in foo () ' # defines a timer, passes in one, and returns another method with the timer function added Def timeit (func):         # fixed An inline wrapper function that adds a timer function to the incoming function.    def wrapper ():        start = Time.clock ()        func ()        end =time.clock ()        print ' Used: ', End-start         # Returns the Wrapped function to return    wrapper foo = Timeit (foo) foo ()

In this way, a simple timer is ready! We only need to call Foo after the definition of foo, and foo = Timeit (foo), to achieve the purpose of timing, which is the concept of adorners, which looks like Foo was Timeit decorated. In this example, the function enters and exits with timing, which is called a cross plane (Aspect), which is called aspect-oriented programming (Aspect-oriented programming). In comparison to the top-down execution of traditional programming habits, a logic is inserted horizontally in the process of function execution. In a specific business area, you can reduce the amount of repetitive code. Aspect-oriented programming there are quite a lot of terminology, here is not much to do introduction, interested in the words can find relevant information.

This example is for demonstration purposes only, and does not consider Foo with parameters and a return value of the case, the task of perfecting it to you:)

The above code seems to be no longer streamlined, and Python provides a syntactic sugar to reduce the amount of character input.

Import Time Def Timeit (func):    def wrapper ():        start = Time.clock ()        func ()        end =time.clock ()        print ' Used: ', End-start    return wrapper @timeitdef foo ():    print ' in foo () ' foo ()

Focus on the 11th line of @timeit, add this line to the definition and the other write foo = Timeit (foo) is completely equivalent, do not think that @ has another magic. In addition to the less character input, there is an additional benefit: it looks more like a decorator.

-------------------

To understand Python's adorners, we must first understand that functions are also considered objects in Python. This is important. Let's look at an example:

def shout (word= "yes"):    return word.capitalize () + "!" Print Shout () # output: ' Yes! ' # as an object, you can assign a function to any other object variable  scream = Shout # Note that we are not using parentheses because we are not calling function # We assign the function shout to scream, which means you can call shout Print scream () # Output by scream: ' Yes! ' # and you can delete the old name s Hout, but you can still access the function via Scream del shouttry:    print shout () except Nameerror, E:    print e    #输出: "Name ' shout ' is no T defined "Print scream () # output: ' Yes! '

Let's put this topic aside for the moment, let's take a look at Python's other interesting property: You can define a function in a function:

Def talk ():     # You can define another function in Talk    def Whisper (word= "yes"):        return Word.lower () + "...";     # ... and immediately use it     print whisper () # Every time you call ' Talk ', the whisper defined in the talk will also be called talk () # output: # Yes ... # but "whisper" does not exist alone: try:    p Rint Whisper () except Nameerror, E:    print e    #输出: "Name ' whisper ' is not defined" *

Function reference

From the above two examples we can conclude that since the function as an object, therefore:

1. It can be assigned to other variables

2. It can be defined within another function

This means that the function can return a function, see the following example:

def gettalk (type= "Shout"):     # We define another function    def shout (word= "yes"):        return word.capitalize () + "!"     DEF Whisper (word= "yes"):        return Word.lower () + "...";     # then we return one of the    if type = = "Shout":        # We are not using (), because we are not calling the function        # We are returning the function return        shout    else:        Return Whisper # and then how to use it? # Assign the function to a variable talk = Gettalk ()      # Here you can see that the talk is actually a function object: Print talk# output: <function shout at 0xb7ea817c> # The object is returned by the function One object: Print talk () # or you can call:p rint gettalk ("Whisper") () #输出: Yes ...

Also, since it is possible to return a function, we can pass it as a parameter to the function:

def dosomethingbefore (func):    print "I do something before then I call the function you gave me"    print func () Doso Methingbefore (Scream) #输出: #I do something before then I call the function you gave Me#yes!

Here you have enough to understand the adorner, and other it can be considered a wrapper. That is, it allows you to execute code before and after decorating without changing the contents of the function itself.

Handmade decoration

So how do you do manual decorating?

# Adorner is a function, and its argument is another function Def my_shiny_new_decorator (a_function_to_decorate): # inside defines another function: a wrapper.        # This function encapsulates the original function, so you can execute some code before or after it, Def The_wrapper_around_the_original_function (): # Put some code that you want before the real function executes        Print "Before the function runs" # executes the original function a_function_to_decorate () # Put some code that you want after the original function executes Print "After the function runs" #在此刻, "a_function_to_decrorate" has not been executed, we return the created encapsulation function #封装器包含了函数以及其前后执行的代码, it is ready to complete re Turn The_wrapper_around_the_original_function # Now imagine that you've created a function that you'll never be far back in touch with Def a_stand_alone_function (): print "I am a s Tand alone function, don ' t dare modify Me "a_stand_alone_function () #输出: I am A stand alone function, don ' t you dare mo Dify me # Well, you can encapsulate the extension of its implementation behavior. You can simply throw it to the adorner # The adorner will dynamically encapsulate it with the code you want, and return a new available function. a_stand_alone_function_decorated = My_shiny_new_decorator (a_stand_alone_function) a_stand_alone_function_ Decorated () #输出: #Before The function runs#i am a stand alone function, don ' t you dare modify Me#after the FUnction runs 

Now you may require that the actual call is a_stand_alone_function_decorated every time you call a_stand_alone_function. Implementation is also very simple, you can use My_shiny_new_decorator to re-assign the value of A_stand_alone_function.

A_stand_alone_function = My_shiny_new_decorator (a_stand_alone_function) a_stand_alone_function () #输出: #Before the Function runs#i am a stand alone function, don ' t you dare modify me#after the function runs # and guess what, that ' s EXACT LY What decorators do!

Decorator Secrets

In the previous example, we can use the adorner syntax:

@my_shiny_new_decoratordef another_stand_alone_function ():    print "Leave Me Alone" another_stand_alone_function ( ) #输出: #Before the function runs#leave me alone#after the function runs

Of course you can also accumulate decorations:

def Bread (func):    def wrapper ():        print "</" "\>"        func ()        print "<\______/>"    Return wrapper def Ingredients (func):    def wrapper ():        print "#tomatoes #"        func ()        print "~salad~"    Return wrapper def Sandwich (food= "--ham--"):    print Food sandwich () #输出:--ham--sandwich = Bread (Ingredients ( Sandwich)) sandwich () #outputs: #</"" \># #tomatoes # #--ham--# ~salad~#<\______/>

Using the Python adorner syntax:

@bread @ingredientsdef Sandwich (food= "--ham--"):    print Food sandwich () #输出: #</"" \># #tomatoes # #-- ham--# ~salad~#<\______/>

The order of the adorners is important and needs attention:

@ingredients @breaddef Strange_sandwich (food= "--ham--"):    print Food Strange_sandwich () #输出: # #tomatoes ##</" "' \>#--ham--#<\______/># ~salad~

Finally, answer the questions mentioned above:

# adorner Makebold used to convert to bold def makebold (FN):    # Results return the function    def wrapper ():        # Insert some code before and after execution        return "<b>" + fn () + "</b>"    return wrapper # Adorner makeitalic used to convert to Italic def makeitalic (FN):    # Results return the function    def wrapper ():        # Insert some code to execute before and after        return "<i>" + fn () + "</i>"    return wrapper @makebold @makeitalicdef say ():    Return "Hello" print Say () #输出: <b><i>hello</i></b> # equals def say ():    return "Hello" say = Makebold (Makeitalic (say)) print say () #输出: <b><i>hello</i></b>

Built-in adorners

There are three built-in decorators, Staticmethod, Classmethod, and property, respectively, to make the instance methods defined in the class into static, class, and class properties. Because functions can be defined in a module, static and class methods are not much useful unless you want to fully object-oriented programming. Attributes are not essential, and Java does not have the properties to live very well. From my personal Python experience, I have not used the property, and the frequency of using Staticmethod and Classmethod is very low.

Class Rabbit (object):         def __init__ (self, name):        self._name = name         @staticmethod    def newrabbit (name):        return Rabbit (name)         @classmethod    def newRabbit2 (CLS):        return Rabbit (")         @property    def Name (self):        return Self._name

The attribute defined here is a read-only property, and if it is writable, a setter needs to be defined:

@name. Setterdef name (self, name):    self._name = name

Functools Module

The Functools module provides two adorners. This module was added after Python 2.5, and generally everyone should use more than this version. But my usual working environment is 2.4 t-t

2.3.1. Wraps (wrapped[, assigned][, updated]):
This is a very useful decorator. A friend who has seen the previous reflection should know that the function has several special properties such as the function name, after being decorated, the function name Foo in the above example becomes the name of the wrapper function wrapper, and if you want to use reflection, it can result in unexpected results. This decorator solves this problem by preserving the special properties of the decorated function.

Import Timeimport functools def Timeit (func):    @functools. Wraps (func)    def wrapper ():        start = Time.clock ()        func ()        end =time.clock ()        print ' used: ', End-start    return wrapper @timeitdef foo ():    print ' in foo ( ) ' foo () print foo.__name__

Notice the 5th line first, and if you comment on this line, foo.__name__ will be ' wrapper '. In addition, I believe you have noticed that this decorator has a parameter. In fact, he has two other optional arguments, the property names in assigned are replaced with assignments, and the property names in updated are merged using update, and you can get their default values by looking at the source code of Functools. For this adorner, it is equivalent to wrapper = Functools.wraps (func) (wrapper).

2.3.2. Total_ordering (CLS):
This adorner is useful for certain occasions, but it is added after Python 2.7. Its role is to implement at least __lt__, __le__, __gt__, __ge__ one of the classes plus other comparison methods, this is a class adorner. If you feel bad, take a closer look at the source code of this adorner:

 

 def total_ordering (CLS): "" "" "Class decorator that fills in missing ordering methods" "" Convert = {56 ' __lt__ ': [(' __gt__ ', lambda Self, other:other < self), $ (' __le__ ', lambda Self, other:not oth Er < self), (' __ge__ ', lambda-Self, other:not-i < Other)],59 ' __le__ ': [(' __ge__ '                     , Lambda Self, other:other-<= self), (' __lt__ ', lambda-Self, other:not-other <=-self), 61 (' __gt__ ', lambda Self, other:not-<= other)],62 ' __gt__ ': [(' __lt__ ', lambda-Self, othe R:other > Self), + (' __ge__ ', lambda Self, other:not other > Self), 64 (' __ Le__ ', lambda Self, other:not-> Other)],65 ' __ge__ ': [(' __le__ ', lambda-Self, other:other->= self), 6 6 (' __gt__ ', lambda Self, other:not other >= self), "__lt__", Lambda Self, Other:not Self >= OTHer)]68}69 roots = Set (dir (CLS)) & Set (convert), if not roots:71 raise ValueError (' must defi NE at least one ordering operation: < > <= >= ') root = max (roots) # prefer __lt__ to __le__ to __ gt__ to __ge__73 for Opname, Opfunc on convert[root]:74 if Opname not in roots:75 opfunc.__name      __ = opname76 opfunc.__doc__ = getattr (int, opname). __doc__77 setattr (CLS, Opname, Opfunc) 78 Return CLS

Python decorator Explained

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.