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())