Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix implicit modules in IPython shells #662

Merged
merged 1 commit into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
)
Comment on lines +15 to +24
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not really happy with this, but I don't know a better way to solve this problem :/



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

Expand Down
Loading