简介
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的语法糖