【问题标题】:Why use contextlib.suppress as opposed to try/except with pass?为什么使用 contextlib.suppress 而不是 try/except 和 pass?
【发布时间】:2016-04-06 15:05:18
【问题描述】:

为什么要使用contextlib.suppress 来抑制异常,而不是使用try/exceptpass

这两种方法在字符数量上没有区别(如果有的话,suppress 有更多字符),即使代码经常以 LOC 而非字符来计算,suppress 似乎也慢得多比try/except 在这两种情况下,无论何时都会引发错误:

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from timeit import timeit
>>> # With an error
>>> timeit("""with suppress(ValueError):
    x = int('a')""", setup="from contextlib import suppress")
1.9571568971892543
>>> timeit("""try:
    x = int('a')
except ValueError:
    pass""")
1.0758466499161656
>>> # With no error
>>> timeit("""with suppress(ValueError):
    x = int(3)""", setup="from contextlib import suppress")
0.7513525708063895
>>> timeit("""try:
    x = int(3)
except ValueError:
    pass""")
0.10141028937128027
>>> 

【问题讨论】:

  • 它节省了两行。如果你有几个这样的连续块,它会大大提高可读性
  • 同样,当您可以使用 for 循环时,为什么还要使用 any()all()?我认为使用contextlib.suppress 有助于提高可读性和维护性。
  • @SimeonVisser any()all() clearly 使代码更短,无论是行还是字符。我也很确定any()all() 在性能方面比for 循环更快。据我所知,使用suppress 的唯一原因是它更具可读性(而且这值得商榷,因为它需要更多字符)。另一方面,使用try/except 要快得多
  • 确实如此。也许它与进行函数式编程有关(即,在某些情况下传递 contextlib.suppress 以有条件地抑制异常,但在其他情况下则没有)?

标签: python python-3.x


【解决方案1】:

它在不牺牲可读性的情况下减少了两行代码。

对于嵌套或连续的代码块可能特别方便。比较:

try:
    a()
    try:
        b()
    except B:
        pass
except A:
    pass

对比:

with suppress(A):
    a()
    with suppress(B):
        b()

它还允许表达意图:

  • with suppress(SpecificError): do_something()如果在做某事时引发错误,请不要传播该错误
  • try: do_something() except SpecificError: pass做一些事情,如果出现错误,不要传播错误

它不太重要,因为大多数人不会注意到差异。

【讨论】:

    【解决方案2】:

    从概念上讲,对我来说, contextlib.suppress 方法允许我处理可能发生的错误(例如尝试删除可能实际上不存在的文件)。然后 try/except 成为对“这不应该发生”事件的更积极处理(例如除以 0 或无法打开我想要写入的一些事件)。

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      相关资源
      最近更新 更多