为什么要使用 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
>>>
最佳答案
它在不牺牲可读性的情况下减少了两行代码。
对于嵌套或连续的代码块可能特别方便。比较:
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
说做某事,如果出现错误,不要传播错误
它不太重要,因为大多数人不会注意到差异。
关于python - 为什么使用 contextlib.suppress 而不是 try/except 和 pass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34566806/