How do I add additional behavior before and after the Python function is executed
- 2020-05-17 05:41:30
- OfStack
Let's start with a small program that measures the amount of time it takes. Here's an example of a previous solution
from functools import wraps, partial
from time import time
def timing(func=None, frequencies=1):
if func is None:
# print("+None")
return partial(timing, frequencies=frequencies)
# else:
# print("-None")
@wraps(func)
def _wrapper(*args, **kwargs):
start_time = time()
for t in range(frequencies):
result = func(*args, **kwargs)
end_time = time()
print(' Running time: {:.6f}s . '.format(end_time-start_time))
return result
return _wrapper
@timing
def run():
l = []
for i in range(5000000):
l.extend([i])
return len(l)
It runs as follows:
In [4]: run()
Running time: 2.383398s .
Out[4]: 5000000
(those who like to get to the bottom can remove the comments and think about what output to expect).
Today I came across Python's context manager (
Context Manager
), and it turns out to be pretty good, too
with
The statement is closely related, actually before 1 straight did not care.
from time import time
def run2():
l = []
for i in range(5000000):
l.extend([i])
return len(l)
class ElapsedTime():
def __enter__(self):
self.start_time = time()
return self
def __exit__(self, exception_type, exception_value, traceback):
self.end_time = time()
print(' Running time: {:.6f}s . '.format(self.end_time - self.start_time))
with ElapsedTime():
run2()
conclusion
After a brief look at 1 point of official documentation, context management is still a bit much. So far, Python has not been easy. Say simple, just you are not up to date with The Times, master is the old 3 plank axe just. Therefore, the knowledge needs to be constantly updated, in order to make up for their own blind spots, the above is all the content of this article, I hope you can study or work to bring 1 definite help.