Handling exceptions with contextlib

Posted by Tobiasz Kedzierski on 27.02.2019

Handling exceptions with contextlib.supress()

import contextlib

with contextlib.suppress(FileNotFoundError):
    os.remove("somefile.tmp")

This is equivalent to the following try/except clause:

try:
    os.remove("somefile.tmp")
except FileNotFoundError:
    pass



Sources: