Sometimes you may need to add additional functions (such as filtering and timing) before and after the function. in the past, you always thought of the decorator first. I recently learned the Python context manager, so this article introduces how to add additional behaviors before and after Python function execution. if you need it, let's take a look at it. First, let's look at a small program. this is a program that measures the time spent. The following is a previous solution example:
From functools import wraps, partialfrom time import timedef 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 ('runtime :{:. 6f} s. '. Format (end_time-start_time) return result return _ wrapper @ timingdef run (): l = [] for I in range (5000000): l. extend ([I]) return len (l)
Run the following command:
In [4]: run () running time: 2.383398 s. Out [4]: 5000000
(If you like to answer questions, you can remove comments and think about the expected output ).
Today, I accidentally saw the Python context manager (Context Manager
), And found very good, in fact, thiswith
The statement is closely related, so I never cared about it before.
From time import timedef run2 (): l = [] for I in range (0, 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 ('runtime :{:. 6f} s. '. Format (self. end_time-self. start_time) with ElapsedTime (): run2 ()
Summary
After reading some official documents at the beginning, context management is still somewhat informative. It is not easy to develop Python. To put it simply, you are not enough to keep pace with the times. all you have mastered is the old-fashioned three-board axe. Therefore, we need to constantly update our knowledge to make up for our blind spots. the above is all the content of this article, hoping to help everyone learn or work.