python decorator

发布时间:2019-08-27 07:59:46编辑:auto阅读(1733)

    def benchmark(func): 

        """ 

        A decorator that prints the time a function takes 

        to execute. 

        """ 

        import time 

        def wrapper(*args, **kwargs): 

            t = time.clock() 

            res = func(*args, **kwargs) 

            print func.__name__, time.clock()-t 

            return res 

        return wrapper 

     

     

    def logging(func): 

        """ 

        A decorator that logs the activity of the script. 

        (it actually just prints it, but it could be logging!) 

        """ 

        def wrapper(*args, **kwargs): 

            res = func(*args, **kwargs) 

            print func.__name__, args, kwargs 

            return res 

        return wrapper 

     

     

    def counter(func): 

        """ 

        A decorator that counts and prints the number of times a function has been executed 

        """ 

        def wrapper(*args, **kwargs): 

            wrapper.count = wrapper.count + 1 

            res = func(*args, **kwargs) 

            print "{0} has been used: {1}x".format(func.__name__, wrapper.count) 

            return res 

        wrapper.count = 0 

        return wrapper 

     

    @counter 

    @benchmark 

    @logging 

    def reverse_string(string): 

        return str(reversed(string)) 

     

    print reverse_string("Able was I ere I saw Elba"

    print reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!"

     

    #outputs: 

    #reverse_string ('Able was I ere I saw Elba',) {} 

    #wrapper 0.0 

    #wrapper has been used: 1x  

    #ablE was I ere I saw elbA 

    #reverse_string ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!',) {} 

    #wrapper 0.0 

    #wrapper has been used: 2x 

    #!amanaP :lanac a ,noep a ,stah eros ,raj a ,hsac ,oloR a ,tur a ,mapS ,snip ,eperc a ,)lemac a ro( niaga gab ananab a ,gat a ,nat a ,gab ananab a ,gag a ,inoracam ,elacrep ,epins ,spam ,arutaroloc a ,shajar ,soreh ,atsap ,eonac a ,nalp a ,nam A 

    @counter 

    @benchmark 

    @logging 

    def get_random_futurama_quote(): 

        import httplib 

        conn = httplib.HTTPConnection("slashdot.org:80"

        conn.request("HEAD""/index.html"

        for key, value in conn.getresponse().getheaders(): 

            if key.startswith("x-b"or key.startswith("x-f"): 

                return value 

        return "No, I'm ... doesn't!" 

     

    print get_random_furturama_quote() 

    print get_random_furturama_quote() 

     

    #outputs: 

    #get_random_futurama_quote () {} 

    #wrapper 0.02 

    #wrapper has been used: 1x 

    #The laws of science be a harsh mistress. 

    #get_random_futurama_quote () {} 

    #wrapper 0.01 

    #wrapper has been used: 2x 

    #Curse you, merciful Poseidon! 

    Python itself provides several decorators: property, staticmethod, etc. Django use decorators to manage caching and view permissions. Twisted to fake inlining asynchronous functions calls. This really is a large playground. 

     

     

关键字