Test which exception a suppress block actually handles
Also published in our primary archive.
with suppress(KeyError): handles a KeyError raised in its body, not every failure in that body. Test the intended recoverable input and an unrelated invalid input so that a future broadening of the exception boundary is visible.
The example has two contrasting lookups. optional_code asks for "missing" in a dictionary containing only "present"; the resulting KeyError is expected, is suppressed, and the function returns the explicit fallback "absent". A lookup for "present" also returns its normal value. Separately, int("not-a-number") raises ValueError inside another suppress(KeyError) block. The except ValueError outside the block proves that this unexpected conversion failure propagated rather than being silently hidden.
The assertions establish this fixture’s exception boundary, not that suppressing a missing key is correct for every application. A fallback can conceal a misspelt required key, for example; make the fallback policy explicit and keep the with body narrow. contextlib.suppress has been in the standard library since Python 3.4. Its documentation cautions that complete suppression should be reserved for specific errors where continuing is known to be appropriate.
See the Python contextlib.suppress documentation.
AI-assistance disclosure: AI helped draft this synthetic example and explanation.
from contextlib import suppress
def optional_code(values, key):
with suppress(KeyError):
return values[key]
return "absent"
values = {"present": "P1"}
assert optional_code(values, "present") == "P1"
assert optional_code(values, "missing") == "absent"
try:
with suppress(KeyError):
int("not-a-number")
except ValueError:
conversion = "propagated"
else:
conversion = "incorrectly suppressed"
assert conversion == "propagated"
print(f"missing=absent value_error={conversion}")
missing=absent value_error=propagated