Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.suppress

Continues after a managed block when one of the specified exception types is raised.

Version: Python 3.14; repository image, production runtime not attested

Syntax

with contextlib.suppress(*exception_types):

Continues after a managed block when one of the specified exception types is raised.

Unlisted exception types propagate, so narrow exception selection preserves unrelated failures.

Ignore matching exception classes and subclasses for one block and resume after it. Other error types propagate. Since 3.12 matching leaves in an exception group can be removed, with a derived subgroup raised for the remainder. Here the missing key is ignored, but converting x to int raises ValueError outside the suppression policy.

from contextlib import suppress
try:
    with suppress(KeyError):
        raise ExceptionGroup("mixed", [KeyError("id"), ValueError("qty")])
except ExceptionGroup as group:
    assert len(group.exceptions) == 1 and isinstance(group.exceptions[0], ValueError)
else:
    raise AssertionError

Examples

import contextlib
with contextlib.suppress(KeyError):
    {}["x"]
print("continued")
try:
    with contextlib.suppress(KeyError):
        int("x")
except ValueError as error:
    print(type(error).__name__)

Result

continued
ValueError

Ignore matching exception classes and subclasses for one block and resume after it. Other error types propagate. Since 3.12 matching leaves in an exception group can be removed, with a derived subgroup raised for the remainder. Here the missing key is ignored, but converting x to int raises ValueError outside the suppression policy.

Sources