File: excepthook.py

package info (click to toggle)
python-friendly 0.7.21%2Bgit20230418.fe5d3a2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,268 kB
  • sloc: python: 2,291; makefile: 6
file content (61 lines) | stat: -rw-r--r-- 1,758 bytes parent folder | download
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
53
54
55
56
57
58
59
60
61
"""Automatically installs Friendly as a replacement for the standard traceback in IPython.

Used in IPython itself and other programming environments based on IPython such as
Jupyter, Google Colab, Mu's repl, etc.
"""

from friendly_traceback import (
    install,
    exclude_file_from_traceback,
    explain_traceback,
    uninstall,
)  # noqa

try:
    from IPython.core import compilerop, interactiveshell
except ImportError:
    raise ValueError("IPython cannot be imported.")
try:
    from IPython.utils import py3compat  # noqa
except ImportError:
    pass
else:
    exclude_file_from_traceback(py3compat.__file__)

exclude_file_from_traceback(interactiveshell.__file__)
exclude_file_from_traceback(compilerop.__file__)


original_exception_hooks = {}


def enable():
    """Installs friendly-traceback as an exception hook in IPython"""
    # save old values
    original_exception_hooks[
        "showtraceback"
    ] = interactiveshell.InteractiveShell.showtraceback
    original_exception_hooks[
        "showsyntaxerror"
    ] = interactiveshell.InteractiveShell.showsyntaxerror
    interactiveshell.InteractiveShell.showtraceback = (
        lambda self, *args, **kwargs: explain_traceback()
    )
    interactiveshell.InteractiveShell.showsyntaxerror = (
        lambda self, *args, **kwargs: explain_traceback()
    )
    install(include="friendly_tb")


def disable():
    if not original_exception_hooks:
        print("friendly is not installed.")
        return
    uninstall()
    interactiveshell.InteractiveShell.showtraceback = original_exception_hooks[
        "showtraceback"
    ]
    interactiveshell.InteractiveShell.showsyntaxerror = original_exception_hooks[
        "showsyntaxerror"
    ]
    original_exception_hooks.clear()