ups and downs
Essay · Python

Handling exceptions with contextlib

Handling exceptions with contextlib

1 min read

From 2019Written in 2019. The ideas may still hold, but check the current docs for newer details.

Handling exceptions with contextlib.supress()

python
import contextlib

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

This is equivalent to the following try/except clause:

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


Sources:

More essays on Python

All essays →