Introduction to with...as usage in Python

Source: Internet
Author: User
Tags exception handling in python

This article mainly introduces the With...as usage introduction in Python, this article gives the usage example directly, the friend who needs can refer to the following

This syntax is used instead of the traditional try...finally syntax.

The code is as follows:

With EXPRESSION [as VARIABLE] With-block

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 code is as follows:

File = Open ("/tmp/foo.txt")

Try

data = File.read ()

Finally

File.close ()

Use with...as ... The way to replace the modified code is:

The code is as follows:

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

data = File.read ()

#!/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

Execution results are

The code is as follows:

In __enter__ ()

Sample:foo

In __exit__ ()

1. __enter__ () method is executed

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

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

4. The __exit__ () method is invoked with the real power 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.

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