snippetpythonTippending
Python contextlib.suppress for clean exception ignoring
Viewed 0 times
suppresscontextlibexceptionignoretry-except
Problem
Try/except/pass blocks are noisy and hide intent when you just want to ignore specific exceptions.
Solution
Use contextlib.suppress to cleanly ignore expected exceptions:
from contextlib import suppress
# Instead of:
try:
os.remove('temp.txt')
except FileNotFoundError:
pass
# Use:
with suppress(FileNotFoundError):
os.remove('temp.txt')
# Multiple exception types:
with suppress(FileNotFoundError, PermissionError):
os.remove('temp.txt')
from contextlib import suppress
# Instead of:
try:
os.remove('temp.txt')
except FileNotFoundError:
pass
# Use:
with suppress(FileNotFoundError):
os.remove('temp.txt')
# Multiple exception types:
with suppress(FileNotFoundError, PermissionError):
os.remove('temp.txt')
Why
suppress() makes the intent clear: we know this might fail and we don't care. It's more readable than try/except/pass.
Revisions (0)
No revisions yet.