Python Context Manager-1

Source: Internet
Author: User
Tags finally block

reference:https://zhuanlan.zhihu.com/p/26487659

Take a look at how to close a file correctly.

Normal version:

def m1():    f = open("output.txt", "w") f.write("python之禅") f.close()

There is a potential problem with this writing, and if an exception occurs during the call to write, causing the subsequent code to fail to continue, the Close method cannot be called properly, so the resource is always occupied by the program and cannot be freed. So how do you improve the code?

Advanced version:

 def m2 (): f Span class= "o" >= open ( "output.txt"  "W" ) try: f.< span class= "n" >write ( "python Zen" ) except ioerror: print ( "Oops error" ) finally: f. Close ()               

The modified version of the program is a try capture of the code where the exception might occur, using the Try/finally statement, which indicates that if the program has an exception in the try code block, subsequent code is no longer executed and jumps directly to the except code block. In any case, finally block code will eventually be executed. Therefore, as soon as you put close in the finally code, the file must be closed.

Premium Version:

def m3():    with open("output.txt", "w") as f: f.write("Python之禅")

A more concise and elegant way is to use the WITH keyword. The return value of the Open method is assigned to the variable F, and the system automatically calls the F.close () method when it leaves the with code block, with the same function as the try/finally statement. So what is the principle of its implementation? There is another concept to be addressed before the principle of with is the context manager.

Context Manager

Any object that implements the __enter__ () and __exit__ () methods can be called a context manager, and the context Manager object can use the WITH keyword. Obviously, the file object also implements the context manager.

So how do the file objects implement both methods? We can simulate implementing a file class of our own, allowing the class to implement the __enter__ () and __exit__ () methods.

classFile ():def __init__(self, filename, mode): Self.filename=filename Self.mode=Modedef __enter__(self):Print("entering") Self.f=Open (Self.filename, Self.mode)returnSELF.Fdef __exit__(Self, *args):Print("Would exit") Self.f.close ()
View Code

The __enter__ () method returns the resource object, which is the file object that you will open, and the__exit__ () method handles some cleanup work.

Because the File class implements the context manager, it is now possible to use the WITH statement.

classFile ():def __init__(self, filename, mode): Self.filename=filename Self.mode=Modedef __enter__(self):Print("entering") Self.f=Open (Self.filename, Self.mode)returnSelf.f#This return value is assigned to the variable F following the as    def __exit__(Self, *args):Print("Would exit") Self.f.close () with File ('OUT.txt','W') as F:Print("Writing") F.write ('Hello, Python')" "execution Result: Enteringwritingwill exit" "
View Code

This way, you don't have to call the Close method, which is called by the system automatically, even if an exception is encountered in the middle of the close method.

Python Context Manager-1

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.