Context Manager in Python

Source: Internet
Author: User

Just looked at the context Manager blog of the Vamei great God, understood as follows:

In fact, I often use the context manager, especially when opening files, if you are lazy, do not want to manually hit the F.close (), using the context manager OK pull.

The context manager is the with * * as:

For example, when you open a file,

The context manager invokes the __enter__ method of fi when it executes, and then calls the __exit__ method of FI, which completes the creation and closing of the file object.

Let's look at what the magic function of fi is:

fi = open (' 1 ', ' W ') >>> dir (FI) [' __class__ ', ' __delattr__ ', ' __doc__ ', ' __enter__ ', ' __exit__ ', ' __format__ ', ' _ _getattribute__ ', ' __hash__ ', ' __init__ ', ' __iter__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr ' __ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' close ', ' Closed ', ' encoding ', ' errors ', ' Fileno ', ' flush ', ' isatty ', ' Mode ', ' name ', ' newlines ', ' next ', ' read ', ' Readinto ', ' readline ', ' readlines ', ' seek ', ' softspace ', ' Tell ', ' truncate ', ' Write ', ' writelines ', ' xreadlines ']

Obviously, test the __enter__ and __exit__ methods:

>>> fi = open (' Test.txt ', ' R ') >>> fi.__enter__ () <open file ' test.txt ', mode ' R ' at 0X107225780>&G T;>> fi.__exit__ () >>> fi.closedtrue

Obviously, the __ENTER__ function opens the file, and the __exit__ function closes the file.

With this principle, we can write our own objects with __enter__ and __exit__ functions, so that we can use context management for these objects.

Principle of context Management:

#with * * AS:OBJECT.__ENTER__ () Try:    block# may throw an exception finally:    object.__exit__ ()

Context Manager in 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.