Python with as usage

Source: Internet
Author: User

With statement:

Afterwards do clean up work. such as file processing, need to get a file handle, read the data from the file, and then close the file handle

Without the With statement, the code is as follows:

File = open ("/tmp/foo.txt"= file.read () file.close ()

Here are two questions. One is to forget to close the file handle, and the other is the file read data exception, no processing. The following is an enhanced version of handling exceptions:

File = open ("/tmp/foo.txt")try:    = file.read () finally :    file.close ()

This code works fine, but it's too verbose.

With can handle exceptions generated by the context, the code is as follows:

With open ("/tmp/foo.txt") as file:    = File.read ()

With how it works:

The basic idea is that the object with which the value is evaluated must have a __enter__ () method, a __exit () __ method.

Immediately after the statement that follows with is evaluated, the __enter__ () method of the returned object is called, and the return value of the method is assigned to the variable following the AS. The __exit () __ method of the previous return object is called when all the code blocks behind with are executed.

classSample:def __enter__(self):Print("In __enter__ ()")        return "Foo"    def __exit__(self, type, value, trace):Print("In __exit__ ()")defget_sample ():returnSample () with Get_sample () as Sample:Print("Sample:", sample)

As you can see:

The 1.__enter__ () method is executed

The value returned by the 2.__enter__ () method is "Foo" in---example, assigned to the variable "sample"

3. Execute code block, print variable "sample" with the value "Foo"

The 4.__exit__ () method is called

With the real power of it is that it can handle exceptions. Perhaps you have noticed that the __exit__ method of the sample class has three parameters Val, type, trace. These parameters are useful in handling exceptions. Change the code below to see how it works.

class Sample:     def __enter__ (self):         return Self         def __exit__ (self, type, value, trace):         Print ("type")

Python with as usage

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.