Contextlib Suppress For Expected Errors
Silence only the specific exception you expect with contextlib.suppress, keeping every other failure loud.
Code
import json
from contextlib import suppress
def parse_optional(raw: str) -> dict | None:
# 只吞 JSON 解析失败:其余异常照常抛出
with suppress(json.JSONDecodeError):
return json.loads(raw)
return None
def remove_quietly(path: str) -> bool:
import os
# 只吞"文件不存在":权限等其他错误继续传播
with suppress(FileNotFoundError):
os.remove(path)
return True
return False
def main() -> None:
print(parse_optional('{"a":1}'))
print(parse_optional('not json'))
print('removed:', remove_quietly('/tmp/definitely-missing-file.txt'))
# 反例:suppress(Exception) 会把真实缺陷也吞掉
try:
with suppress(ZeroDivisionError):
_ = 1 / 0
print('suppressed as expected')
except Exception as exc:
print('unexpected:', exc)
if __name__ == '__main__':
main()Output
Captured from a sandboxed run of this snippet in the build pipeline.
{'a': 1}
None
removed: False
suppressed as expectedHow it works
Contextlib Suppress For Expected Errors reduces to the functions parse_optional, remove_quietly and main.
Using it
The primary signature is def parse_optional(raw: str) -> dict | None
The demo output is labeled (removed:, suppressed as expected), so every printed line maps back to its originating operation.
The entry point wires parse_optional and remove_quietly together — run it once and the whole demo flows.
Key statements
def parse_optional(raw: str) -> dict | None:
# 只吞 JSON 解析失败:其余异常照常抛出
with suppress(json.JSONDecodeError):
return json.loads(raw)
return None
def remove_quietly(path: str) -> bool:
import os
# 只吞"文件不存在":权限等其他错误继续传播
with suppress(FileNotFoundError):
os.remove(path)
return True
return False
with suppress(ZeroDivisionError):
_ = 1 / 0
Interactive Tools for This Topic
FAQ
- What does Contextlib Suppress For Expected Errors print when run?
- Invoke the file as-is — the `removed:`, `suppressed as expected` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.