Python basic instruction with, contextlib instance usage detailed

Source: Internet
Author: User
This article mainly introduces the usage of with and contextlib in Python, and analyzes the function, use method and related precautions of the with and contextlib in detail in the case form, and the friends can refer to the following

This example describes the use of with and contextlib in Python. Share to everyone for your reference, as follows:

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-8class Echo:  def output (self):    print "Hello World"  def __enter__ (self):    print ' Enter ' Return self    #返回自身实例, of course, can also return anything you wish to return  def __exit__ (self, exception_type, Exception_value, Exception_ Traceback):    #若发生异常, will be captured here, can be handled abnormally    print ' exit '    #如果改__exit__可以处理改异常则通过返回True告知该异常不必传播, otherwise return false    if Exception_type = = ValueError:      return True    else:      return falsewith Echo () as E:  e.output () C14/>print ' Do something inside ' print '-----------' with Echo () as E:  raise ValueError (' value error ') print '-------- ---' with echo () as E:  raise Exception (' 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:


From contextlib import Contextmanager@contextmanagerdef make_context ():  print ' Enter '  try:    yield {}  Except RuntimeError, err:    print ' error ', err  finally:    print ' exit ' with Make_context () as value:  print Value

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:


From contextlib import contextmanagerfrom contextlib import nestedfrom contextlib import closing@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 make_context (' a ') as a, Make_context (' B ') as B:  print a
  
   print bclass Door (object):  def Open (self):    print ' Door are opened '  def close (self):    print ' Door ' Closed ' 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.