Python
Python ·1 min read 02

Handling exceptions with contextlib

Handling exceptions with contextlib

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: