Look at this module first look at the use of with AS, the most common way is to open a file:
Copy the Code code as follows:
With open ("filename") as F:
F.read ()
With can invoke a context manager that produces the runtime context. The context manager primarily defines two methods, __enter__,__exit__. __ENTER__ returns the object that is manipulated in the context, such as F. __exit__ is destroying objects and exception handling.
The Contextlib module has three external interfaces,
ContextManager decorator, the decorated function must be a generator. It then returns a function that returns a context manager when the function is called.
Nested in order to invoke more than one context manager at a time, the __enter__ in all the context manager is placed in the VARs, one yield return, and then unpack. It produces multiple objects. __exit__ are placed in the exits list, which is called uniformly in Finally, and the __exit__ is handled when the calling context manager produces an exception. If False is returned, the exception will continue to be thrown, returning true without throwing an exception.
Closing, this used, unexpectedly is a class, rather than a function. is to turn an object with a close method but no __exit__ method into a context manager. The code is simple:
Copy the Code code 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 ()