使用python"with"带有try-except块的语句 [英] Using python "with" statement with try-except block

查看:551
本文介绍了使用python"with"带有try-except块的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这里的"with"语句的主要好处是我们可以摆脱三行代码吗?在这个用例中,对我来说似乎没有什么吸引力(尽管我知道"with"语句还有其他用途).

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

以上两个代码块的功能是否相同?

Is the functionality of the above two blocks of code identical?

前几个答案大体上谈及了使用"with"的好处,但在这里似乎没有什么好处.我们已经(或应该已经)明确地调用f.close()多年了.我想一个好处是草率的编码器将从使用"with"中受益.

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

推荐答案

  1. 您给出的两个代码块是 不等同
  2. 您描述为旧方式的代码 做事有一个严重的错误: 万一打开文件失败 将会在 finally子句,因为f不是 绑定.
  1. The two code blocks you gave are not equivalent
  2. 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.

等效的旧样式代码为:

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

如您所见,with语句可以使事情少出错.在较新版本的Python(2.7,3.1)中,您还可以在一个with语句中组合多个表达式.例如:

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 open("input", "r") as inp, open("output", "w") as out:
    out.write(inp.read())

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

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.

这篇关于使用python"with"带有try-except块的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆