Usage of with as in python, and usage of python

Source: Internet
Author: User
Tags integer division

Usage of with as in python, and usage of python

What is the With statement?

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.
If the with statement is not used, 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.

The following example illustrates how with works:

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

In _ enter __()
Sample: Foo
In _ 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. Execute the code block and print the value of the variable "sample" to "Foo"

4. The _ exit _ () method is called.

The real strength of with 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.

#!/usr/bin/env python# with_example02.pyclass 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 () following with is changed to Sample (). 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.

After the code is executed:

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 19, in <module>
Sample. do_something ()
File "./with_example02.py", line 15, in do_something
Bar = 1/0
ZeroDivisionError: 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.

With-as statement

From python2.6, with becomes the default keyword. With is a control flow statement, which is similar to if for while try. with can be used to simplify try-finally code, which looks clearer than try finally, therefore, with uses an elegant method to handle exceptions in the context. The use of the with keyword is as follows:

with expression as variable:  with block

The code execution process is as follows:

1. Execute expression first, then execute the _ enter _ function of the object instance returned by the expression, and then assign the return value of the function to the variable after the. (Note that the return value of the _ enter _ function is assigned to the variable)

2. then execute the with block code block. Whether it is successful, error, or exception, after the with block is executed, the _ exit _ function of the instance in step 1 is executed.

With-as statement example

(1) Example of opening a file

The most common use of the with-as statement is to open a file, as follows:

with open("decorator.py") as file:  print file.readlines()

(2) custom

The objects following the with statement must have the _ enter _ and _ exit _ methods. The following is a custom example:

class WithTest():  def __init__(self,name):    self.name = name    pass  def __enter__(self):    print "This is enter function"    return self   def __exit__(self,e_t,e_v,t_b):    print "Now, you are exit"  def playNow(self):    print "Now, I am playing"print "**********"with WithTest("coolboy") as test:  print type(test)  test.playNow()   print test.nameprint "**********"

The result of running the above Code is as follows:

**********
This is enter function
<Type 'instance'>
Now, I am playing
Coolboy
Now, you are exit
**********

Analyze the code above: one or two lines. Execute the open function. This function returns an instance of a file object and then runs the _ enter _ function of the instance. This function returns the instance itself, finally, assign the value to the file variable. It can be confirmed from the first sentence.

The custom class WithTest is overloaded with the _ enter _ and _ exit _ functions to implement the with syntax. Note that in the _ enter _ function, self is returned. In the _ exit _ function, you can use the return value of _ exit _ to indicate whether reraise is required for exceptions in the with-block section. If false is returned, reraise with block exception. If true is returned, it is like nothing happens.

Support for with-as in the contextlib module of the context Manager

The contextlib module provides three objects: contextmanager, nested, and closing. These objects can be used to encapsulate existing generator functions or objects and support the context management protocol, avoiding the need to write the context manager to support with statements.

For closing of contextlib, closing helps implement the _ enter _ and _ exit _ methods. You do not need to implement these two methods by yourself, however, the close method must be provided for the objects loaded by closing. The contextlib. closing class implementation code is as follows:

class closing(object):  # help doc here  def __init__(self, thing):    self.thing = thing  def __enter__(self):    return self.thing  def __exit__(self, *exc_info):    self.thing.close()

The following is an example of using contextlib. closing:

import contextlibrequest_url = ('http://www.sina.com.cn/')with contextlib.closing(urlopen(request_url)) as response:  return response.read().decode('utf-8')

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.