【发布时间】:2016-04-06 15:05:18
【问题描述】:
为什么要使用contextlib.suppress 来抑制异常,而不是使用try/except 和pass?
这两种方法在字符数量上没有区别(如果有的话,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