简介
python中,with-as
语法一般用于资源关闭的情况,可以当成try - except - finally
的一种优雅写法,不需要我们自己频繁编写关于释放资源的代码。
以打开文件资源为例,通常的写法:
try:
f = open("xxx")
except:
print("except when open file")
exit(0)
try:
do ...
except:
do ...
finally:
f.close()
(PS:python中,try
,if
语块等并没有类似于其他语言中的作用域概念)
但是,用with ... as ...
写法,可以变成这样:
with open("xxx") as f:
do ...
原理
with-as
表达式语法需要python中class
的支持:
class TEST:
def __enter__ (self):
do ...
return somethings
def __exit__ (self, type, value, traceback):
do ... (finally)
当执行with-as
时(with TEST() as t
),首先调用__enter__
函数,
然后把该函数的return值返回给as
后面指定的变量。之后执行执行正常代码块,
最终,流程正常完毕或有异常状况,都会执行__exit__
函数。
后记
总之,with-as
是python在语言级别上实现了一种try-except-finally
的语法糖