After listening to the python decorator a hundred times, you will know that
Now that we know what python decorators are, what do we actually do with them at work?
Especially for my little test/manual innocent who can only write scripts and don’t do Python development.
Let’s start with the conclusion. It must be useful.
I. Use in automated testing
Take written automated tests for example. If I want to output something uniform, such as the running time of the case, the name of the case, etc., then I can use it.
First, take a look at the simplest case, which has no decorator:
import pytest
def test_01():
a = 1
b = 2
assert a < b
def test_02():
a = 1
b = 1
assert a-b == 0
if __name__ == '__main__':
pytest.main(['demo_test.py'])
Copy the code
There are two cases in the use-case file. Run them:
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = test session starts = = = = = = = = = = = = = = = = = = = = = = = = = = = = = platform win32 - Python 3.8.5, Pytest-6.0.1, py-1.9.0, plugy-0.13.1 RootDir: D:\ Practice collected 2 items demo_test.py.. [100%] = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 2 passed in 0.01 s = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = [Finished in 0.4 s]Copy the code
Run pass is… so 2 cases pass, 2 cases pass.
If I want to see the execution time of each case in the result, I can write a decorator to handle it:
import pytest import functools import time def log_execute_time(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() res = func(*args, **kwargs) end = time.perf_counter() print("{} time {} ms". Format (func.__name__, (end - start) * 1000)) return res return wrapper @log_execute_time def test_01(): a = 1 b = 2 assert a < b @log_execute_time def test_02(): a = 1 b = 1 assert a-b == 0 if __name__ == '__main__': pytest.main(['-s','demo_test.py'])Copy the code
Run it:
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = test session starts = = = = = = = = = = = = = = = = = = = = = = = = = = = = = platform win32 - Python 3.8.5, Pytest - the 6.0.1, py - 1.9.0, pluggy - 0.13.1 rootdir: D:\ exercise collected 2 items demo_test.py test_01 时 用 0.009999999674934 Ms. Test_02 时 0.0012999999999818712 ms. = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 2 passed in 0.03 s = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = [Finished in 0.4 s]Copy the code
As you can see, each case execution prints out the execution time.
The above example is a scenario for implementing automated tests, depending on how you explore your requirements.
Use of other Python development directions
I looked up other uses as well, and there are many uses in Python development, including the familiar “authentication”.
For example, if people fall in love with blog park, you can browse blogs without logging in to your account. Decorators can be used when you’re watching the rise and want to comment or post yourself and are prompted to log in. Code examples:
import functools def authenticate(func): @functools.wraps(func) def wrapper(*args, **kwargs): request = args[0] if check_user_logged_in(request): Return func(*args, **kwargs) # Post_comment () else: Raise Exception('Authentication failed') # Otherwise, Authentication fails return wrapper@authenticate def post_comment(request) passCopy the code
The above code just says that, to help describe the scenario.
In addition, it can also be used in many scenarios such as input rationality checking and caching. After all, it is not for development, so I will not go into the details here.
Three, decoration summary
A decorator is essentially a Python function or class that allows other functions or classes to add additional functionality without making any code changes. The return value of the decorator is also a function object or class object.
With decorators, we can extract a lot of code that is similar to the function itself and reuse it. At this point, I feel a bit like AOP for faceted programming.
What other application scenarios do you know? Please leave a comment.