一、With语句是什么?
许多编程任务涉及前置设置与后置清理工作。针对此类场景,Python提供了便捷的with语句。以文件处理为例,通常流程包括获取文件句柄、读取数据以及关闭句柄。
若不使用with语句,常规代码如下:
file = open("/tmp/foo.txt")
data = file.read()
file.close()
这种方式存在两个主要缺陷:
首先,开发者可能遗漏关闭文件句柄;其次,若在读取数据时发生异常且未做处理,程序将直接中断。
以下是增强版异常处理代码:
try:
f = open('xxx')
except:
print 'fail to open'
exit(-1)
try:
do something
except:
do something
finally:
f.close()
尽管该代码能正常运行,但结构过于冗长。
此时,with语句的优势得以体现。它不仅语法更简洁,还能妥善处理上下文环境产生的异常。
使用with语句的代码如下:
with open("/tmp/foo.txt") as file:
data = file.read()
二、with如何工作?
紧跟在with后的语句求值后,其返回对象的__enter__()方法会被调用,返回值赋值给as后的变量。当with包裹的代码块执行完毕后,系统将调用前述对象的__exit__()方法。
以下示例具体展示with的工作流程:
#!/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#!/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__()
正如你看到的:
1. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是”Foo”,赋值给变量’sample’
3. 执行代码块,打印变量”sample”的值为 “Foo”
4. __exit__()方法被调用
with的核心优势在于异常处理能力。注意Sample类的__exit__方法包含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()
本例中,with后的get_sample()替换为Sample(),这并非关键,只要with后表达式返回的对象具备__enter__()和__exit__()方法即可。
在此例中,Sample()的__enter__()方法返回新创建的Sample对象,并赋值给变量sample。
代码执行后的状态:
bash-3.2$ ./with_example02.py
type:
value: integer division or modulo by zero
trace:
Traceback (most recent call last):
File "./with_example02.py", line 19, in
sample.do_something()
File "./with_example02.py", line 15, in do_something
bar = 1/0
ZeroDivisionError: integer division or modulo by zero
实际上,当with包裹的代码块抛出任何异常时,__exit__()方法即被触发。如示例所示,异常关联的type、value和stack trace会传递给__exit__(),因此ZeroDivisionError异常被打印出来。
在开发库时,资源清理、文件关闭等操作均可置于__exit__方法中。
此外,__exit__不仅用于资源销毁(tear things down),还可监控和处理异常,需注意后续参数。若要忽略特定异常,只需让函数返回True。
以下样例代码跳过所有TypeError,而其他异常则正常抛出。
def __exit__(self, type, value, traceback):
return isinstance(value, TypeError)
总之,with-as表达式极大简化了finally块的编写,对保持代码优雅性有显著帮助。
若需处理多个项,写法如下:
with open("x.txt") as f1, open('xxx.txt') as f2:
do something with f1,f2
因此,Python的with语句提供了一种有效机制,使代码更简练,同时在异常发生时简化清理工作。
三、相关术语
使用with语句需理解上下文管理器概念。只有具备上下文管理器,with语句才能正常工作。以下列出相关概念。
上下文管理协议(Context Management Protocol):包含__enter__()和__exit__()方法,支持该协议的对象必须实现这两个方法。
上下文管理器(Context Manager):支持上下文管理协议的对象,实现了__enter__()和__exit__()方法。它定义执行with语句时的运行时上下文,负责进入与退出操作。通常通过with语句调用,也可直接调用其方法。
运行时上下文(runtime context):由上下文管理器创建,通过__enter__()和__exit__()方法实现。__enter__()在语句体执行前进入上下文,__exit__()在语句体执行后退出上下文。
上下文表达式(Context Expression):with关键字后的表达式,需返回一个上下文管理器对象。
语句体(with-body):with包裹的代码块。执行前调用__enter__(),执行后调用__exit__()。
到此这篇关于浅谈一下Python中的with用法的文章就介绍到这了,更多相关Python的with用法内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!