在 Python 中,如果我返回一个“with"阻止,文件还会关闭吗? [英] In Python, if I return inside a "with" block, will the file still close?
问题描述
考虑以下事项:
with open(path, mode) as f:
return [line for line in f if condition]
文件会被正确关闭,还是使用 return
以某种方式绕过 上下文管理器一个>?
Will the file be closed properly, or does using return
somehow bypass the context manager?
推荐答案
是的,它的作用类似于 try
块之后的 finally
块,即它总是执行(除非python进程当然以一种不寻常的方式终止).
Yes, it acts like the finally
block after a try
block, i.e. it always executes (unless the python process terminates in an unusual way of course).
在 PEP-343 的示例之一中也提到了它这是 with
语句的规范:
It is also mentioned in one of the examples of PEP-343 which is the specification for the with
statement:
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..除了
块,这通常不是人们想要的.
Something worth mentioning is however, that you cannot easily catch exceptions thrown by the open()
call without putting the whole with
block inside a try..except
block which is usually not what one wants.
这篇关于在 Python 中,如果我返回一个“with"阻止,文件还会关闭吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!