Use contextlib.suppress(*exceptions) (with contextlib.suppress(FileNotFoundError): os.remove("temp.txt")) from Python’s built-in contextlib module to cleanly ignore specific, expected exceptions without writing boilerplate try ... except SomeError: pass blocks.
Basic Example
from contextlib import suppress
import os
# 1. Recommended: Ignore a single expected exception cleanly
with suppress(FileNotFoundError):
os.remove("cache.tmp")
# 2. Ignore multiple expected exception types in a single context manager:
raw_items = ["42", "invalid", None, "99"]
parsed = []
for item in raw_items:
with suppress(ValueError, TypeError):
parsed.append(int(item))
print(parsed)
# Output: [42, 99]
Key Details & Edge Cases
- Never wrap an entire
forloop inside a singlewith suppress(...)block:- Because
suppress()acts as a context manager (__exit__catches the exception and exits thewithblock immediately), placing a loop insidewith suppress(...)aborts the remaining loop iterations on the first exception. Always placewith suppress(...)inside the loop body when skipping individual failing items.
- Because
- Only pass narrow, specific exception classes—never
ExceptionorBaseException:- Writing
with suppress(Exception):silently swallows unexpected bugs (TypeError,AttributeError,KeyError), making failures invisible. Always list the exact expected failure modes (e.g.,FileNotFoundError,KeyError,ValueError,ProcessLookupError). - Never suppress
BaseExceptionorKeyboardInterrupt/SystemExit, which would preventCtrl+Corsys.exit()from terminating your program.
- Writing
- When
try / exceptis still required instead ofcontextlib.suppress:suppress()strictly discards the exception (equivalent toexcept Exc: pass). Use a standardtry ... except Exc as err:block whenever you need to log the error, inspecterr, execute fallback/cleanup logic in theexcepthandler, or use anelse:branch that runs only when no exception occurred.
- Idiomatic single-call alternatives that avoid exceptions altogether:
- Often a built-in API already handles the missing case without raising an exception:
- Deleting a file if it exists:
Path("cache.tmp").unlink(missing_ok=True)(Python 3.8+). - Removing a dictionary key if present:
my_dict.pop("key", None)instead ofwith suppress(KeyError): del my_dict["key"]. - Removing a set element if present:
my_set.discard(item)instead ofwith suppress(KeyError): my_set.remove(item). - Creating a directory if it doesn’t exist:
Path("logs").mkdir(parents=True, exist_ok=True)instead ofwith suppress(FileExistsError): os.mkdir("logs").
- Deleting a file if it exists:
- Often a built-in API already handles the missing case without raising an exception:
Comparison of Approaches for Ignoring Expected Exceptions in Python
| Approach | Lines of Code | Allows Logging / Fallback Action? | Readability & Intent Clarity | Best Used When |
|---|---|---|---|---|
with contextlib.suppress(Exc1, Exc2): (Recommended) |
2 lines | No (pure no-op suppression) | Highest (explicitly states intent at top of block) | Ignoring expected, harmless exceptions (FileNotFoundError, KeyError, ValueError) where no recovery action is needed. |
Built-in safe APIs (unlink(missing_ok=True), dict.pop(k, None)) |
1 line | No | Highest (avoids exception unwinding overhead) | Standard file, directory, dictionary, or set operations that natively offer non-raising methods. |
try: ... except Exc: pass |
4 lines | Yes (if pass is replaced with handler code) |
Good, though slightly noisier than suppress() |
Codebases on restricted imports or blocks where you plan to add logging/metrics later. |
with suppress(Exception): (Avoid) |
2 lines | No | Dangerous (hides real bugs) | Never use—catches unintended programming errors (NameError, TypeError, AttributeError) silently. |
You must log in or register to comment.
