使用Python的“with”带有 try- except 块的语句
这是将 python“with”语句与 try- except 块结合使用的正确方法吗?:
try:
with open("file", "r") as f:
line = f.readline()
except IOError:
<whatever>
如果是,那么考虑旧的做事方式:
try:
f = open("file", "r")
line = f.readline()
except IOError:
<whatever>
finally:
f.close()
这里“with”语句的主要好处是我们可以摆脱三行代码?对于这个用例来说,这对我来说似乎没有那么引人注目(尽管我知道“with”语句还有其他用途)。
编辑:上述两个代码块的功能是否相同?
EDIT2:前几个答案一般谈论使用“with”的好处,但这些在这里似乎是边际效益。多年来我们都(或应该)显式调用 f.close() 。我认为一个好处是,草率的程序员会从使用“with”中受益。
Is this the right way to use the python "with" statement in combination with a try-except block?:
try:
with open("file", "r") as f:
line = f.readline()
except IOError:
<whatever>
If it is, then considering the old way of doing things:
try:
f = open("file", "r")
line = f.readline()
except IOError:
<whatever>
finally:
f.close()
Is the primary benefit of the "with" statement here that we can get rid of three lines of code? It doesn't seem that compelling to me for this use case (though I understand that the "with" statement has other uses).
EDIT: Is the functionality of the above two blocks of code identical?
EDIT2: The first few answers talk generally about the benefits of using "with", but those seem of marginal benefit here. We've all been (or should have been) explicitly calling f.close() for years. I suppose one benefit is that sloppy coders will benefit from using "with".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不等效
的做事有一个严重的bug:
如果打开文件失败
将得到第二个异常
finally
子句,因为f
不是边界。
等效的旧式代码如下:
如您所见,
with
语句可以减少出错的可能性。在较新版本的 Python(2.7、3.1)中,您还可以在一个with
语句中组合多个表达式。例如:除此之外,我个人认为尽早捕获异常是一个坏习惯。这不是例外的目的。如果可能失败的 IO 函数是更复杂操作的一部分,则在大多数情况下,IOError 应中止整个操作,因此在外部级别进行处理。使用
with
语句,您可以摆脱内部级别的所有这些try...finally
语句。not equivalent
of doing things has a serious bug:
in case opening the file fails you
will get a second exception in the
finally
clause becausef
is notbound.
The equivalent old style code would be:
As you can see, the
with
statement can make things less error prone. In newer versions of Python (2.7, 3.1), you can also combine multiple expressions in onewith
statement. For example:Besides that, I personally regard it as bad habit to catch any exception as early as possible. This is not the purpose of exceptions. If the IO function that can fail is part of a more complicated operation, in most cases the IOError should abort the whole operation and so be handled at an outer level. Using
with
statements, you can get rid of all thesetry...finally
statements at inner levels.如果
finally
块的内容是由正在打开的文件对象的属性决定的,为什么文件对象的实现者不应该是编写finally
的人堵塞? 这就是with
语句的好处,远不止在此特定实例中节省三行代码。是的,将
with
和try- except
结合起来的方式几乎是唯一的方法,因为open
中会导致异常错误code> 语句本身无法在with
块中捕获。If the contents of the
finally
block are determined by the properties of the file object being opened, why shouldn't the implementer of the file object be the one to write thefinally
block? That's the benefit of thewith
statement, much more than saving you three lines of code in this particular instance.And yes, the way you've combined
with
andtry-except
is pretty much the only way to do it, as exceptional errors caused within theopen
statement itself can't be caught within thewith
block.我认为你对“with”语句的理解是错误的,它只会减少行数。
它实际上进行初始化并处理拆卸。
在您的情况下,“with”确实
以下是理解“with”语句的链接:http://effbot.org/zone/ python-with-statement.htm
编辑:是的,您对“with”的使用是正确的,并且两个代码块的功能是相同的。
关于为什么使用“with”的问题?这是因为你从中获得的好处。就像你提到的不小心错过了 f.close() 。
I think you got it wrong about "with" statement that it only reduces lines.
It actually does initialization and handle teardown.
In your case "with" does
Here is link for understanding "with" statement : http://effbot.org/zone/python-with-statement.htm
Edit: Yes your usage of "with" is correct and functionality of both blocks of code is identical.
Question about why to use "with" ? it's because of benefits you get with it. like you mentioned about accidentally missing f.close().
下面的代码更Pythonic的方式是:
The more Pythonic way for the following codes is: