Python contextlib module usage example, pythoncontextlib

Source: Internet
Author: User

Python contextlib module usage example, pythoncontextlib

To read this module, you must first check the usage of with as. The most common method is to open a file:
Copy codeThe Code is as follows:
With open ("filename") as f:
F. read ()

With can call a context manager to generate a runtime context. The context manager mainly defines two methods, __enter __,__ exit __. _ Enter _ return the objects in the context, such as f. _ Exit _ is used to destroy objects and handle exceptions.

The contextlib module has three external interfaces,
Contextmanager. The decoration function must be a generator. Then, a function is returned, and a context manager is returned when the function is called.

To call multiple context managers at a time, nested puts _ enter _ in all context managers in vars, returns yield at a time, and unpacks it. Multiple objects are generated. _ Exit _ are all put in the exits list and called in finally. These _ exit _ are used to handle exceptions when the context manager is called. If false is returned, the exception will be thrown. If true is returned, the exception will not be thrown.

Closing, this is used. I didn't expect it to be a class, not a function. The object with the close method but no _ exit _ method is converted into a context manager. The code is simple:
Copy codeThe Code is 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.