-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsuppress_traceback.py
More file actions
52 lines (40 loc) · 1.63 KB
/
suppress_traceback.py
File metadata and controls
52 lines (40 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
Context manager to suppress the traceback output when an exception is raised.
The previous traceback limit is returned when exiting the context manager.
"""
import sys
from typing import TYPE_CHECKING, override
if TYPE_CHECKING:
from collections.abc import Sequence
from types import TracebackType
__all__: "Sequence[str]" = ("SuppressTraceback",)
class SuppressTraceback:
"""
Context manager to suppress the traceback output when an exception is raised.
The previous traceback limit is returned when exiting the context manager.
"""
@override
def __init__(self) -> None:
"""
Initialise a new SuppressTraceback context manager instance.
The current value of `sys.tracebacklimit` is stored for future reference to revert to
upon exiting the context manager.
"""
self.previous_traceback_limit: int | None = getattr(sys, "tracebacklimit", None)
def __enter__(self) -> None:
"""Enter the context manager, suppressing the traceback output."""
sys.tracebacklimit = 0
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: "TracebackType | None", # noqa: PYI036
) -> None:
"""Exit the context manager, reverting the limit of traceback output."""
if exc_type is not None or exc_val is not None or exc_tb is not None:
return
if hasattr(sys, "tracebacklimit"):
if self.previous_traceback_limit is None:
del sys.tracebacklimit
else:
sys.tracebacklimit = self.previous_traceback_limit