Suppress Only Expected Exceptions
Core idea
A truthy exit result suppresses the exception passed to it. Return False for unexpected failures. contextlib.suppress provides a concise option for specifically named exception types, including subclasses.
from contextlib import suppresssettings = {}with suppress(KeyError): print(settings["label"])print("continue")The block stops at KeyError; execution continues after it.
Preserve unrelated failures
from contextlib import suppresstry: with suppress(KeyError): int("broken")except ValueError: print("unexpected input")ValueError is outside the chosen suppression policy.
Common mistake
Do not wrap a large operation in broad suppression. Keep the protected block small and suppress only an explicitly acceptable failure. Suppression skips the remaining statements in that block.
Practice
Use suppress for an optional dictionary key, then demonstrate that an unrelated TypeError still propagates.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Narrow suppression
Check your understanding of exception suppression.
What is printed?
from contextlib import suppresswith suppress(KeyError): raise KeyError("x") print("inside")print("after")Which exception propagates?
from contextlib import suppresswith suppress(KeyError): int("x")Which __exit__ return suppresses a pending error?
Which scope is best for suppress?