contextlib.suppress (* exceptions)
* exceptions - Types of exceptions that should be ignored.
Returns a context manager that will suppress the specified types of exceptions if they occur in during the execution of the instruction body with , while execution will continue from the code following the instruction.
Attention
Like any other mechanism for suppressing exceptions , the context manager mentioned should only be used in a very limited set of scenarios, when it is absolutely clear that program execution must continue.
import os
from contextlib import suppress
with suppress (FileNotFoundError):
os.remove (’somefile.tmp’)
# Equivalent:
try:
os.remove (’ somefile.tmp’)
except FileNotFoundError:
pass
The created manager object is reentrant . This means that within the same
with
block, which has the same nested blocks, it can be used several times: import os
from contextlib import suppress
remove_error_supressed = suppress (FileNotFoundError)
with remove_error_supressed:
os.remove (’somefile.tmp’)
with remove_error_supressed:
os.remove (’anotherfile.tmp’)