In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you the relevant knowledge points about how to achieve the Python context manager. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
When can I consider the context manager
When your code logic requires the following keywords, consider using a context manager to make your code more elegant:
Try:... finally:...
Next, we introduce three ways to implement the context manager.
Method 1 (context Manager Protocol)
It is well known that open () supports context managers by default. So the code that opens a txt file, writes to it, and then closes the file can be written like this:
With open ("1.txt", "w") as file:file.write ("this is a demo")
This is equivalent to:
File = Nonetry: file = open ("1.txt", "w") file.write ("this is a demo") finally: file.close ()
To implement the use of with statements in Python, you need to rely on the context manager protocol. That is, two magic methods, _ _ enter__ and _ _ exit__, need to be implemented.
Class OpenMyFile (object): def _ init__ (self, path): self.path = path def _ enter__ (self): print ("opening the txt") self.f = open (self.path, "w") return self def _ exit__ (self, * args, * * kwargs): print ("closing the txt") self.f.close () def write (self) String): print ("writing...") Self.f.write (string) with OpenMyFile ("2.txt") as file: file.write ("this is a demo2") # output: opening the txtwriting...closing the txt
At the same time, you can see that the 2.txt file is generated locally. It should be noted that _ _ enter__ gets the return instance object, otherwise an exception will be reported: AttributeError: "NoneType" object has no attribute "write"
This is because functions in Python return None by default.
Method 2 (@ contextmanager)
Use the contextmanager decorator in contextlib.
From contextlib import contextmanager@contextmanagerdef open_my_file (path): print ("opening the txt") f = open ("3.txt", "w") yield f print ("closing the txt") f.close () with open_my_file ("3.txt") as file: file.write ("this is demo3") # output: opening the txtclosing the txt
In the function decorated with @ contextmanager, you need to separate two logical statements with yield. Here the object coming out of yield will be received by the variable after as.
Method 3 (contextlib.closing ())
Use the closing () method in contextlib.
From contextlib import closingclass OpenMyFile (object): def _ init__ (self, path): print ("opening the txt") self.f = open (path, "w") def write (self String): self.f.write (string) def close (self): print ("closing the txt") self.f.close () with closing (OpenMyFile ("4.txt")) as file: file.write ("this is demo4") # output: opening the txtclosing the txt
Different from method 1. After being wrapped by the closing () method, the object's close () method is forced to be called at the end of the with statement. So using method 3, the method that needs to be defined is not _ _ exit__ () but close ().
These are all the contents of the article "how to implement the Python context Manager". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.