Look at this module to see the use of with AS, the most common method is to open a file:
Copy Code code as follows:
With open ("filename") as F:
F.read ()
With can invoke a context manager to produce a run-time context. The context manager mainly defines two methods, __enter__,__exit__. __ENTER__ returns an object that is manipulated in the context, such as F. __exit__ is the destruction of objects and exception handling.
The Contextlib module has three external interfaces,
ContextManager Adorner, the decorated function must be a builder. It then returns a function that returns a context manager when the function is called.
Nested in order to invoke multiple context managers at a time, put all the __enter__ in the context manager into VARs, once yield back, and then unpack. will produce multiple objects. __exit__ are placed in the exits list, and in finally the unified invocation of how these __exit__ are handled when invoking the context manager to produce an exception. If False, the exception will continue to be thrown, and return true will not throw an exception.
Closing, this used, unexpectedly is a class, not a function. is to turn an object with the Close method but no __exit__ method into a context manager. The code is simple:
Copy 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 ()