Python has a lot of magic methods, and this article documents the usefulness of two magic methods used by context managers that can be customized with statements, namely the
Custom Context Management Classes
The most common with statement is the open function. Instead of explaining it here, let’s look directly at an example of a custom class.
The above defines a class that defines two methods that print values, one of which throws an exception. Also the class uses two magic methods. With these two methods, the class can be called using the with statement to see the result of calling a normal function.
The results are as follows.
Then look at the result of calling a function that throws an exception.
From the above two calls, you can see that the three parameters inside the
__exit__ function (which are required by default when defining the function) represent the type of error, the cause of the error, and the trace of the error, and only when the with statement is called with an error, these three parameters have values, otherwise they are None. These three parameters can be used to determine and handle exceptions.
Context Management Utilities
We already know how to define the with statement and what happens when we encounter an exception, so now let’s see what are the scenarios for using the custom with statement.
The with statement is more suitable for the scenario of open->operate->close, in addition to our common file operations, there are database operations, SSH operations will involve this process. So, let’s take a look at the examples of these two operations directly.
The above example of data manipulation is typical, it includes database connection, database manipulation (after the with statement), exception handling, and database connection closure.
Take a look at the use of the with statement.
It is very convenient, but of course, if you combine it with try statements to connect, it will be more secure and reliable.
Let’s take a look at the SSH operation example.
Obviously, the above custom class with statement returns an SSHClient object, so it can be called directly according to the methods of this object, and will be automatically disconnected at the end of the call.
To summarize: the custom with statement is simply understood to be very suitable for some “start and finish” scenarios, by customizing the context manager, you can simplify some fixed operations that need to be executed repeatedly, and only need to focus on the specific operation itself.