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.

fix: guard against modules that don't have a `__spec__` attr (#1058)

Akshay Agrawalf00edc7e8443
diff --git a/marimo/_runtime/packages/module_registry.py b/marimo/_runtime/packages/module_registry.py
index 1eb87c7a1c..ab2396fd69 100644
--- a/marimo/_runtime/packages/module_registry.py
+++ b/marimo/_runtime/packages/module_registry.py
@@ -2,11 +2,28 @@
from __future__ import annotations
import importlib.util
+import sys
from marimo._ast.cell import CellId_t
from marimo._runtime.dataflow import DirectedGraph
+def _is_module_installed(module_name: str) -> bool:
+ # importlib.util.find_spec retrieves a module's ModuleSpec, which
+ # is typically available as a dunder attribute on the module, i.e.
+ # module.__spec__. However, some packages are non-compliant and don't
+ # include a __spec__ attr (e.g., manim-slides), which can cause find_spec
+ # to throw if the module has already been imported.
+ #
+ # We don't actually need the spec, we just need to see if a package is
+ # available, so we first check if the module is in sys.modules without
+ # checking for a __spec__ attr.
+ return (
+ module_name in sys.modules
+ or importlib.util.find_spec(module_name) is not None
+ )
+
+
class ModuleRegistry:
def __init__(
self, graph: DirectedGraph, excluded_modules: set[str] | None = None
@@ -35,10 +52,6 @@ class ModuleRegistry:
def missing_modules(self) -> set[str]:
"""Modules that will fail to import."""
return (
- set(
- mod
- for mod in self.modules()
- if importlib.util.find_spec(mod) is None
- )
+ set(mod for mod in self.modules() if not _is_module_installed(mod))
- self.excluded_modules
)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index fa03c29692..7f321828af 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -452,7 +452,9 @@ class Kernel:
defs_to_delete, exclude_defs if exclude_defs is not None else set()
)
- missing_modules_after_deletion = self.module_registry.missing_modules()
+ missing_modules_after_deletion = (
+ missing_modules_before_deletion & self.module_registry.modules()
+ )
if (
self.package_manager is not None
and missing_modules_after_deletion
diff --git a/marimo/_smoke_tests/bugs/1055.py b/marimo/_smoke_tests/bugs/1055.py
new file mode 100644
index 0000000000..9f55e35204
--- /dev/null
+++ b/marimo/_smoke_tests/bugs/1055.py
@@ -0,0 +1,21 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __():
+ import manim_slides
+ return manim_slides,
+
+
+def __():
+ print(1)
+ return
+
+
+if __name__ == "__main__":
+ app.run()