Common coding process, often used with the scene is (open file for file processing, and then implicitly executed the file handle closed, also suitable for sockets, these classes provide support for with):
With file ('test.py','r') as F: print F.readline ()
With the effect, like try...finally ..., provides a context mechanism to apply a class with a with statement, which must internally provide two built-in functions __enter__ and __exit__. The former executes before the principal code executes, and then executes after the principal code executes. The variables following the as are returned in the __ENTER__ function. The following code snippet and notes illustrate the use of __enter__ and __exit__ in a clear sense:
#!encoding:utf-8classEcho:defoutput (self):Print 'Hello World' def __enter__(self):Print 'Enter' returnSelf#return an instance of itself, and of course return anything you want to return def __exit__(self, exception_type, Exception_value, exception_traceback):#If an exception occurs, it is captured here and can be handled with exception Print 'Exit' #If you change the __exit__ to handle the exception, then return true to tell the exception not to propagate, otherwise false ifException_type = =ValueError:returnTrueElse: returnFalse with Echo () as E:e.output ()Print 'Do something inside'Print '-----------'With Echo () as E:RaiseValueError ('Value Error')Print '-----------'With Echo () as E:RaiseException ('can not detect')
Operation Result:
Contextlib is a module that provides a context mechanism to strengthen the with statement, which is implemented through generator. Context management is not difficult, but cumbersome, by defining classes and writing __enter__ and __exit__. The ContextManager in Contextlib as an adorner to provide a context-management mechanism for the function level. Common frameworks are as follows:
fromContextlibImportContextManager @contextmanagerdefMake_context ():Print 'Enter' Try : yield {} exceptRuntimeError, err:Print 'Error', Errfinally : Print 'Exit'With Make_context () as Value:PrintValue
Contextlib also has an important thing, one is nested, and the other is closing, which is used to create nested contexts, and then to help you execute a defined close function. But nested is obsolete, because with can already be nested directly through multiple contexts. Here is an example:
1 fromContextlibImportContextManager2 fromContextlibImportnested3 fromContextlibImportclosing4 @contextmanager5 defMake_context (name):6Print 'Enter', name7yieldname8Print 'Exit', name9 TenWith Nested (Make_context ('A'), Make_context ('B') as (A, b): OnePrinta APrintb - -With Make_context ('A') as a, Make_context ('B') as B: thePrinta -Printb - - classDoor (object): +defOpen (self): -Print 'Door is opened' +defClose (self): APrint 'Door is closed' at - With closing (Door ()) as Door: -Door.open ()
Operation Result:
Summary: Python has a lot of powerful features, and because we are always accustomed to some of the previous programming habits of C + + or Java, these good mechanisms are often overlooked. So, to learn to use these Python features, let's write a python program that looks more like python.
Original from: http://www.cnblogs.com/coser/archive/2013/01/28/2880328.html
Python_ on the use of with and contextlib