考虑以下事项:
with open(path, mode) as f:
return [line for line in f if condition]
文件是否会正确关闭,或者使用return
是否会绕过context manager?
考虑以下事项:
with open(path, mode) as f:
return [line for line in f if condition]
文件是否会正确关闭,或者使用return
是否会绕过context manager?
是的,它的行为就像try
块之后的finally
块,也就是说,它总是执行(当然,除非python进程以一种不寻常的方式终止).
with
语句的规格为PEP-343的示例之一中也提到了这一点:
with locked(myLock):
# Code here executes with myLock held. The lock is
# guaranteed to be released when the block is left (even
# if via return or by an uncaught exception).
然而,值得一提的是,如果不将整个with
挡路放入try..except
挡路中,您就无法轻松捕获由open()
调用抛出的异常,这通常不是人们想要的.