Python decorator example use analysis

Source: Internet
Author: User

Python decorator example use analysis
Overview

The decorator is essentially a Python function that allows other functions to add additional functions without any code changes. The return value of the decorator is also a function object.

We need a decorator that can test the function running time, which can be defined as follows:

def timer(func):    def wrapper(*args, **kwargs):        start_time = time.time()        res = func(*args, **kwargs)        end_time = time.time()        print("Run time is: %s" % (end_time - start_time))        return res    return wrapper

Because it is a decorator, a function is accepted as a parameter and a function is returned. We need to use the @ Syntax of Python to place the decorator in the definition of the function:

@timerdef fun():    time.sleep(1)    print("This is a test")    return "OK"

The running result is:

This is a testRun time is: 1.0000572204589844OK

Putting @ timer at fun () is equivalent to executing the statement:

fun = timer(fun)

If the decorator itself needs to input parameters, you need to write a high-level function that returns the decorator, such as adding the name:

def timer(name):    def decorator(func):        def wrapper(*args, **kwargs):            start_time = time.time()            res = func(*args, **kwargs)            end_time = time.time()            print("Name is: %s ; Run time is: %s" % (name, (end_time - start_time)))            return res        return wrapper    return decorator

The call and result are shown as follows:

@timer("Lance#")def fun():    time.sleep(1)    print("This is a test")    return "OK"
This is a testName is: Lance# ; Run time is: 1.0000572204589844OK

Compared with the two-layer nested decorator, the effect of three-layer Nesting is as follows:

fun = timer("Lance#")(fun)

Because a function is also an object, it also has attributes such as _ name.
In the fun () function before the decorator is added, the result of calling the _ name _ attribute of fun is 'fun '. However, after the decorator is decorated, their _ name _ has changed from 'fun' to 'wrapper'

Therefore, you need to copy the _ name _ and other attributes of the original function to the wrapper () function. Otherwise, code execution that relies on the function signature will fail.

Python built-in functools. wraps can complete this task. Therefore, a complete decorator statement is as follows:

import functoolsdef timer(func):    @functools.wraps(func)    def wrapper(*args, **kwargs):        start_time = time.time()        res = func(*args, **kwargs)        end_time = time.time()        print("Run time is: %s" % (end_time - start_time))        return res    return wrapper

The overall code is as follows:

__Author__ = "Lance#"# -*- coding = utf-8 -*-import timeimport functoolsdef timer(name):    def decorator(func):        @functools.wraps(func)        def wrapper(*args, **kwargs):            start_time = time.time()            res = func(*args, **kwargs)            end_time = time.time()            print("Name is: %s ; Run time is: %s" % (name, (end_time - start_time)))            return res        return wrapper    return decorator@timer("Lance#")def fun():    time.sleep(1)    print("This is a test")    return "OK"if __name__ == '__main__':    print(fun())

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.