Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of with and exception handling in python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people don't understand the knowledge points of this article "with and exception handling example analysis in python", so Xiaobian summarizes the following contents for everyone. The contents are detailed, the steps are clear, and they have certain reference value. I hope everyone can gain something after reading this article. Let's take a look at this article "with and exception handling example analysis in python".

In your long programming career, you've probably seen or used this code:

with open("test.txt", "r", encoding="utf-8") as f: s = f.readlines()

Some people will know the reason for writing this, but many more people do not know the reason. I just feel like everyone else writes like this, so I'll follow suit.

At the same time, many people who know why don't know why: the with statement automatically closes open file objects for us. But by what mechanism?

1. with and exception handling

We know that if you don't use the with statement, reading and writing a file normally should go through these processes: opening the file, manipulating the file, and closing the file. Expressed in Python code as follows:

f = open("test.txt", "r", encoding="utf-8")s = f.readlines()f.close()

Under normal circumstances, this seems to be fine.

Next we'll create an artificial "surprise": change the mode specified when opening a file object from "r" to "w."

f = open("test.txt", "w", encoding="utf-8")s = f.readlines()f.close()

At this point, when the program executes to line 2 to read the contents of the file, it will throw an error:

Traceback (most recent call last): File "test_with.py", line 2, in s = f.readlines()io.UnsupportedOperation: not readable

And then... something terrible happened.

Python exits with an unhandled exception, leaving code after line 2 unexecuted, so f.close() never gets a chance to execute again. A file object opened like a ghost, such a person adrift in the vast ocean of memory, no one knows who he is, where he came from, where he is going.

Thus, every time an exception is thrown, such a stray object is generated. Over time, the vast ocean of memory was naturally transformed into a paradise for wanderers, and no one else could think of it at all.

In the end, we found that the key to this problem lies in the possibility of throwing exceptions in the "open-action-close" file pipeline.

So we thought of using Python's killer to deal with these exceptions: try-catch.

Transform the previous code with exception handling:

try: f = open("test.txt", "a", encoding="utf-8") s = f.readlines()except: print("exception occurred")finally: f.close()

In this way, with the additional finally statement, open files are guaranteed to be closed regardless of whether the file operation throws an exception. thereby avoiding the problem of resource leakage caused by continuously occupying resources.

In effect, the with statement provides us with a try-catch-finally wrapper.

When programming, it seems to be just a casual with, but in fact, it has secretly ensured an exception handling mechanism similar to the above code.

2. context manager

To take effect, you need to act on a context manager--

Wait, what exactly is a context manager?

To make a long story short, objects that implement the__enter__and__exit__methods.

Both methods are loaded for use before entering a runtime context. The__enter__method is called when entering the runtime context, and the__exit__method is called before exiting the context.

The "runtime context" here can be simply understood as a code scope that provides some special configuration.

When we use the code with open("test.txt", "r", encoding="utf-8") as f, Python first evaluates open("test.txt", "r", encoding="utf-8") to get a context manager.

What's special here is that the file object itself is a context manager in Python, so we can use the open function as an expression to evaluate.

Then we call the__enter__method, which returns an object bound to the identifier f we specified. The file object's__enter__returns the file object itself, so this code binds the open "test.txt" file object to the identifier f.

Immediately follow the execution of the contents of the with block.

Finally call__exit__to exit the with statement block.

Based on the above, we can also construct a context manager ourselves (note that the parameters of the two feature methods should be consistent with the protocol):

class testContextManager: def __enter__(self): print("Enter runtime context, call__enter__method") def __exit__(self, exc_type, exc_value, traceback): print("exit runtime context, call__exit__method")with testContextManager() as o: pass

Output:

Enter runtime context, call__enter__method Exit runtime context, call__exit__method

The reason why the with statement can replace the cumbersome exception handling statement is that the context manager implements the__enter__and__exit__methods according to the protocol, and the with statement ensures that the__exit__method can be executed when an exception occurs, and then exits the relevant runtime context.

In this way, we can do some of the necessary cleaning.

The above is the content of this article about "with and exception handling example analysis in python". I believe everyone has a certain understanding. I hope the content shared by Xiaobian will be helpful to everyone. If you want to know more relevant 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report