Home  >  Article  >  Backend Development  >  How to add extra behavior before and after Python function execution

How to add extra behavior before and after Python function execution

WBOY
WBOYOriginal
2016-12-05 13:27:161430browse

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)

Run as follows:

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

(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 the with statement, 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()

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.

Statement:
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