suppress Swallows Expected Exceptions Only

contextlib.suppress swallows only the listed exception types while anything else still propagates, replacing bare except blocks with stated intent.

PythonResilience

Code

pythonsnippet
20 lines
from contextlib import suppress

config: dict = {}

# an expected absence: one line says "skip it if it is not there", no bare except needed
with suppress(KeyError):
    print("theme:", config["theme"])

with suppress(FileNotFoundError):
    with open("definitely-missing.cfg", encoding="utf-8") as handle:
        print("loaded:", handle.readline())

print("run continues after suppressed errors")

# only the listed types are swallowed: every other exception propagates untouched
try:
    with suppress(KeyError):
        raise ValueError("not on the list")
except ValueError as exc:
    print("ValueError escapes suppress:", exc)

Inside the snippet

The suppress blocks only swallow the types they list (KeyError, FileNotFoundError) — the ValueError raised inside one still propagates and lands in the except ValueError handler.

Top-level bindings config hold the demo state — nothing sits inside a function scope.

Putting it to use

The run emits 4 labeled sections — theme:, loaded:, run continues after suppressed errors, ValueError escapes suppress: — one per step.

Core lines

with open("definitely-missing.cfg", encoding="utf-8") as handle:
    print("loaded:", handle.readline())
except ValueError as exc:
    print("ValueError escapes suppress:", exc)
with suppress(KeyError):
    print("theme:", config["theme"])

Interactive Tools for This Topic

FAQ

Does `suppress` catch everything?
No — only the types it lists (`KeyError`, `FileNotFoundError`). The `ValueError` raised inside the block still propagates and is caught by the `except ValueError` handler.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `config`.