Research on the with principle of Python

The principle of with in Python

The with statement is suitable for accessing resources to ensure that necessary "cleanup" operations are performed regardless of whether an exception occurs during use, and resources are released, such as automatic closing of files after use, automatic acquisition and release of locks in threads, etc. For example, the above code, transformed by using the with statement, becomes the following:

#!/usr/bin/env python

with open('students.txt', 'r') as fileReader:
    for row in fileReader:
        print(row.strip())

As you can see, by using the with statement to refactor, the code immediately became clearer. Although I talked about how to use with here, it didn't say anything about it, so that people can't really understand the principle of with.

Digging deeper into the principle
In order to better grasp the usage of the with statement and understand its inner principle. Here is a deep dive into the principle of the with statement, so that everyone knows what it is and why.

To understand the principle of the with statement, we must first talk about the following concepts:

Context Management Protocol (Context Management Protocol): Contains methods enter () and __exit__(). Objects supporting this protocol must implement these two methods.
Context Manager: An object that supports the context management protocol. This object implements the __enter__() and __exit__() methods. The context manager defines the runtime context to be established when the with statement is executed, and is responsible for executing the entry and exit operations in the context of the with statement block. Usually use the with statement to call the context manager, you can also use it by directly calling its methods.
After talking about the above two concepts, let's start with the common expressions of the with statement. A basic with expression has the following structure:

with EXPR as VAR:
    BLOCK

Where EXPR can be any expression; as VAR is optional. The general execution process is as follows:

Execute EXPR to generate the context manager context_manager;
obtain the __exit() method of the
context manager and save it for later calls; call the __enter () method of the context manager ; if the as clause is used, set _ The return value of the _enter__() method is assigned to the VAR in the as clause;
the expression in the BLOCK
is executed ; whether an exception occurs during execution or not, the __exit__() method of the context manager is executed, and the exit () method is responsible for execution "Clean up" work, such as releasing resources. If there is no exception during the execution, or the statement break/continue/return is executed in the statement body, call __exit__(None, None, None) with None as the parameter; if an exception occurs during the execution, use sys.exc_info to get The exception information is the parameter call __exit__(exc_type, exc_value, exc_traceback);
when an exception occurs, if __exit__(type, value, traceback) returns False, the exception will be re-thrown and the statement logic other than with can handle the exception , This is also a common practice; if it returns True, the exception is ignored and no longer processed.

Guess you like

Origin blog.csdn.net/XRTONY/article/details/114869302