Python Contextlib Module Use example _python

Source: Internet
Author: User

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 ()

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.