Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: enhance `ImportError` handling for better package suggestions (#5281)

Trevor Manz66ef42c5ac27
diff --git a/marimo/_runtime/packages/import_error_extractors.py b/marimo/_runtime/packages/import_error_extractors.py
new file mode 100644
index 0000000000..698fa4bc46
--- /dev/null
+++ b/marimo/_runtime/packages/import_error_extractors.py
@@ -0,0 +1,120 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+import re
+
+
+def extract_missing_module_from_cause_chain(
+ error: ImportError,
+) -> str | None:
+ """Traverse an `ImportError` cause chain maybe find a missing module name.
+
+ This handles cases where a `ModuleNotFoundError` was raised and then wrapped,
+ e.g., via `raise ImportError("helpful message") from err`
+ """
+ current: None | BaseException = error
+ while current is not None:
+ if (
+ isinstance(current, ModuleNotFoundError)
+ and hasattr(current, "name")
+ and current.name
+ ):
+ return current.name
+ current = current.__cause__
+ return None
+
+
+def strip_quotes(s: str) -> str:
+ if len(s) >= 2 and s[0] == s[-1] and s[0] in {"'", '"'}:
+ return s[1:-1]
+ return s
+
+
+def extract_packages_from_pip_install_suggestion(
+ message: str,
+) -> list[str] | None:
+ """Extract package names from pip install commands in error messages."""
+
+ # First try to find quoted/backticked pip install commands (complete commands)
+ quoted_patterns = [
+ r"`pip install\s+([^`]+)`", # backticks
+ r'"pip install\s+([^"]+)"', # double quotes
+ r"'pip install\s+([^']+)'", # single quotes
+ ]
+
+ for pattern in quoted_patterns:
+ match = re.search(pattern, message, re.IGNORECASE)
+ if match:
+ args_part = match.group(1)
+ args = args_part.split()
+ packages = []
+ seen = set()
+
+ for arg in args:
+ # Could be `pip install "foo[extra1,extra2]"`
+ arg = strip_quotes(arg)
+ # Skip flags and duplicates
+ if not arg.startswith("-") and arg not in seen:
+ packages.append(arg)
+ seen.add(arg)
+
+ if packages:
+ return packages
+
+ # Look for pip install with quoted individual packages
+ individual_quoted_pattern = r'pip install\s+"([^"]+)"'
+ match = re.search(individual_quoted_pattern, message, re.IGNORECASE)
+ if match:
+ return [match.group(1)]
+
+ # If no quoted command found, look for unquoted and take only first positional arg
+ unquoted_pattern = (
+ r"pip install\s+([a-zA-Z0-9_.-]+(?:\[[a-zA-Z0-9_,.-]+\])?)"
+ )
+
+ match = re.search(unquoted_pattern, message, re.IGNORECASE)
+
+ if match:
+ return [match.group(1)]
+
+ return None
+
+
+def extract_packages_special_cases(message: str) -> list[str] | None:
+ """Extract package names based on special case substrings in error messages."""
+
+ special_cases = {
+ # pd.DataFrame.to_parquet()
+ "Unable to find a usable engine; tried using: 'pyarrow', 'fastparquet'.": [
+ "pyarrow"
+ ],
+ }
+
+ packages = []
+ for substring, package_names in special_cases.items():
+ if substring in message:
+ packages.extend(package_names)
+
+ return packages if packages else None
+
+
+def try_extract_packages_from_import_error_message(
+ import_error_message: str,
+) -> list[str] | None:
+ """Try to extract package names from an `ImportError` message using various strategies.
+
+ Args:
+ import_error_message: The error message
+
+ Returns:
+ List of package names if found, None otherwise
+ """
+
+ for extract in [
+ extract_packages_from_pip_install_suggestion,
+ extract_packages_special_cases,
+ ]:
+ result = extract(import_error_message)
+ if result is not None:
+ return result
+ return None
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 391066104e..d23f8c4aa1 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -105,6 +105,10 @@ from marimo._runtime.context.kernel_context import (
from marimo._runtime.context.types import teardown_context
from marimo._runtime.control_flow import MarimoInterrupt
from marimo._runtime.input_override import input_override
+from marimo._runtime.packages.import_error_extractors import (
+ extract_missing_module_from_cause_chain,
+ try_extract_packages_from_import_error_message,
+)
from marimo._runtime.packages.module_registry import ModuleRegistry
from marimo._runtime.packages.package_manager import PackageManager
from marimo._runtime.packages.package_managers import create_package_manager
@@ -2416,7 +2420,7 @@ class PackagesCallbacks:
module_not_found_errors = [
e
for e in runner.exceptions.values()
- if isinstance(e, (ModuleNotFoundError, ManyModulesNotFoundError))
+ if isinstance(e, (ImportError, ManyModulesNotFoundError))
]
if len(module_not_found_errors) == 0:
@@ -2428,23 +2432,36 @@ class PackagesCallbacks:
missing_modules: set[str] = set()
missing_packages: set[str] = set()
- # Populate missing_modules and missing_packages
- # from the errors
+ # Populate missing_modules and missing_packages from the errors
for e in module_not_found_errors:
if isinstance(e, ManyModulesNotFoundError):
# filter out packages that we already attempted to install
# to prevent an infinite loop
missing_packages.update(
{
- package
- for package in e.package_names
- if not self.package_manager.attempted_to_install(
- package
- )
+ pkg
+ for pkg in e.package_names
+ if not self.package_manager.attempted_to_install(pkg)
+ }
+ )
+ continue
+
+ maybe_missing_module = extract_missing_module_from_cause_chain(e)
+ if maybe_missing_module:
+ missing_modules.add(maybe_missing_module)
+ continue
+
+ maybe_missing_packages = (
+ try_extract_packages_from_import_error_message(str(e))
+ )
+ if maybe_missing_packages:
+ missing_packages.update(
+ {
+ pkg
+ for pkg in maybe_missing_packages
+ if not self.package_manager.attempted_to_install(pkg)
}
)
- elif e.name is not None:
- missing_modules.add(e.name)
# Grab missing modules from module registry and from module not found errors
missing_modules = (
diff --git a/tests/_runtime/packages/test_import_error_extractors.py b/tests/_runtime/packages/test_import_error_extractors.py
new file mode 100644
index 0000000000..89368561d0
--- /dev/null
+++ b/tests/_runtime/packages/test_import_error_extractors.py
@@ -0,0 +1,103 @@
+# Copyright 2025 Marimo. All rights reserved.
+
+import pytest
+
+from marimo._runtime.packages.import_error_extractors import (
+ extract_missing_module_from_cause_chain,
+ extract_packages_from_pip_install_suggestion,
+ extract_packages_special_cases,
+)
+
+
+def test_extract_missing_module_from_cause_chain_direct():
+ """Test direct ModuleNotFoundError (no cause chain)."""
+ module_error = ModuleNotFoundError("No module named 'numpy'")
+ module_error.name = "numpy"
+
+ result = extract_missing_module_from_cause_chain(module_error)
+ assert result == "numpy"
+
+
+def test_extract_missing_module_from_cause_chain_with_cause():
+ """Test ImportError with ModuleNotFoundError cause."""
+ module_error = ModuleNotFoundError("No module named 'numpy'")
+ module_error.name = "numpy"
+
+ import_error = ImportError("Custom message")
+ import_error.__cause__ = module_error
+
+ result = extract_missing_module_from_cause_chain(import_error)
+ assert result == "numpy"
+
+
+def test_extract_missing_module_from_cause_chain_nested():
+ """Test nested cause chain."""
+ root_error = ModuleNotFoundError("No module named 'pandas'")
+ root_error.name = "pandas"
+
+ middle_error = ImportError("Middle error")
+ middle_error.__cause__ = root_error
+
+ top_error = ImportError("Top error")
+ top_error.__cause__ = middle_error
+
+ result = extract_missing_module_from_cause_chain(top_error)
+ assert result == "pandas"
+
+
+def test_extract_missing_module_from_cause_chain_no_module():
+ """Test error with no module in chain."""
+ import_error = ImportError("No useful cause")
+ result = extract_missing_module_from_cause_chain(import_error)
+ assert result is None
+
+
+ ("message", "expected"),
+ [
+ # Simple cases
+ ("Try: pip install requests", ["requests"]),
+ ("Run: pip install pandas[all]", ["pandas[all]"]),
+ # Quoted commands (multiple packages)
+ ("Try `pip install -U polars anywidget`", ["polars", "anywidget"]),
+ (
+ 'Run "pip install --upgrade requests pandas[all]"',
+ ["requests", "pandas[all]"],
+ ),
+ ("Execute 'pip install -U numpy matplotlib'", ["numpy", "matplotlib"]),
+ # Additional quoted edge cases
+ ("Try: `pip install pandas`.", ["pandas"]), # trailing punctuation
+ ('Try running `"pip install seaborn"`', ["seaborn"]), # nested quotes
+ (
+ "Use: 'pip install scipy matplotlib'",
+ ["scipy", "matplotlib"],
+ ), # extra spaces
+ (
+ "Here's the command: `pip install jupyterlab` for notebooks",
+ ["jupyterlab"],
+ ),
+ # Unquoted with surrounding text (conservative parsing)
+ ("Try: pip install polars if you want to do something", ["polars"]),
+ ("You can pip install requests pandas but maybe not", ["requests"]),
+ # No match
+ ("Some other error message", None),
+ # Harder, https://github.com/flekschas/jupyter-scatter/blob/ecfd8c4e19a1ad202372c09939682e5fbe9e70ba/jscatter/dependencies.py#L33-L37
+ (
+ """Please install it with: pip install "jupyter-scatter[blah]" or pip install "jupyter-scatter[all]".""",
+ ["jupyter-scatter[blah]"],
+ ),
+ ('Try: `pip install foo bar "baz[all]"`.', ["foo", "bar", "baz[all]"]),
+ ("Try: `pip install foo bar 'baz[all]'`.", ["foo", "bar", "baz[all]"]),
+ ],
+)
+def test_extract_packages_from_pip_install_suggestion(message, expected):
+ """Test pip install suggestion extraction with various formats."""
+ result = extract_packages_from_pip_install_suggestion(message)
+ assert result == expected
+
+
+def test_extract_packages_special_cases_pandas_parquet():
+ """Test pandas parquet special case."""
+ message = "Unable to find a usable engine; tried using: 'pyarrow', 'fastparquet'."
+ result = extract_packages_special_cases(message)
+ assert result == ["pyarrow"]