This article is for you to share the content of Python in the use of with, the need for friends can refer to
What is a 1.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:
File = Open ("/tmp/foo.txt") data = File.read () file.close ()
Here are two questions:
One is the possibility of forgetting to close the file handle;
The second is the file read data exception, no processing.
The following is an enhanced version of handling exceptions:
Try: f = open (' xxx ') except: print ' fail to open ' exit ( -1) Try: Does somethingexcept: do Somethingfinally: 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:
With open ("/tmp/foo.txt") as file: data = File.read ()
How does 2.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:
#!/usr/bin/env python# with_example01.pyclass 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, output as follows
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 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 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.
#!/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 + 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:
bash-3.2$./with_example02.pytype: <type ' exceptions. Zeropisionerror ' >value:integer pision or modulo by Zerotrace: <traceback object at 0x1004a8128>traceback (most R Ecent call last): file "./with_example02.py", line A, in <module> sample.do_something () file ". with_example02.py ", line at do_something bar = 1/0zeropisionerror:integer pision 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 Zeropisionerror 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.
def __exit__ (self, type, value, Traceback): 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):
Try: With open ("A.txt") as F: Do somethingexcept xxxerror: Does 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:
With open ("X.txt") as F1, open (' Xxx.txt ') as F2: Does 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.
3. Related terms
RELATED links:
1.http://blog.kissdata.com/2014/05/23/python-with.html
2.https://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/
Related recommendations:
How to understand the WITH statement in Python
Focus-within the use of a detailed