If you have the habit of reading the source code, you may see that some excellent codes often contain statements with the "with" keyword. what scenarios does it usually use? Let's talk about with and context manager today. If you have the habit of reading the source code, you may see that some excellent codes often contain statements with the "with" keyword. what scenarios does it usually use? Let's talk about with and context manager today.
For system resources such as files, database connections, and sockets, once the application opens these resources and runs the business logic, one thing that must be done is to close (disconnect) the resource.
For example, if a Python program opens a file and writes content to the file, it will close the file after writing it. Otherwise, what will happen? In extreme cases, the "Too open files" error may occur, because the maximum number of files allowed by the system is limited.
Similarly, if the number of connections to the database is Too large and the database is not closed in time, "Can not connect to MySQL server Too many ONS" may occur ", because database connection is a very expensive resource, it is impossible to create without limit.
To see how to close a file correctly.
Normal version:
Def m1 (): f = open ("output.txt", "w") f. write ("python Zen") f. close ()
In this way, there is a potential problem in writing. if an exception occurs during the write call, the subsequent code cannot be executed, and the close method cannot be called normally, therefore, resources will be released by the user of the program. So how can we improve the code?
Advanced Edition:
Def m2 (): f = open ("output.txt", "w") try: f. write ("Zen python") handle T IOError: print ("oops error") finally: f. close ()
The program of the improved version captures the code where exceptions may occur and uses the try/finally statement. This statement indicates that if exceptions occur in the try code block, the subsequent code will not be executed, but will jump directly to the coding T code block. In any case, the finally block code will eventually be executed. Therefore, as long as you put close in finally code, the file will be closed.
Advanced Edition:
Def m3 (): with open ("output.txt", "r") as f: f. write ("Zen Python ")
A more concise and elegant method is to use the with keyword. The return value of the open method is assigned to the variable f. When the with code block is left, the system automatically calls the f. close () method. the with function is the same as the try/finally statement. So what is its implementation principle? Another concept is involved before talking about the with principle, that is, Context Manager ).
Context manager
Any implementedEnter ()AndExit ()The method object can be called the context manager, and the context manager object can use the with keyword. Obviously, the file object also implements the context manager.
How do we implement these two methods for file objects? We can simulate and implement a file class to implement this class.Enter ()AndExit ()Method.
class File(): def init(self, filename, mode): self.filename = filename self.mode = mode def enter(self): print("entering") self.f = open(self.filename, self.mode) return self.f def exit(self, *args): print("will exit") self.f.close()
Enter ()The method returns the resource object, which is the object you want to open,Exit ()Method.
Because the File class implements the context manager, now you can use the with statement.
with File('out.txt', 'w') as f: print("writing") f.write('hello, python')
In this way, you do not need to explicitly call the close method, which is automatically called by the system, even if an exception occurs in the middle of the close method.
Contextlib
Python also provides a contextmanager modifier, which further simplifies the implementation of the context manager. Yield divides the function into two parts.EnterMethod, and the statements after yield areExitMethod. The value following yield is the return value of the function.
from contextlib import contextmanager@contextmanagerdef my_open(path, mode): f = open(path, mode) yield f f.close()
Call
with my_open('out.txt', 'w') as f: f.write("hello , the simplest context manager")
Summary
Python provides the with syntax to simplify subsequent cleanup operations for Resource Operations. it is an alternative to try/finally. the implementation principle is based on the context manager. In addition, Python provides a contextmanager modifier to further simplify the implementation of the upper and lower managers.
The above is the detailed description of the keyword "with" and the context manager. For more information, see other related articles in the first PHP community!