Python with as usage

Source: Internet
Author: User
Tags integer division stack trace

The following is reproduced

With.. As.. A usage scenario is file processing, you need to get a file handle, read the data from the file, and then close the file handle.

Common file processing is as follows:

1 file = open ("/tmp/foo.txt")2 data = ()  3 file.close ()# The file must be closed after it is used, because the file object consumes the resources of the operating system, and the number of files that the operating system can open at the same time is limited

Because the file reads and writes the possibility to produce the ioerror, once the error, the later F.close () will not call. So, to ensure that the file is closed correctly, whether or not it is an error, we can use the try ... finally to achieve:

1 file = open ("/tmp/foo.txt")2try:3      data = ()4finally:5     file.close ()

But there is a more concise implementation that uses the with AS

1 with open ("/tmp/foo.txt") as file:2     data = ()

The object with which the value is evaluated must have a __enter__ () method, a __exit__ () method.

1 classSample:2     def __enter__(self):3         Print "In __enter__ ()"4         return "Foo"5  6     def __exit__(self, type, value, trace):7         Print "In __exit__ ()"8  9 defget_sample ():Ten     returnSample () One   A With get_sample () as Sample: -     Print "Sample:", sample

Run as follows:

1 __enter__ ()2sample:foo3__exit__()

Run the process:

1. The __enter__ () method is executed and the returned object is assigned a value to the variable ' sample '

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

4. The __exit__ () method is called

With the real power of it is that it can handle exceptions. You may have noticed that the __exit__ method of 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.

 classSample:def __enter__(self):return Selfdef __exit__(self, type, value, trace):Print "Type:", typePrint "Value:", ValuePrint "Trace:", Tracedefdo_something (self): bar= 1/0returnBar + 10With Sample () as sample:sample.do_something ()

In this example, the Get_sample () behind with is changed to sample (). This has nothing to do with the __enter__ () and __exit__ () methods as long as the object returned by the statement following the with is followed. In this example, the __enter__ () method of sample () returns the newly created sample object and assigns a value to the variable sample.

After the code executes:

1bash-3.2$./with_example02.py2Type: <type'exceptions. Zerodivisionerror'>3Value:integer Divisionormodulo by Zero4Trace: <traceback object at 0x1004a8128>5 Traceback (most recent):6File"./", line 19,inch<module>7 sample.do_something ()8File"./", line 15,inchdo_something9Bar = 1/0TenZerodivisionerror:integer DivisionorModulo by zero

In fact, the __exit__ () method is executed when any exception is thrown in the code block following the with. As the example shows, when an exception is thrown, the associated type,value and stack trace is passed to the __exit__ () method, so the thrown Zerodivisionerror exception is printed out. When you develop a library, clean up resources, close files, and so on, all in the __exit__ method.

As a result, Python's with statement provides an effective mechanism for making the code more concise and for easier cleanup when the exception is generated.

Python with as usage

Related Article

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: 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.