When I read a program that uses Fabric, there is an object that is called by the with statement. After a little research, it seems that it's called ** Context Manager . .. The person who manages the context ( conquitest ) ( manager **) is What does Python mean and what makes me happy? I didn't understand it well and thought that I shouldn't copy it easily, so I decided to look it up.
In the official documentation It is explained as an object for defining and establishing ** runtime context ** when executing the with statement. So what is the ** runtime context **?
So I found an article on stack overflow. What is a “runtime context”?
It is described as an environment that is assembled by calling ** \ _ \ _ enter \ _ \ _ () and demolished by calling \ _ \ _ exit \ _ \ _ () **. This ** environment ** probably refers to the set of properties that the context manager itself has.
The context manager always promises to define the special methods \ _ \ _enter \ _ \ _ () and \ _ \ _ exit \ _ \ _ (). The signatures of \ _ \ _ enter \ _ \ _ () and \ _ \ _ exit \ _ \ _ () are strictly agreed. Details are omitted.
When the context manager is called with the with statement, just before the with block, Be sure to call \ _ \ _enter \ _ \ _ () If the processing of the with block ends normally (or an exception occurs), The context manager \ _ \ _ exit \ _ \ _ () is always called.
From the above, the merits of using the context manager can be seen.
--Small amount of code (especially the part that handles exceptions) and high readability --Providing a local scope environment (set of properties) with a block --Forced pre-processing (\ _ \ _ enter \ _ \ _) and post-processing (\ _ \ _ exit \ _ \ _)
Described at a later date