The previous blog post simply describes the use of the WITH statement and the concept of the context Manager object, presumably with a certain understanding of the context Manager object. An object that implements the context management protocol, that is, an object that defines the two methods of the __enter__ () and __exit__ () methods in a class, can be called a context manager object.
However, there is a contextlib module in Python, which is a more graceful thing than with the context mechanism, which is implemented through the generator adorner, no longer using __enter__ and __exit__.
The Contextlib module has three external interfaces, namely the contextlib.contextmanager,contextlib.nested,
Contextlib.closing.
(1) Contextlib.contextmanager
ContextManager decorator, the decorated function must be a generator. It then returns a function that returns a context manager at the time of the function call, which is a context-management mechanism for the function level. Common methods are as follows:
#coding =utf-8from contextlib Import contextmanager@contextmanagerdef make_context (): print ' Enter ' Try:yield {} E Xcept runtimeerror, Err:print ' error ', err Finally:print ' exit ' with Make_context () as Value:print value
Output Result:
Enter
{}
Exit
At present there is no good example of use, and later, will be affixed.
(2) contextlib.nested
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. but nested is obsolete, because with can already be nested directly through multiple contexts . Use the following example:
#coding =utf-8from contextlib Import contextmanager,nested@contextmanagerdef make_context (name): print ' Enter ', name Yield name print ' exit ', Namewith nested (Make_context (' a '), Make_context (' B ')) as (A, B): Print A print bwith m Ake_context (' a ') as a, Make_context (' B ') as b:print a print B
Output Result:
Enter A
Enter B
A
B
Exit B
Exit A
Enter A
Enter B
A
B
Exit B
Exit A
(3) contextlib.closing
The file class supports the context manager, but there are some objects that are not supported. There are also classes that use the close () method but do not support the context Manager and use closing () to create a context manager for him. is to turn an object with a close method but no __exit__ method into a context manager.
Look at the following code:
From contextlib import Closingclass Door (object): Def open: print ' Door are opened ' def close (self): print ' Door is closed ' with closing (Door ()) as Door:door.open ()
Python:contextlib Module--Context Manager tool