How to add additional behavior before and after Python function execution

Source: Internet
Author: User
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, thiswithThe 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.