为什么要使用
这两种方法的字符数没有区别(如果有区别的话,
contextlib.suppress
来压制异常,而不是用 try
/except
和 pass
?这两种方法的字符数没有区别(如果有区别的话,
suppress
字符更多),尽管代码通常按行数计算,但无论何时发生错误或未发生错误,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
>>>
any()
或all()
,而不是使用for循环呢?我认为使用contextlib.suppress
有助于提高可读性和维护性。 - Simeon Visserany()
和all()
显然可以使代码更短,无论是在行数上还是字符数上。我也非常确定any()
和all()
在性能方面比for
循环更快。就我所见,使用suppress
的唯一原因是它更易读(即使这也是有争议的,因为它需要更多的字符)。另一方面,使用try/except
则要快得多。 - Markus Meskanencontextlib.suppress
来有条件地抑制异常,而在其他情况下则不抑制)? - Simeon Visser