Skip to content

Commit

Permalink
fix: Fix implicit modules in IPython shells (#662)
Browse files Browse the repository at this point in the history
Fixes #661
  • Loading branch information
mark-koch authored Nov 25, 2024
1 parent bb2ca83 commit 4ecb5f2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
10 changes: 6 additions & 4 deletions guppylang/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@
from guppylang.definition.struct import RawStructDef
from guppylang.definition.ty import OpaqueTypeDef, TypeDef
from guppylang.error import MissingModuleError, pretty_errors
from guppylang.ipython_inspect import get_ipython_globals, is_running_ipython
from guppylang.ipython_inspect import (
get_ipython_globals,
is_ipython_dummy_file,
is_running_ipython,
)
from guppylang.module import (
GuppyModule,
PyClass,
Expand Down Expand Up @@ -154,10 +158,8 @@ def _get_python_caller(self, fn: PyFunc | None = None) -> ModuleIdentifier:
# Jupyter notebook cells all get different dummy filenames. However,
# we want the whole notebook to correspond to a single implicit
# Guppy module.
# TODO: Find a better way to detect if `filename` is a dummy name
# generated by Jupyter
filename = info.filename
if is_running_ipython() and not module and "ipykernel" in filename:
if is_running_ipython() and not module and is_ipython_dummy_file(filename):
filename = _JUPYTER_NOTEBOOK_MODULE
module_path = Path(filename)
return ModuleIdentifier(
Expand Down
12 changes: 12 additions & 0 deletions guppylang/ipython_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,18 @@ def is_running_ipython() -> bool:
return False


def is_ipython_dummy_file(filename: str) -> bool:
"""Checks whether a given filename is a dummy name generated for an IPython cell."""
# TODO: The approach below is false-positive prone. Figure out if there is a better
# way to do this.
return (
# IPython cells have filenames like "<ipython-input-3-3e9b5833de21>"
filename.startswith("<ipython-input-")
# Jupyter cells have filenames like "/var/{...}/ipykernel_82076/61218616.py"
or "ipykernel_" in filename
)


def get_ipython_cell_sources() -> list[str]:
"""Returns the source code of all cells in the running IPython session.
Expand Down

0 comments on commit 4ecb5f2

Please sign in to comment.