- 毅力与勇气是事业的双飞翼; - 在尝试中成长,在失败中奋起。 - 概览 -> 细读 -> 概览 - 书不在多,在于精。
分类: Python/Ruby
2014-07-14 16:17:37
点击(此处)折叠或打开
点击(此处)折叠或打开
点击(此处)折叠或打开
While this might look like magic, the way Python handles with is more clever than magic. The basic idea is that the statement after with has to evaluate an object that responds to an __enter__() as well as an __exit__() function.
After the statement that follows with is evaluated, the __enter__() function on the resulting object is called. The value returned by this function is assigned to the variable following as. After every statement in the block is evaluated, the __exit__() function is called.
This can be demonstrated with the following example:
点击(此处)折叠或打开
点击(此处)折叠或打开
As you can see,
What makes with really powerful is the fact that it can handle exceptions. You would have noticed that the __exit__() function for Sample takes three arguments – val, type and trace. These are useful in exception handling. Let’s see how this works by modifying the above example.
点击(此处)折叠或打开
Notice how in this example, instead of get_sample(), with takes Sample(). It does not matter, as long as the statement that follows with evaluates to an object that has an __enter__() and __exit__() functions. In this case, Sample()’s __enter__() returns the newly created instance of Sample and that is what gets passed to sample.
When executed:
点击(此处)折叠或打开
Essentially, if there are exceptions being thrown from anywhere inside the block, the __exit__() function for the object is called. As you can see, the type, value and the stack trace associated with the exception thrown is passed to this function. In this case, you can see that there was a ZeroDivisionError exception being thrown. People implementing libraries can write code that clean up resources, close files etc. in their __exit__() functions.
Thus, Python’s with is a nifty construct that makes code a little less verbose and makes cleaning up during exceptions a bit easier.
I have put the code examples given here on .