Mar*_*nen 23 python python-3.x
为什么人会使用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
>>>
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 18
在不牺牲可读性的情况下,它可以减少两行代码.
对于嵌套或连续的代码块,它可能特别方便.相比:
try:
a()
try:
b()
except B:
pass
except A:
pass
Run Code Online (Sandbox Code Playgroud)
VS:
with suppress(A):
a()
with suppress(B):
b()
Run Code Online (Sandbox Code Playgroud)
它还允许表达意图:
with suppress(SpecificError): do_something()说,如果同时做一些提出不传播错误try: do_something() except SpecificError: pass说做某事,如果提出错误就不传播错误它不那么重要,因为大多数人都不会注意到这种差异.
从概念上讲,对我来说,contextlib.suppress 方法允许我处理可能发生的错误(例如尝试删除实际上可能不存在的文件)。try/except 然后变得更积极地处理“这不应该发生”事件(例如除以 0 或无法打开一些我想写入的事件)。
| 归档时间: |
|
| 查看次数: |
4099 次 |
| 最近记录: |