How to add extra behavior before and after Python function execution

WBOY
Release: 2016-12-05 13:27:16
Original
1385 people have browsed it

First, let’s look at a small program. This is a program that measures the time spent. The following are examples of previous solutions

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('运行花费时间:{:.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)
Copy after login

Run as follows:

In [4]: run() 运行花费时间:2.383398s。 Out[4]: 5000000
Copy after login

(If you like to get to the bottom of it, you can remove the comments and think about what kind of output is expected).

Today I accidentally saw Python’s context manager (Context Manager), and found it to be very good. In fact, it is closely related to thewithstatement, and I had never noticed it before.

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('运行花费时间:{:.6f}s。'.format(self.end_time - self.start_time)) with ElapsedTime(): run2()
Copy after login

Summary

After briefly reading some official documents, context management is still a bit complicated. Python has developed to this day, and it is actually not simple anymore. To put it simply, you are just not keeping up with the times, and all you have mastered are the old-fashioned three-axe. Therefore, knowledge needs to be constantly updated to make up for your blind spots. The above is the entire content of this article. I hope it can bring some help to everyone's study or work.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!