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.

perf: lazy imports when checking for datasets (#2262)

Akshay Agrawal8034a3df14fd
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 26621c169f..c58a06ac07 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -38,6 +38,9 @@ class Dependency:
max_v=max_version,
)
+ def imported(self) -> bool:
+ return self.pkg in sys.modules
+
def require(self, why: str) -> None:
"""
Raise an ModuleNotFoundError if the package is not installed.
@@ -163,6 +166,14 @@ class DependencyManager:
"""Return True if any lib is installed."""
return Dependency(pkg).has()
+ @staticmethod
+ def imported(pkg: str) -> bool:
+ """Return True if the lib has been imported.
+
+ Can be much faster than 'has'.
+ """
+ return Dependency(pkg).imported()
+
@staticmethod
def which(pkg: str) -> bool:
"""
diff --git a/marimo/_plugins/ui/_impl/tables/utils.py b/marimo/_plugins/ui/_impl/tables/utils.py
index cb0ec609ef..f68a4ff9e9 100644
--- a/marimo/_plugins/ui/_impl/tables/utils.py
+++ b/marimo/_plugins/ui/_impl/tables/utils.py
@@ -42,13 +42,16 @@ def get_table_manager_or_none(data: Any) -> TableManager[Any] | None:
# Try to find a manager specifically for the data type
for manager_factory in MANAGERS:
- if DependencyManager.has(manager_factory.package_name()):
+ # We use `imported` instead of `has()` because `has()` can be very
+ # slow. If a variable created by a package is in memory, then the
+ # module will have been imported.
+ if DependencyManager.imported(manager_factory.package_name()):
manager = manager_factory.create()
if manager.is_type(data):
return manager(data)
# Unpack narwhal dataframe wrapper
- if DependencyManager.narwhals.has():
+ if DependencyManager.narwhals.imported():
import narwhals # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
if isinstance(data, narwhals.DataFrame):
diff --git a/tests/_dependencies/test_dependencies.py b/tests/_dependencies/test_dependencies.py
index 4506438311..c1464c3f8f 100644
--- a/tests/_dependencies/test_dependencies.py
+++ b/tests/_dependencies/test_dependencies.py
@@ -16,12 +16,16 @@ def test_dependencies() -> None:
assert altair is not None
DependencyManager.altair.require("for testing")
+ assert DependencyManager.altair.imported()
+ assert DependencyManager.imported("altair")
if DependencyManager.pandas.has():
import pandas
assert pandas is not None
DependencyManager.pandas.require("for testing")
+ assert DependencyManager.pandas.imported()
+ assert DependencyManager.imported("pandas")
def test_without_dependencies() -> None: