4. Use contextlib.suppress for narrow ignored exceptions
Use contextlib.suppress when a specific exception is expected and can be ignored cleanly.
A narrow suppress block documents that the exception is intentionally non-fatal in this specific operation. It is much safer than a broad try/except because the ignored surface area stays small and visible.
4.1. Don’t do this
1try:
2 cache.pop('expired')
3except KeyError:
4 pass
4.2. Do this
1from contextlib import suppress
2
3with suppress(KeyError):
4 cache.pop('expired')