Skip to content

Commit

Permalink
fix: Use correct hook for error printing inside jupyter notebooks (#324)
Browse files Browse the repository at this point in the history
Fixes #323
  • Loading branch information
mark-koch authored Jul 25, 2024
1 parent 6698b75 commit bfdb003
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions guppylang/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,29 @@ class InternalGuppyError(Exception):
@contextmanager
def exception_hook(hook: ExceptHook) -> Iterator[None]:
"""Sets a custom `excepthook` for the scope of a 'with' block."""
old_hook = sys.excepthook
sys.excepthook = hook
yield
sys.excepthook = old_hook
try:
# Check if we're inside a jupyter notebook since it uses its own exception
# hook. If we're in a regular interpreter, this line will raise a `NameError`
ipython_shell = get_ipython() # type: ignore[name-defined]

def ipython_excepthook(
shell: Any,
etype: type[BaseException],
value: BaseException,
tb: TracebackType | None,
tb_offset: Any = None,
) -> Any:
return hook(etype, value, tb)

ipython_shell.set_custom_exc((GuppyError,), ipython_excepthook)
yield
ipython_shell.set_custom_exc((), None)
except NameError:
# Otherwise, override the regular sys.excepthook
old_hook = sys.excepthook
sys.excepthook = hook
yield
sys.excepthook = old_hook


def format_source_location(
Expand Down

0 comments on commit bfdb003

Please sign in to comment.