How to add extra behavior before and after a Python function is executed

Source: Internet
Author: User
First look at a small program, this is the measurement of the time spent in the program, the following is the previous solution example

From Functools import wraps, Partialfrom time import timedef timing (Func=none, Frequencies=1): If Func is None:  # Prin T ("+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_ Times = time ()  print (' run elapsed: {:. 6f}s. '. Format (end_time-start_time))  return result return _wrapper@timingdef run (): L = [] for I in range (5000000):  L.E Xtend ([i]) return Len (L)

Run as follows:

In [4]: Run () Elapsed time: 2.383398s. OUT[4]: 5000000

(like to be inquisitive, you can get rid of comments and think about what kind of output is expected).

Today I inadvertently see the context manager of Python ( Context Manager ), found also very good, in fact, this with is closely related to the statement, unexpectedly has never cared.

From time import Timedef 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 (' runtime elapsed: {:. 6f}s. '. Format (self.end_time-self.start_time)) with ElapsedTime (): Run2 ()

Summarize

A little bit of official documentation, context management or a lot of content. Python has evolved into the present, but it's not easy. Say simple, but you are not enough to keep pace with the times, master is old-fashioned kick just. Therefore, knowledge needs to be constantly updated to make up for their blind spots, the above is the whole content of this article, I hope we can learn or work to bring some help.

  • 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.