Python Contextlib Module Use example

Source: Internet
Author: User
Look at this module first look at the use of with AS, the most common way is to open a file:
Copy the Code code as follows:


With open ("filename") as F:
F.read ()


With can invoke a context manager that produces the runtime context. The context manager primarily defines two methods, __enter__,__exit__. __ENTER__ returns the object that is manipulated in the context, such as F. __exit__ is destroying objects and exception handling.

The Contextlib module has three external interfaces,
ContextManager decorator, the decorated function must be a generator. It then returns a function that returns a context manager when the function is called.

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.

Closing, this used, unexpectedly is a class, rather than a function. is to turn an object with a close method but no __exit__ method into a context manager. The code is simple:
Copy the 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.