Python with usage

Source: Internet
Author: User
Tags file handling integer division stack trace

Transfer from http://blog.kissdata.com/2014/05/23/python-with.htmlWhat is the WITH statement?

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

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

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

Here are two questions:

    1. One is the possibility of forgetting to close the file handle;
    2. The second is the file read data exception, no processing.

The following is an enhanced version of handling exceptions:

  1. try:
  2. f = open(‘xxx‘)
  3. except:
  4. print ‘fail to open‘
  5. exit(-1)
  6. try:
  7. do something
  8. except:
  9. do something
  10. finally:
  11. f.close()

Although this code works well, it's too verbose.

This is the time for a show with a skill. In addition to having a more elegant syntax, with can also handle the exception generated by the context environment very well.

The following is the code with the version:

    1. with open("/tmp/foo.txt") as file:
    2. data = file.read()
How does the with work?
    • Immediately after the statement that follows with is evaluated, the __enter__ () method of the returned object is called, and the return value of the method is assigned to the variable following the AS.
    • The __exit__ () method of the previous return object is called when all code blocks following the with are executed.

The following example can specify how with works:

  1. #!/usr/bin/env python
  2. # with_example01.py
  3. class Sample:
  4. def __enter__(self):
  5. print "In __enter__()"
  6. return "Foo"
  7. def __exit__(self, type, value, trace):
  8. print "In __exit__()"
  9. def get_sample():
  10. return Sample()
  11. with get_sample() as sample:
  12. print "sample:", sample

Run the code, output as follows

    1. bash-3.2$ ./with_example01.py
    2. In __enter__()
    3. sample: Foo
    4. In __exit__()

As you can see: 1. The __enter__ () method is executed 2. The value returned by the __enter__ () method-In this case, "Foo", is assigned to the variable ' sample ' 3. Executes the code block and prints the variable "sample" with the value "Foo" 4. The __exit__ () method is called with the real power 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.

  1. #!/usr/bin/env python
  2. # with_example02.py
  3. class Sample:
  4. def __enter__(self):
  5. return self
  6. def __exit__(self, type, value, trace):
  7. print "type:", type
  8. print "value:", value
  9. print "trace:", trace
  10. def do_something(self):
  11. bar = 1/0
  12. return bar + 10
  13. with Sample() as sample:
  14. 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:

  1. bash-3.2$ ./with_example02.py
  2. type: <type ‘exceptions.ZeroDivisionError‘>
  3. value: integer division or modulo by zero
  4. trace: <traceback object at 0x1004a8128>
  5. Traceback (most recent call last):
  6. File "./with_example02.py", line 19, in <module>
  7. sample.do_something()
  8. File "./with_example02.py", line 15, in do_something
  9. bar = 1/0
  10. ZeroDivisionError: integer division or modulo 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.

In addition, __exit__ in addition to tear things down, can also be abnormal monitoring and processing, note the following several parameters. To skip an exception, you only need to return the function true.

The following sample code skips all TypeError and throws the other exceptions normally.

    1. def __exit__(self, type, value, traceback):
    2. return isinstance(value, TypeError)

As mentioned above, the __EXIT__ function can handle partial exceptions, and if we do not handle exceptions in this function, he will throw them normally, which is what we can write (Python version 2.7 and above, the previous version reference uses the contextlib.nested library function):

    1. try:
    2. with open( "a.txt" ) as f :
    3. do something
    4. except xxxError:
    5. do something about exception

In summary, the WITH-AS expression greatly simplifies the work of the Finally, which is very helpful for maintaining the elegance of the code.

If there are multiple items, we can write this:

    1. with open("x.txt") as f1, open(‘xxx.txt‘) as f2:
    2. do something with f1,f2

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