Understanding the WITH statement in Python _python

Source: Internet
Author: User
Tags exception handling integer division stack trace in python

What is the WITH statement?

There are some tasks that may need to be set up beforehand to do clean-up work afterwards. For this scenario, Python's with statement provides a very convenient way to handle it. A good example is file processing, where you need to get a file handle, read data from a file, and then close the file handle.

If you do not use the WITH statement, the code is as follows:

Copy Code code as follows:

File = Open ("/tmp/foo.txt")
data = File.read ()
File.close ()

Here are two questions. One is the possibility of forgetting to close the file handle, and the second is that the file reads the data abnormally, without any processing. The following is a reinforced version of handling exceptions:

Copy Code code as follows:

File = Open ("/tmp/foo.txt")
Try
data = File.read ()
Finally
File.close ()

Although this code works well, it is too verbose. This is the time with a show of skill. In addition to having a more elegant syntax, with can also handle the exceptions generated by the context environment well. The following is the code for the with version:

Copy Code code as follows:

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

With how to work?

It looks magical, but it's not just magic, but Python's handling with it is smart. The basic idea is that the object with the value must have a __enter__ () method, a __exit__ () method.

The __enter__ () method of the returned object is called when the statement immediately following the with is evaluated, and the return value of the method is assigned to the variable after the AS. The __exit__ () method of the previously returned object is invoked when all the code blocks after the with are executed.

The following example can specify how the with works:

Copy Code code as follows:

#!/usr/bin/env python
# with_example01.py

Class Sample:
def __enter__ (self):
Print "in __enter__ ()"
Return "Foo"

def __exit__ (self, type, value, trace):
Print "in __exit__ ()"


Def get_sample ():
Return Sample ()


With Get_sample () as Sample:
Print "Sample:", sample

Line code, the output is as follows

Copy Code code as follows:

bash-3.2$./with_example01.py
In __enter__ ()
Sample:foo
In __exit__ ()

As you can see,

__enter__ () method is executed

The value returned by the __enter__ () method-This example is "Foo" and assigned to the variable ' sample '
Execute code block, print variable "sample" value is "Foo"

The __exit__ () method is called

With the real strength of it is that it can handle exceptions. You may have noticed that the __exit__ method for the sample class has three parameters-Val, type, and trace. These parameters are quite useful in exception handling. Let's change the code to see how it works.

Copy Code code as follows:

#!/usr/bin/env python
# with_example02.py


Class Sample:
def __enter__ (self):
return self

def __exit__ (self, type, value, trace):
print ' type: ', type
Print "Value:", value
Print "Trace:", Trace

def do_something (self):
Bar = 1/0
Return bar + 10

With sample () as Sample:
Sample.do_something ()

In this example, the Get_sample () behind the with is changed to sample (). This has nothing to do with the __enter__ () and __exit__ () method of the object returned by the statement immediately following the with. In this case, the __enter__ () method of sample () returns the newly created sample object and assigns it to the variable sample.

After code execution:

Copy Code code as follows:

bash-3.2$./with_example02.py
Type: <type ' exceptions. Zerodivisionerror ' >
Value:integer division or modulo by zero
Trace: <traceback object at 0x1004a8128>
Traceback (most recent call last):
File "./with_example02.py", line, in <module>
Sample.do_somet Hing ()
File "./with_example02.py", line, in do_something
Bar = 1/0
Zerodivisionerror:integer division or modulo by zero

In fact, the __exit__ () method is executed when any exception is thrown by the code block following the with. As the example shows, when an exception is thrown, the type,value and stack trace associated with it are passed to the __exit__ () method, so the thrown Zerodivisionerror exception is printed. When developing a library, cleaning resources, closing files, and so on, can be placed in the __exit__ method.

Thus, the Python with statement provides an efficient mechanism for making the code more concise, while the cleanup is simpler when the exception is generated.

The sample code can be found above the GitHub.

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.