contextlib.suppress(*exceptions)
- Return a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution
with
the first statement following the end of thewith
statement.
As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.
与完全抑制异常的任何其他机制一样,该上下文管理器应当只用来抑制非常具体的错误,并确保该场景下静默地继续执行程序是通用的正确做法.
# In Python 3.4+ you can use
# contextlib.suppress() to selectively
# ignore specific exceptions:
import contextlib
with contextlib.suppress(FileNotFoundError):
os.remove('somefile.tmp')
# This is equivalent to:
try:
os.remove('somefile.tmp')
except FileNotFoundError:
pass
# contextlib.suppress docstring:
#
# "Return a context manager that suppresses any
# of the specified exceptions if they occur in the body
# of a with statement and then resumes execution with
# the first statement following the end of
# the with statement."
# For example:
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('somefile.tmp')
with suppress(FileNotFoundError):
os.remove('someotherfile.tmp')
# This code is equivalent to:
try:
os.remove('somefile.tmp')
except FileNotFoundError:
pass
try:
os.remove('someotherfile.tmp')
except FileNotFoundError:
pass
# This context manager is [reentrant](https://docs.python.org/3/library/contextlib.html#reentrant-cms).