Understand the With statement and pythonwith statement in Python

Source: Internet
Author: User
Tags integer division

Understand the With statement and pythonwith statement in Python

Some tasks may need to be configured in advance and cleaned up afterwards. In this scenario, the with statement of Python provides a very convenient processing method. A good example is File Processing. You need to obtain a file handle, read data from the file, and then close the file handle. Without the with statement, one wocould write something along the lines of: if you do not need the with statement, the Code is as follows:

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

There are two problems. First, you may forget to close the file handle. Second, an exception occurs when reading data from the file, and no processing is performed. The following is an enhanced version for exception handling:

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

This code runs well, but it is too long. At this time, it is time to show your skills. In addition to more elegant syntaxes, with can also handle exceptions in the context. The code for the with version is as follows:

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

How does with work?
This seems to be full of magic, but it is not just magic. Python is still very clever in handling. The basic idea is that the object with the value must have a _ enter _ () method and a _ exit _ () method.

After the statement followed by with is evaluated, the _ enter _ () method of the returned object is called, and the return value of this method is assigned to the variable after. After all the code blocks after with are executed, the _ exit _ () method of the returned object is called. This can be demonstrated with the following example: the following example describes how to work:

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

Run the code and output the following code:

bash-3.2$ ./with_example01.pyIn __enter__()sample: FooIn __exit__()

As you can see, 1. the _ enter _ () method is executed. 2. the value returned by the _ enter _ () method. In this example, it is "Foo" and is assigned to the variable 'sample' 3. run the code block and print the value of the variable "sample" to "Foo" 4. when the _ exit _ () method is called with, 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.

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

This does not matter, as long as the object returned by the statement following with has the _ enter _ () and _ exit _ () methods. In this example, the _ enter _ () method of Sample () returns the newly created Sample object and assigns it to the variable sample. When executed: After the code is executed:

bash-3.2$ ./with_example02.pytype: <type 'exceptions.ZeroDivisionError'>value: integer division or modulo by zerotrace: <traceback object at 0x1004a8128>Traceback (most recent call last): File "./with_example02.py", line 19, in <module>  sample.do_something() File "./with_example02.py", line 15, in do_something  bar = 1/0ZeroDivisionError: integer division or modulo by zero

In fact, when the code block after with throws any exception, the __exit _ () method is executed. As shown in the example, when an exception is thrown, the associated type, value, and stack trace are passed to the _ exit _ () method. Therefore, the error ZeroDivisionError thrown is printed out.

During database development, operations such as clearing resources and closing files can all be placed in the _ exit _ method.

Therefore, the with statement of Python provides an effective mechanism to make the code more concise, while cleaning is easier when exceptions are generated.

The above is an understanding of the With statement in Python, and I hope it will help you learn it.

Articles you may be interested in:
  • Python with Statement details
  • Python with usage
  • Understanding With statements in Python
  • How to Use the startswith () function in Python to determine the start of a string
  • Basic use of the endswith () function in Python
  • Python with usage example
  • The usage of the with statement in Python

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.