使用带有try-except块的python“with”语句

[英]Using python “with” statement with try-except block


Is this the right way to use the python "with" statement in combination with a try-except block?:

这是将python“with”语句与try-except块结合使用的正确方法吗?:

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).

这里“with”语句的主要好处是我们可以摆脱三行代码吗?对于这个用例来说,这似乎并不令我感到高兴(尽管我理解“with”语句还有其他用途)。

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".

EDIT2:前几个答案一般都谈到使用“with”的好处,但这些似乎在边缘带来了好处。我们已经(或者应该)多年来明确地调用f.close()。我想一个好处是,草率的编码员将从使用“with”中受益。

4 个解决方案

#1


118  

  1. The two code blocks you gave are not equivalent
  2. 您提供的两个代码块不相同
  3. The code you described as old way of doing things has a serious bug: in case opening the file fails you will get a second exception in the finally clause because f is not bound.
  4. 您描述为旧的处理方式的代码存在严重错误:如果打开文件失败,您将在finally子句中获得第二个异常,因为f未绑定。

The equivalent old style code would be:

等效的旧样式代码是:

try:
    f = open("file", "r")
    try:
        line = f.readline()
    finally:
        f.close()
except IOError:
    <whatever>

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 one with statement. For example:

正如您所看到的,with语句可以减少错误。在较新版本的Python(2.7,3.1)中,您还可以将多个表达式合并到一个语句中。例如:

with open("input", "r") as inp, open("output", "w") as out:
    out.write(inp.read())

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 these try...finally statements at inner levels.

除此之外,我个人认为尽早捕捉任何例外都是不好的习惯。这不是例外的目的。如果可能失败的IO功能是更复杂操作的一部分,则在大多数情况下,IOError应该中止整个操作,因此应在外层处理。使用with语句,你可以在内层删除所有这些try ... finally语句。

#2


6  

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 the finally block? That's the benefit of the with statement, much more than saving you three lines of code in this particular instance.

如果finally块的内容是由打开的文件对象的属性决定的,为什么文件对象的实现者不应该是写finally块的实现者?这是with语句的好处,远不止在这个特定实例中保存三行代码。

And yes, the way you've combined with and try-except is pretty much the only way to do it, as exceptional errors caused within the open statement itself can't be caught within the with block.

是的,你结合使用和try-except的方式几乎是唯一的方法,因为在open语句中引起的异常错误不能在with块中捕获。

#3


1  

I think you got it wrong about "with" statement that it only reduces lines. It actually does initialization and handle teardown.

我认为你对“with”声明说错了它只会减少线条。它实际上做了初始化和处理拆解。

In your case "with" does

在你的情况下“与”做

  • open a file,
  • 打开一个文件,
  • process its contents, and
  • 处理其内容,和
  • make sure to close it.
  • 一定要关闭它。

Here is link for understanding "with" statement : http://effbot.org/zone/python-with-statement.htm

以下是理解“with”声明的链接: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().

编辑:是的,您对“with”的使用是正确的,两个代码块的功能是相同的。关于为何使用“with”的问题?这是因为你得到的好处。就像你提到的意外丢失了f.close()。

#4


-2  

The more Pythonic way for the following codes is:

以下代码的Pythonic方式更多:

try:
    f = open("file", "r")
    try:
        line = f.readline()
    finally:
        f.close()
except IOError:
    <whatever>

try:
    f = open("file", "r")
except IOError:
    <whatever>
else:
    f.close()
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2010/09/04/94cf08e5fdcbe741f421e3a2c508a84d.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告