Hi Pythonistas!
Sometime we have to silently ignore the exceptions in our code, For that we are mostly using try except and in the exception block we add add a pass. Today were learning more pythonic way for silently ignore the execptions.contextlib.suppress() is a context manager introduced in Python 3.4 that allows you to suppress (ignore) specific exceptions during the execution of a code block without writing verbose try except statements.
It lives in the contextlib module and is often used when you know an exception might happen and you don't want to handle it you just want to ignore it.
code
from contextlib import suppress
with suppress(FileNotFoundError):
open("somefile.txt")
You can also suppress multiple exception types
from contextlib import suppress
with suppress(FileNotFoundError, PermissionError):
open("somefile.txt")
you can also combine with another context manager block
from contextlib import suppress
with suppress(FileNotFoundError):
with open('optional_config.txt') as f:
config=f.read()
with suppress the code more cleaner than
try:
with open('optional_config.txt') as f:
config=f.read()
except FileNotFoundError:
pass
When Not to Use suppress()
- When you need to log the error — use try/except instead.
- When the exception might indicate a bug or unexpected state.
- When you plan to handle the exception in a meaningful way.
When to Use It
- Optional cleanup (e.g., delete a file if it exists).
- Optional feature loading (e.g., import optional modules).
- Silently skipping known, acceptable exceptions.
You can combine suppress() with loops or other context managers:
from contextlib import suppress
for filename in ["a.txt", "b.txt", "c.txt"]:
with suppress(FileNotFoundError):
os.remove(filename)
contextlib.suppress() provides a clean, readable way to ignore exceptions you know can occur.Best used for safe-to-ignore, non-critical exceptions. Makes your code shorter and easier to read.