Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Suppressing Exceptions in Python with contextlib.suppress

Learn how to use contextlib.suppress in Python to ignore expected exceptions, pass multiple exception types, and decide when try/except gives you more control.

~3 min readPython
#Python#contextlib#exception handling#context managers
Illustration of a Python context manager acting as a shield that deflects one specific exception while other exceptions pass through.

Python's contextlib.suppress context manager lets you ignore specific exceptions inside a block. Instead of writing a try/except block that catches an exception and does nothing, you can wrap the code in with suppress(SomeError):.

python
from contextlib import suppress import os with suppress(FileNotFoundError): os.remove("temp.txt")

This is equivalent to:

python
import os try: os.remove("temp.txt") except FileNotFoundError: pass

The suppress manager accepts one or more exception types. If any of those exceptions is raised inside the block, it is caught and execution continues normally after the with statement. Any other exception propagates as usual.

Passing Multiple Exception Types

You can pass several exception classes at once:

python
from contextlib import suppress import shutil with suppress(FileNotFoundError, PermissionError): shutil.rmtree("/tmp/cache")

The context manager catches only the specified exceptions and returns normally. A TypeError or ValueError raised in the same block will still propagate to the caller.

Why suppress Is Not a Replacement for try/except

suppress is designed for cases where you explicitly want to ignore an exception and continue. It is not a general-purpose exception handler. You cannot inspect the exception object, log it, or perform cleanup based on it. If you need any of that, a regular try/except block is the correct tool.

Unlike except ValueError as exc:, suppress does not expose the exception to your code:

python
from contextlib import suppress with suppress(ValueError): int("not-a-number") # No exception variable is available here.

The context manager simply swallows the exception. If you need to log the failure, retry the operation, or take a different branch based on the exception, use try/except instead.

Common Use Cases

The most natural use cases are cleanup operations and optional resource handling:

  • Removing files that may not exist
  • Closing a connection that may already be closed
  • Removing an optional key from a dictionary
  • Ignoring TimeoutError in a non-critical background check
python
from contextlib import suppress config = {"retries": 3} with suppress(KeyError): del config["retries"]

This pattern reads clearly: "try to remove this value, but it is fine if it is already absent." The intent is more explicit than an empty except block, which a reader might mistake for unfinished work.

When suppress Hides Real Problems

The main risk is overuse. Suppressing an exception without any logging can hide bugs. If the operation fails for an unexpected reason, the program continues silently, and the failure may surface much later in an unrelated part of the code.

For example, suppressing PermissionError when deleting a file might hide a permission configuration problem that should be fixed. A better approach is to suppress only the narrow exception you expect, and let everything else propagate.

python
from contextlib import suppress import os with suppress(FileNotFoundError): os.remove("data.csv")

Here only FileNotFoundError is suppressed. A PermissionError or another OSError will still raise, which is usually the desired behavior.

Runtime and Maintainability Considerations

contextlib.suppress is a small context manager, but the decision to use it should be based mostly on readability and maintainability, not performance. In a long-lived codebase, consider whether the suppressed exception should be logged. If the operation is expected to fail occasionally, suppressing it without a comment may confuse future maintainers.

A short comment explaining why the exception is expected is often worth adding:

python
from contextlib import suppress import os # The file may have been cleaned up by another worker. with suppress(FileNotFoundError): os.remove(f"/tmp/job-{job_id}.lock")

Compatibility Notes

contextlib.suppress was added in Python 3.4, so it is available in current Python releases without a third-party package.

One boundary to remember: the exception is suppressed only if it is raised inside the with block. If the exception is raised in the __enter__ method of the context manager itself, suppress does not catch it. This is rarely relevant in practice, but it is a subtle point worth knowing when you nest context managers.

Choosing Between suppress and try/except

Use suppress when:

  • The exception is expected and harmless
  • You do not need to log or inspect it
  • The block is short and the intent is obvious

Use try/except when:

  • You need the exception object
  • You need to log or alert
  • The error handling involves multiple steps
  • The exception might indicate a real bug

The decision is not about style. It is about whether the exception carries information you need. If it does, suppress is the wrong tool. If the exception is genuinely irrelevant to the outcome, suppress keeps the code shorter and makes the intent explicit.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.