在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗?

In Python, if I return inside a quot;withquot; block, will the file still close?(在 Python 中,如果我在一个“with中返回.块,文件还会关闭吗?)
本文介绍了在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下几点:

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"中返回.块,文件还会关闭吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)