In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to create the context manager in Python". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to create the context manager in Python.
Usually we want to put some operations in a code block so that we can keep it in a certain running state when executed in the code block, and when we leave that code block, we perform another operation to end the current state; so, in short, the purpose of the context manager is to specify the scope of the object's use and take "processing" if it goes beyond it. Python provides different ways to manage execution time. For example, you can use Python's built-in timeit module to manage the execution time of a small piece of code.
> import timeit
> timeit.timeit ('"-" .join (str (n) for n in range)', number=10000)
0.3018611848820001
However, the timeit.timeit function only accepts strings, which is limited if you want to manage more complex functions. The following example shows you how to run and manage functions using the timeit module.
Def test ():
"" Stupid test function "
L = [i for i in range (100)]
If _ _ name__ = ='_ _ main__':
Import timeit
Print (timeit.timeit ("test ()", setup= "from _ main__ import test"))
Although it works, it doesn't seem to be a real pythonic. Another way to manage execution time is to take advantage of Python's built-in cProfile module, but it is not recommended. In fact, it is not very precise, and it is just a workaround to let you know how long some code snippets need to execute. You can use it in the following ways:
> python-m cProfile
Since neither of the above methods is very Pythonic and flawed, how can we achieve a perfect solution?
In fact, it's very simple: we just need to get the time when the program starts and ends. Here's how to do it. Python has a built-in module for us to use: time.
> import time
> > start = time.time ()
> # do some stuff
> > end = time.time ()
> print (f "Elapsed Time: {end-start}")
But it's not very convenient to write like this. We can create a context manager.
Create a context manager
There are two different ways to create a context manager using Python, and we will explore two ways to do this: a class-based and generator-based context manager.
Class-based context manager
To create a class-based context manager, you need to first implement the magic variables _ _ enter__ and _ _ exit__. The first is called when entering the context (or code block) and the latter when leaving the context.
With these preparations in place, we can create a Timer class that implements both methods. When we enter the code block, we want to get the current time and save it in a variable that represents the beginning. If we leave the code block, we want to get the current time and subtract the start time from it. The results are printed out.
To customize the output, we ask the user to specify a statement that prints before the elapsed time. The following points show you a ready-to-use class.
From time import time
Class Timer (object):
Def _ _ init__ (self, description):
Self.description = description
Def _ enter__ (self):
Self.start = time ()
Def _ _ exit__ (self, type, value, traceback):
Self.end = time ()
Print (f "{self.description}: {self.end-self.start}")
With Timer ("List Comprehension Example"):
S = [x for x in range (10000000)]
Generator-based context manager
The generator-based approach is simpler. We can create a generator function that contains the program flow (getting the start and end times and the elapsed time for printing). The @ contextmanager decorator transforms the generator functionality into the appropriate context manager by using the GeneratorContextManager object wrapper generator.
From contextlib import contextmanager
From time import time
@ contextmanager
Def timing (description: str)-> None:
Start = time ()
Yield
Ellapsed_time = time ()-start
Print (f "{description}: {ellapsed_time}")
With timing ("List Comprehension Example"):
S = [x for x in range (10000000)]
If the code block after with is executed, it will jump back to the position after the yield keyword to continue execution. Thank you for reading, the above is the content of "how to create the context manager in Python". After the study of this article, I believe you have a deeper understanding of how to create the context manager in Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.