Python contextlib module usage example, pythoncontextlib
To read this module, you must first check the usage of with as. The most common method is to open a file:
Copy codeThe Code is as follows:
With open ("filename") as f:
F. read ()
With can call a context manager to generate a runtime context. The context manager mainly defines two methods, __enter __,__ exit __. _ Enter _ return the objects in the context, such as f. _ Exit _ is used to destroy objects and handle exceptions.
The contextlib module has three external interfaces,
Contextmanager. The decoration function must be a generator. Then, a function is returned, and a context manager is returned when the function is called.
To call multiple context managers at a time, nested puts _ enter _ in all context managers in vars, returns yield at a time, and unpacks it. Multiple objects are generated. _ Exit _ are all put in the exits list and called in finally. These _ exit _ are used to handle exceptions when the context manager is called. If false is returned, the exception will be thrown. If true is returned, the exception will not be thrown.
Closing, this is used. I didn't expect it to be a class, not a function. The object with the close method but no _ exit _ method is converted into a context manager. The code is simple:
Copy codeThe Code is as follows:
Class closing (object ):
Def _ init _ (self, thing ):
Self. thing = thing
Def _ enter _ (self ):
Return self. thing
Def _ exit _ (self, * exc_info ):
Self. thing. close ()