python with and context management tools

  • For system resources such as files, database connections, and sockets, after the application opens these resources and executes business logic, one thing that must be done is to close (disconnect) the resources.
  • For example, a Python program opens a file, writes content to the file, and closes the file after writing, otherwise what will happen? The "Too many open files" error occurs in extreme cases, because the maximum number of files the system allows you to open is limited.
  • Similarly, for databases, if there are too many connections and they are not closed in time, "Can not connect to MySQL server Too many connections" may appear, because database connections are a very expensive resource and cannot be created unlimitedly .
  • Reference: Correct understanding of the Python keyword "with" and context managers
def m1():
    f = open("output.txt", "w")
    f.write( " The Zen of Python " )
    f.close()
def m3():
    with open("output.txt", "w") as f:
        f.write( " The Zen of Python " )
  • A more concise and elegant way is to use the with keyword. The return value of the open method is assigned to the variable f. When leaving the with code block, the system will automatically call the f.close() method. The function of with is the same as using the try/finally statement. So what is its realization principle? Before talking about the principle of with, there is another concept involved, that is, the context manager (Context Manager).

context manager

Any object that implements the __enter__() and __exit__() methods can be called a context manager, and the context manager object can use the with keyword. Obviously, the file (file) object also implements a context manager.

So how does the file object implement these two methods? We can simulate and implement a file class of our own, and let this class implement the __enter__() and __exit__() methods.

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()

The __enter__() method returns the resource object, which is the file object you will open, and the __exit__() method handles some cleanup.

Because the File class implements a context manager, the with statement can now be used.

with File('out.txt', 'w') as f:
    print("writing")
    f.write('hello, python')

In this way, you don't need to explicitly call the close method, it is called automatically by the system, even if an exception is encountered in the middle, the close method will also be called.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325013843&siteId=291194637