它是什么?
Python的with语句提供了一种非常便捷的方式来处理必须进行设置和拆卸才能使某些事情发生的情况。这方面的一个很好的例子是您想要获得文件处理程序,从文件中读取数据并关闭文件处理程序的情况。
如果没有该with声明,则可能会写以下内容:
file = open("/tmp/foo.txt")
data = file.read()
file.close()
这里有两个烦人的事情。首先,您最终忘记关闭文件处理程序。第二个是如何处理一旦获得文件处理程序可能发生的异常。可以这样写来解决这个问题:
file = open("/tmp/foo.txt")
try:
data = file.read()
finally:
file.close()
虽然这很好用,但它不必要地冗长。这with是有用的地方。with除了更好的语法外,关于它的好处还在于它可以很好地处理异常。使用时,上面的代码如下所示with:
with open("/tmp/foo.txt") as file:
data = file.read()
它是如何工作的?
尽管这看起来像魔术,但Python处理的方式with比魔术更聪明。基本思想是,后面的语句with必须评估响应__enter__()一个__exit__()函数以及一个函数的对象。
在with评估后面的语句之后,将__enter__()调用结果对象上的函数。此函数返回的值分配给变量following as。评估块中的每个语句后,将__exit__()调用该函数。
下面的示例可以证明这一点:
#!/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
执行后,将导致:
bash-3.2$ ./with_example01.py
In enter()
sample: Foo
In exit()
如你看到的,
该__enter__()函数被执行
它返回的值-在这种情况下"Foo",分配给sample
执行块的主体,从而打印sampleie 的值。“Foo”
该__exit__()函数被调用。
是什么让with真正强大的是它可以处理异常的事实。你会注意到,exit()对功能Sample有三个参数- val,type和trace。这些在异常处理中很有用。让我们通过修改上面的示例来了解其工作原理。
#!/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()
请注意,在这个例子中,而不是get_sample(),with需要Sample()。没关系,只要后面的语句with求值为具有__enter__()和__exit__()函数的对象即可。在这种情况下,Sample()的会__enter__()返回的新创建的实例,Sample而该实例将传递给sample。
执行时:
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
本质上,如果从块内的任何地方抛出了异常,则将__exit__()调用该对象的函数。如您所见,与引发的异常关联的类型,值和堆栈跟踪将传递给此函数。在这种情况下,您可以看到ZeroDivisionError抛出了异常。实现库的人员可以在其__exit__()功能中编写清理资源,关闭文件等的代码。