On this page
contextlib.suppress
Prev: contextlib.redirect_stdout | Up: contextlib
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.suppress
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import suppress
Signature & Overview
contextlib.suppress(*exceptions)
Context manager to suppress specified exceptions After the exception is suppressed, execution proceeds with the next statement following the with statement.
Usage
from contextlib import suppress
from pathlib import Path
with suppress(FileNotFoundError):
Path("definitely_nonexistent_temp_file_xyz").unlink()
Gotchas
- Cleaner than
try: ... except Err: pass: Only use when ignoring the exception is genuinely intentional. - Keep the
withbody minimal: Wrapping many lines insuppress(KeyError)can accidentally silence an unrelatedKeyErroryou wanted to see.
REPL Inspect
from contextlib import suppress
help(suppress)
Linked from
Related notes
- tuts/python3/stdlib_module/contextlib/redirect_stdout Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/asynccontextmanager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AsyncExitStack shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/chdir shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/closing shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/ContextDecorator shared tags: #contextlib, #stdlib