Skip to content

Use `contextlib.suppress`

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: use-contextlib-suppress

Section titled “Sourcery refactoring id: use-contextlib-suppress”

Use contextlib’s suppress method to silence a specific error, instead of passing in an exception handler. This refactoring will add an import for contextlib if needed.

try:
travel_world(days=80)
except DistractionError:
pass
import contextlib
with contextlib.suppress(DistractionError):
travel_world(days=80)

The context manager slightly shortens the code and significantly clarifies the author’s intention to ignore the specific errors. The standard library feature was introduced following a discussion, where the consensus was that

A key benefit here is in the priming effect for readers… The with statement form makes it clear before you start reading the code that certain exceptions won’t propagate.