Python 3.4+contextlibterm
contextlib.suppress
exceptions
Suppresses the given exceptions. The equivalent of try/except pass, but shorter and easier to read.
Syntax
contextlib.suppress(*exceptions)
with suppress(FileNotFoundError):
os.remove('file')
The main trap: the exception skips the rest of the with block, not just one line — execution resumes after the block, so do not stack several steps inside if the later ones must run. Subclasses of the listed exceptions are suppressed too, so suppress(Exception) will swallow everything, including a typo in a variable name. Use it only where silently continuing is provably the right behaviour.
Examples
import os
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('/nonexistent_file') # исключение подавлено
print('Continued normally') # → Continued normally
from contextlib import suppress
with suppress(KeyError):
d = {'a': 1}
print(d['missing']) # KeyError подавлен — печати нет
print('недостижимо')
print('ok') # → ok — блок прерван на первой ошибке
# Эквивалент через try/except
import os
try:
os.remove('no_file')
except FileNotFoundError:
pass
See also
Open in the full glossarydocs.python.orgReport an inaccuracy