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: support lazy imports in setup cells (#11431)

Dylan Madisetti15ed710d7571
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
index cd11e99a66..61f531ab20 100644
--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
@@ -207,7 +207,8 @@ export const MarimoErrorOutput = ({
e.type === "ancestor-stopped",
);
const syntaxErrors = errors.filter(
- (e): e is Extract<MarimoError, { type: "syntax" }> => e.type === "syntax",
+ (e): e is Extract<MarimoError, { type: "syntax" | "lazy-import" }> =>
+ e.type === "syntax" || e.type === "lazy-import",
);
const unknownErrors = errors.filter(
(e): e is Extract<MarimoError, { type: "unknown" }> => e.type === "unknown",
diff --git a/frontend/src/core/errors/error-entries.ts b/frontend/src/core/errors/error-entries.ts
index e27bf85a27..64f82e7cf7 100644
--- a/frontend/src/core/errors/error-entries.ts
+++ b/frontend/src/core/errors/error-entries.ts
@@ -122,6 +122,9 @@ export function describeError(error: MarimoError): string {
if (error.type === "import-star") {
return error.msg;
}
+ if (error.type === "lazy-import") {
+ return error.msg;
+ }
if (error.type === "ancestor-stopped") {
return error.msg;
}
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index 8dbb357ebc..c9d7f7fdd8 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -301,7 +301,11 @@ def compile_cell(
isinstance(stmt, (ast.Import, ast.ImportFrom)) for stmt in module.body
)
- v = ScopedVisitor("cell_" + cell_id)
+ # NB. Setup cell IDs can have an app-specific prefix.
+ v = ScopedVisitor(
+ "cell_" + cell_id,
+ allow_lazy_imports=cell_id.endswith(SETUP_CELL_NAME),
+ )
v.visit(module)
expr: ast.Expression
diff --git a/marimo/_ast/errors.py b/marimo/_ast/errors.py
index 58f78c0b43..15a0fc1682 100644
--- a/marimo/_ast/errors.py
+++ b/marimo/_ast/errors.py
@@ -14,6 +14,10 @@ class ImportStarError(SyntaxError):
pass
+class LazyImportError(SyntaxError):
+ pass
+
+
class MultipleDefinitionError(Exception):
pass
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 5b5e806a0a..b76b8b5987 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, Literal, Union
from uuid import uuid4
from marimo import _loggers
-from marimo._ast.errors import ImportStarError
+from marimo._ast.errors import ImportStarError, LazyImportError
from marimo._ast.sql_visitor import (
SQLDefs,
SQLKind,
@@ -46,6 +46,13 @@ class LexicalScope(str, Enum):
ANNOTATION = "annotation"
+def is_lazy_import(node: ast.AST) -> bool:
+ """Return whether the node is a lazy import statement."""
+ return isinstance(node, (ast.Import, ast.ImportFrom)) and bool(
+ getattr(node, "is_lazy", 0)
+ )
+
+
@dataclass
class ImportData:
# full module name
@@ -58,6 +65,7 @@ class ImportData:
# from a.b import c => symbol == a.b.c
imported_symbol: str | None = None
import_level: int | None = None
+ is_lazy: bool = False
def __post_init__(self) -> None:
self.namespace = self.module.split(".")[0]
@@ -238,8 +246,11 @@ class ScopedVisitor(ast.NodeVisitor):
ignore_local: bool = False,
on_def: Callable[[NamedNode, str, list[Block]], None] | None = None,
on_ref: Callable[[NamedNode], None] | None = None,
+ allow_lazy_imports: bool = True,
) -> None:
self.block_stack: list[Block] = [Block()]
+ # NB. Lazy imports are invalid in cells saved as function bodies.
+ self.allow_lazy_imports = allow_lazy_imports
# Names to be loaded into a variable required_refs
self.ref_stack: list[set[Name]] = [set()]
self.obscured_scope_stack: list[ObscuredScope] = []
@@ -1112,7 +1123,19 @@ class ScopedVisitor(ast.NodeVisitor):
self._add_ref(node, name, deleted=False)
return node
+ def _check_lazy_import(self, node: ast.Import | ast.ImportFrom) -> bool:
+ is_lazy = is_lazy_import(node)
+ if is_lazy and not self.allow_lazy_imports:
+ error = LazyImportError(
+ "`lazy import` is only allowed in the setup cell."
+ )
+ error.lineno = node.lineno
+ error.offset = node.col_offset + 1
+ raise error
+ return is_lazy
+
def visit_Import(self, node: ast.Import) -> ast.Import:
+ is_lazy = self._check_lazy_import(node)
for alias_node in node.names:
variable_name = self._get_alias_name(alias_node)
self._define(
@@ -1124,12 +1147,14 @@ class ScopedVisitor(ast.NodeVisitor):
module=alias_node.name,
definition=variable_name,
imported_symbol=None,
+ is_lazy=is_lazy,
),
),
)
return node
def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.ImportFrom:
+ is_lazy = self._check_lazy_import(node)
module = node.module if node.module is not None else ""
# we don't recurse into the alias nodes, since we define the
# aliases here
@@ -1146,6 +1171,7 @@ class ScopedVisitor(ast.NodeVisitor):
definition=variable_name,
imported_symbol=module + "." + original_name,
import_level=node.level,
+ is_lazy=is_lazy,
),
),
)
diff --git a/marimo/_messaging/errors.py b/marimo/_messaging/errors.py
index c7c838155f..1467e18c87 100644
--- a/marimo/_messaging/errors.py
+++ b/marimo/_messaging/errors.py
@@ -37,6 +37,14 @@ class ImportStarError(msgspec.Struct, tag="import-star"):
return self.msg
+class LazyImportError(msgspec.Struct, tag="lazy-import"):
+ msg: str
+ lineno: int | None = None
+
+ def describe(self) -> str:
+ return self.msg
+
+
class MarimoInterruptionError(msgspec.Struct, tag="interruption"):
def describe(self) -> str:
return "This cell was interrupted and needs to be re-run"
@@ -168,6 +176,7 @@ Error = (
| CycleError
| MultipleDefinitionError
| ImportStarError
+ | LazyImportError
| MarimoAncestorStoppedError
| MarimoAncestorPreventedError
| MarimoExceptionRaisedError
diff --git a/marimo/_runtime/executor/lifecycles/strict.py b/marimo/_runtime/executor/lifecycles/strict.py
index 13abdb22be..fac8e5a88a 100644
--- a/marimo/_runtime/executor/lifecycles/strict.py
+++ b/marimo/_runtime/executor/lifecycles/strict.py
@@ -19,6 +19,7 @@ from marimo._runtime.primitives import (
CLONE_PRIMITIVES,
build_ref_predicate_for_primitives,
from_unclonable_module,
+ is_module,
is_unclonable_type,
)
from marimo._runtime.runner.result import RunResult
@@ -113,7 +114,7 @@ class StrictLifecycle:
def _sanitize_ref(self, name: str, value: Any) -> Any:
if (
isinstance(value, ZeroCopy)
- or inspect.ismodule(value)
+ or is_module(value)
or inspect.isfunction(value)
or from_unclonable_module(value)
or is_unclonable_type(value)
diff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.py
index 471fea9658..948d4ce998 100644
--- a/marimo/_runtime/primitives.py
+++ b/marimo/_runtime/primitives.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import inspect
import numbers
+import types
import weakref
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
@@ -170,12 +171,23 @@ def from_unclonable_module(obj: object) -> bool:
)
+# NB. inspect.ismodule does not recognize Python 3.15 lazy import proxies.
+_LAZY_IMPORT_TYPES: tuple[type, ...] = (
+ (types.LazyImportType,) if hasattr(types, "LazyImportType") else ()
+)
+
+
+def is_module(value: Any) -> bool:
+ """Whether `value` is a module or a lazy import proxy for one."""
+ return inspect.ismodule(value) or isinstance(value, _LAZY_IMPORT_TYPES)
+
+
def is_pure_scope(
ref: Name,
defs: dict[str, Any],
cache: FN_CACHE_TYPE = None,
) -> bool:
- return inspect.ismodule(defs[ref]) or is_pure_function(
+ return is_module(defs[ref]) or is_pure_function(
ref, defs[ref], defs, cache
)
@@ -248,7 +260,7 @@ def is_pure_function(
if ref in defs:
# Recursion allows for effective DFS
if not (
- inspect.ismodule(defs[ref])
+ is_module(defs[ref])
or is_pure_function(ref, defs[ref], defs, cache, graph)
):
cache[value] = False
@@ -316,7 +328,7 @@ def build_ref_predicate_for_primitives(
def check_ref(ref: Name) -> bool:
return ref in glbls and (
inspect.isfunction(glbls[ref])
- or inspect.ismodule(glbls[ref])
+ or is_module(glbls[ref])
or inspect.isclass(glbls[ref])
or callable(glbls[ref])
)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 4411b883b1..2a29c3d5fc 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -32,7 +32,7 @@ from marimo._ast.cell import (
RuntimeStateType,
)
from marimo._ast.compiler import _build_source_position_map, compile_cell
-from marimo._ast.errors import ImportStarError
+from marimo._ast.errors import ImportStarError, LazyImportError
from marimo._ast.names import SETUP_CELL_NAME
from marimo._ast.variables import BUILTINS, is_local
from marimo._ast.visitor import ImportData, Name, VariableData
@@ -54,6 +54,7 @@ from marimo._messaging.context import (
from marimo._messaging.errors import (
Error,
ImportStarError as MarimoImportStarError,
+ LazyImportError as MarimoLazyImportError,
MarimoInterruptionError,
MarimoStrictExecutionError,
MarimoSyntaxError,
@@ -952,6 +953,9 @@ class Kernel:
lineno = getattr(e, "lineno", None)
if isinstance(e, ImportStarError):
error = MarimoImportStarError(msg=str(e), lineno=lineno)
+ elif isinstance(e, LazyImportError):
+ # NB. str(e) appends the line number already in lineno.
+ error = MarimoLazyImportError(msg=e.msg, lineno=lineno)
else:
def _get_syntax_hints(broken_line: str) -> str:
diff --git a/marimo/_schemas/generated/notifications.yaml b/marimo/_schemas/generated/notifications.yaml
index 5222a8df16..432ab378e6 100644
--- a/marimo/_schemas/generated/notifications.yaml
+++ b/marimo/_schemas/generated/notifications.yaml
@@ -207,6 +207,7 @@ components:
- $ref: '#/components/schemas/CycleError'
- $ref: '#/components/schemas/MultipleDefinitionError'
- $ref: '#/components/schemas/ImportStarError'
+ - $ref: '#/components/schemas/LazyImportError'
- $ref: '#/components/schemas/MarimoAncestorStoppedError'
- $ref: '#/components/schemas/MarimoAncestorPreventedError'
- $ref: '#/components/schemas/MarimoExceptionRaisedError'
@@ -225,6 +226,7 @@ components:
import-star: '#/components/schemas/ImportStarError'
internal: '#/components/schemas/MarimoInternalError'
interruption: '#/components/schemas/MarimoInterruptionError'
+ lazy-import: '#/components/schemas/LazyImportError'
multiple-defs: '#/components/schemas/MultipleDefinitionError'
setup-refs: '#/components/schemas/SetupRootError'
sql-error: '#/components/schemas/MarimoSQLError'
@@ -1171,6 +1173,23 @@ components:
- data
title: LayoutConfig
type: object
+ LazyImportError:
+ properties:
+ lineno:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ default: null
+ msg:
+ type: string
+ type:
+ enum:
+ - lazy-import
+ required:
+ - type
+ - msg
+ title: LazyImportError
+ type: object
MarimoAncestorPreventedError:
properties:
blamed_cell:
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index b022c93c84..a99d1e4513 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -540,6 +540,7 @@ components:
- $ref: '#/components/schemas/CycleError'
- $ref: '#/components/schemas/MultipleDefinitionError'
- $ref: '#/components/schemas/ImportStarError'
+ - $ref: '#/components/schemas/LazyImportError'
- $ref: '#/components/schemas/MarimoAncestorStoppedError'
- $ref: '#/components/schemas/MarimoAncestorPreventedError'
- $ref: '#/components/schemas/MarimoExceptionRaisedError'
@@ -558,6 +559,7 @@ components:
import-star: '#/components/schemas/ImportStarError'
internal: '#/components/schemas/MarimoInternalError'
interruption: '#/components/schemas/MarimoInterruptionError'
+ lazy-import: '#/components/schemas/LazyImportError'
multiple-defs: '#/components/schemas/MultipleDefinitionError'
setup-refs: '#/components/schemas/SetupRootError'
sql-error: '#/components/schemas/MarimoSQLError'
@@ -3215,6 +3217,23 @@ components:
- data
title: LayoutConfig
type: object
+ LazyImportError:
+ properties:
+ lineno:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ default: null
+ msg:
+ type: string
+ type:
+ enum:
+ - lazy-import
+ required:
+ - type
+ - msg
+ title: LazyImportError
+ type: object
LintConfig:
description: "Configuration for lint rule selection.\n\n Follows ruff-inspired\
\ semantics for selecting which rules to run\n during `marimo check`.\n\
@@ -3655,6 +3674,7 @@ components:
- $ref: '#/components/schemas/CycleError'
- $ref: '#/components/schemas/MultipleDefinitionError'
- $ref: '#/components/schemas/ImportStarError'
+ - $ref: '#/components/schemas/LazyImportError'
- $ref: '#/components/schemas/MarimoAncestorStoppedError'
- $ref: '#/components/schemas/MarimoAncestorPreventedError'
- $ref: '#/components/schemas/MarimoExceptionRaisedError'
@@ -3673,6 +3693,7 @@ components:
import-star: '#/components/schemas/ImportStarError'
internal: '#/components/schemas/MarimoInternalError'
interruption: '#/components/schemas/MarimoInterruptionError'
+ lazy-import: '#/components/schemas/LazyImportError'
multiple-defs: '#/components/schemas/MultipleDefinitionError'
setup-refs: '#/components/schemas/SetupRootError'
sql-error: '#/components/schemas/MarimoSQLError'
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index cf40b5ec05..f73058107c 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -4176,6 +4176,7 @@ export interface components {
| components["schemas"]["CycleError"]
| components["schemas"]["MultipleDefinitionError"]
| components["schemas"]["ImportStarError"]
+ | components["schemas"]["LazyImportError"]
| components["schemas"]["MarimoAncestorStoppedError"]
| components["schemas"]["MarimoAncestorPreventedError"]
| components["schemas"]["MarimoExceptionRaisedError"]
@@ -5735,6 +5736,14 @@ export interface components {
data: Record<string, any>;
type: string;
};
+ /** LazyImportError */
+ LazyImportError: {
+ /** @default null */
+ lineno?: number | null;
+ msg: string;
+ /** @enum {unknown} */
+ type: "lazy-import";
+ };
/**
* LintConfig
* @description Configuration for lint rule selection.
@@ -5996,6 +6005,7 @@ export interface components {
| components["schemas"]["CycleError"]
| components["schemas"]["MultipleDefinitionError"]
| components["schemas"]["ImportStarError"]
+ | components["schemas"]["LazyImportError"]
| components["schemas"]["MarimoAncestorStoppedError"]
| components["schemas"]["MarimoAncestorPreventedError"]
| components["schemas"]["MarimoExceptionRaisedError"]
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index 3625a1b6b2..f105498946 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -3,9 +3,11 @@ from __future__ import annotations
import ast
import json
+import sys
from functools import partial
from inspect import cleandoc
from pathlib import Path
+from runpy import run_path
from textwrap import dedent
from typing import Any
from unittest.mock import patch
@@ -19,7 +21,7 @@ from marimo._ast import codegen, compiler, load
from marimo._ast.app import App, InternalApp
from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
-from marimo._ast.names import is_internal_cell_name
+from marimo._ast.names import SETUP_CELL_NAME, is_internal_cell_name
from marimo._schemas.notebook import NotebookV1
compile_cell = partial(compiler.compile_cell, cell_id="0")
@@ -2366,3 +2368,45 @@ def test_format_markdown_preserves_surrounding_source(
code: str, expected: str
) -> None:
assert codegen.format_markdown(compile_cell(code)) == expected
+
+
+ sys.version_info < (3, 15), reason="`lazy import` requires Python 3.15"
+)
+class TestLazyImports:
+ @staticmethod
+ def test_lazy_import_in_regular_cell_saves_as_unparsable_cell(
+ tmp_path: Path,
+ ) -> None:
+ contents = wrap_generate_filecontents(
+ ["lazy import json", "x = 1"], ["one", "two"]
+ )
+ assert "app._unparsable_cell" in contents
+ assert "lazy import json" in contents
+ compile(contents, "<notebook>", "exec")
+ path = tmp_path / "notebook.py"
+ path.write_text(contents)
+ app = load.load_app(path)
+ assert app is not None
+ assert list(app._cell_manager.codes()) == ["lazy import json", "x = 1"]
+
+ @staticmethod
+ def test_lazy_import_in_setup_cell_serializes(tmp_path: Path) -> None:
+ contents = wrap_generate_filecontents(
+ ["lazy import json\nX = 1", "y = json.dumps(X)"],
+ [SETUP_CELL_NAME, "two"],
+ )
+ assert "with app.setup:" in contents
+ assert " lazy import json" in contents
+ assert "app._unparsable_cell" not in contents
+ compile(contents, "<notebook>", "exec")
+ path = tmp_path / "notebook.py"
+ path.write_text(contents)
+ app = load.load_app(path)
+ assert app is not None
+ assert list(app._cell_manager.codes()) == [
+ "lazy import json\nX = 1",
+ "y = json.dumps(X)",
+ ]
+ _, defs = run_path(str(path))["app"].run()
+ assert defs["y"] == "1"
diff --git a/tests/_ast/test_compiler.py b/tests/_ast/test_compiler.py
index 1ae5d51965..517976725b 100644
--- a/tests/_ast/test_compiler.py
+++ b/tests/_ast/test_compiler.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import os
+import sys
from functools import partial
from typing import Any
from unittest.mock import patch
@@ -10,9 +11,12 @@ import pytest
from marimo._ast import compiler
from marimo._ast.cell_manager import CellManager
+from marimo._ast.errors import LazyImportError
+from marimo._ast.names import SETUP_CELL_NAME
from marimo._ast.sql_visitor import SQLRef
from marimo._ast.visitor import ImportData, VariableData
from marimo._dependencies.dependencies import DependencyManager
+from marimo._types.ids import CellId_t
compile_cell = partial(compiler.compile_cell, cell_id="0")
@@ -1017,3 +1021,54 @@ class TestCellAstMatchesRawAst:
assert pos is not None
self._assert_fixed_ast_contains_line(cell.code, source, pos)
+
+
+ sys.version_info < (3, 15), reason="`lazy import` requires Python 3.15"
+)
+class TestLazyImports:
+ @staticmethod
+ @pytest.mark.parametrize(
+ ("code", "lineno", "offset"),
+ [
+ ("lazy import numpy", 1, 1),
+ ("x = 1\nif x:\n lazy import numpy", 3, 5),
+ ],
+ )
+ def test_lazy_import_in_regular_cell_is_a_syntax_error(
+ code: str, lineno: int, offset: int
+ ) -> None:
+ with pytest.raises(
+ LazyImportError, match="only allowed in the setup cell"
+ ) as e:
+ compile_cell(code)
+ assert e.value.lineno == lineno
+ assert e.value.offset == offset
+
+ @staticmethod
+ @pytest.mark.parametrize("prefix", ["", "app1-"])
+ def test_lazy_import_in_setup_cell_compiles(prefix: str) -> None:
+ cell = compiler.compile_cell(
+ "lazy import numpy", cell_id=CellId_t(prefix + SETUP_CELL_NAME)
+ )
+ assert cell.defs == {"numpy"}
+
+ @staticmethod
+ def test_lazy_import_is_tracked() -> None:
+ cell = compiler.compile_cell(
+ "lazy import numpy\nimport os\nlazy from json import dumps",
+ cell_id=CellId_t(SETUP_CELL_NAME),
+ )
+ assert {data.definition: data for data in cell.imports} == {
+ "numpy": ImportData(
+ module="numpy", definition="numpy", is_lazy=True
+ ),
+ "os": ImportData(module="os", definition="os"),
+ "dumps": ImportData(
+ module="json",
+ definition="dumps",
+ imported_symbol="json.dumps",
+ import_level=0,
+ is_lazy=True,
+ ),
+ }
diff --git a/tests/_messaging/test_messaging_errors.py b/tests/_messaging/test_messaging_errors.py
index 223e49446d..179fe197ca 100644
--- a/tests/_messaging/test_messaging_errors.py
+++ b/tests/_messaging/test_messaging_errors.py
@@ -6,6 +6,7 @@ import msgspec
from marimo._messaging.errors import (
CycleError,
ImportStarError,
+ LazyImportError,
MarimoAncestorPreventedError,
MarimoAncestorStoppedError,
MarimoExceptionRaisedError,
@@ -65,6 +66,21 @@ class TestErrorClasses:
assert error.describe() == "Cannot use import * in this context"
assert error.lineno == 3
+ def test_lazy_import_error(self) -> None:
+ error = LazyImportError(
+ msg="`lazy import` is only allowed in the setup cell.", lineno=2
+ )
+
+ assert msgspec.to_builtins(error) == {
+ "type": "lazy-import",
+ "msg": "`lazy import` is only allowed in the setup cell.",
+ "lineno": 2,
+ }
+ assert (
+ error.describe()
+ == "`lazy import` is only allowed in the setup cell."
+ )
+
def test_marimo_interruption_error(self) -> None:
error = MarimoInterruptionError()
diff --git a/tests/_runtime/reload/test_lazy_import_reload.py b/tests/_runtime/reload/test_lazy_import_reload.py
new file mode 100644
index 0000000000..3e0585a035
--- /dev/null
+++ b/tests/_runtime/reload/test_lazy_import_reload.py
@@ -0,0 +1,203 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import asyncio
+import copy
+import sys
+from queue import Queue
+from typing import TYPE_CHECKING, Literal
+
+import pytest
+from reload_test_utils import update_file
+
+import marimo._runtime.reload.module_watcher as mw
+from marimo._ast.names import SETUP_CELL_NAME
+from marimo._config.config import DEFAULT_CONFIG
+from marimo._runtime.commands import (
+ ExecuteCellCommand,
+ ExecuteStaleCellsCommand,
+ UpdateUserConfigCommand,
+)
+from marimo._runtime.runtime import Kernel
+from marimo._types.ids import CellId_t
+from tests.conftest import ExecReqProvider
+
+if TYPE_CHECKING:
+ import pathlib
+ from collections.abc import Callable, Iterator
+
+pytestmark = pytest.mark.skipif(
+ sys.version_info < (3, 15), reason="`lazy import` requires Python 3.15"
+)
+
+INTERVAL = 0.2
+SETUP = CellId_t(SETUP_CELL_NAME)
+
+
+def module_file(
+ tmp_path: pathlib.Path,
+ py_modname: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> Iterator[pathlib.Path]:
+ monkeypatch.setattr(mw, "_TEST_SLEEP_INTERVAL", INTERVAL)
+ monkeypatch.syspath_prepend(tmp_path)
+ py_file = tmp_path / f"{py_modname}.py"
+ py_file.write_text("def foo():\n return 1\n")
+ yield py_file
+ sys.modules.pop(py_modname, None)
+
+
+async def _wait_for(predicate: Callable[[], bool], polls: int = 25) -> bool:
+ for _ in range(polls):
+ await asyncio.sleep(INTERVAL)
+ if predicate():
+ return True
+ return predicate()
+
+
+def _set_mode(k: Kernel, mode: Literal["lazy", "autorun"]) -> None:
+ config = copy.deepcopy(DEFAULT_CONFIG)
+ config["runtime"]["auto_reload"] = mode
+ k.set_user_config(UpdateUserConfigCommand(config=config))
+
+
+ ("setup_code", "reader"),
+ [
+ ("import {m}", "x = {m}.foo()"),
+ ("lazy import {m}", "x = {m}.foo()"),
+ ("from {m} import foo", "x = foo()"),
+ ("lazy from {m} import foo", "x = foo()"),
+ ],
+ ids=["import", "lazy-import", "from-import", "lazy-from-import"],
+)
+async def test_setup_import_reloads_in_lazy_mode(
+ module_file: pathlib.Path,
+ py_modname: str,
+ execution_kernel: Kernel,
+ exec_req: ExecReqProvider,
+ setup_code: str,
+ reader: str,
+) -> None:
+ k = execution_kernel
+ _set_mode(k, "lazy")
+ await k.run(
+ [
+ ExecuteCellCommand(
+ cell_id=SETUP, code=setup_code.format(m=py_modname)
+ ),
+ er := exec_req.get(reader.format(m=py_modname)),
+ ]
+ )
+ assert not k.errors, k.errors
+ assert k.globals["x"] == 1
+ setup_cell = k.graph.cells[SETUP]
+ assert setup_cell.import_workspace.is_import_block
+ update_file(module_file, "def foo():\n return 2\n")
+ assert await _wait_for(lambda: setup_cell.stale)
+
+ await k.run_stale_cells()
+ assert k.globals["x"] == 2
+ assert not setup_cell.stale
+ assert not k.graph.cells[er.cell_id].stale
+ assert setup_cell.import_workspace.imported_defs == setup_cell.defs
+
+
+ ("setup_code", "reader"),
+ [
+ ("import {m}", "x = {m}.foo()"),
+ ("lazy import {m}", "x = {m}.foo()"),
+ ("lazy from {m} import foo", "x = foo()"),
+ ],
+ ids=["import", "lazy-import", "lazy-from-import"],
+)
+async def test_setup_import_reloads_in_autorun_mode(
+ module_file: pathlib.Path,
+ py_modname: str,
+ execution_kernel: Kernel,
+ exec_req: ExecReqProvider,
+ setup_code: str,
+ reader: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ k = execution_kernel
+ queue: Queue[ExecuteStaleCellsCommand] = Queue()
+ monkeypatch.setattr(k, "enqueue_control_request", queue.put)
+ _set_mode(k, "autorun")
+ await k.run(
+ [
+ ExecuteCellCommand(
+ cell_id=SETUP, code=setup_code.format(m=py_modname)
+ ),
+ exec_req.get(reader.format(m=py_modname)),
+ ]
+ )
+ assert not k.errors, k.errors
+ assert k.globals["x"] == 1
+
+ update_file(module_file, "def foo():\n return 2\n")
+ assert await _wait_for(lambda: not queue.empty(), polls=50)
+ assert k.graph.cells[SETUP].stale
+ request = queue.get_nowait()
+ assert request == ExecuteStaleCellsCommand()
+ await k.handle_message(request)
+ assert k.globals["x"] == 2
+ assert not k.graph.get_stale()
+
+
+async def test_unused_lazy_import_is_not_watched(
+ module_file: pathlib.Path,
+ py_modname: str,
+ execution_kernel: Kernel,
+ exec_req: ExecReqProvider,
+) -> None:
+ k = execution_kernel
+ _set_mode(k, "lazy")
+ await k.run(
+ [ExecuteCellCommand(cell_id=SETUP, code=f"lazy import {py_modname}")]
+ )
+ assert not k.errors
+ assert py_modname not in sys.modules
+
+ update_file(module_file, "def foo():\n return 2\n")
+ assert not await _wait_for(lambda: k.graph.cells[SETUP].stale, polls=8)
+
+ await k.run([exec_req.get(f"x = {py_modname}.foo()")])
+ assert not k.errors
+ assert k.globals["x"] == 2
+ assert py_modname in sys.modules
+ assert not k.graph.cells[SETUP].stale
+
+
[email protected]("module_file")
+async def test_lazy_import_added_to_setup_does_not_rerun_readers(
+ py_modname: str,
+ execution_kernel: Kernel,
+ exec_req: ExecReqProvider,
+) -> None:
+ k = execution_kernel
+ _set_mode(k, "lazy")
+ await k.run(
+ [
+ ExecuteCellCommand(
+ cell_id=SETUP, code=f"lazy import {py_modname}"
+ ),
+ exec_req.get(f"x = ({py_modname}.foo(), object())"),
+ ]
+ )
+ assert not k.errors
+ before = k.globals["x"]
+ assert before[0] == 1
+ await k.run(
+ [
+ ExecuteCellCommand(
+ cell_id=SETUP,
+ code=f"lazy import {py_modname}\nlazy import json",
+ )
+ ]
+ )
+ assert not k.errors
+ assert k.globals["x"] is before
+ assert not k.graph.get_stale()
diff --git a/tests/_runtime/test_lazy_import.py b/tests/_runtime/test_lazy_import.py
new file mode 100644
index 0000000000..f10a36046b
--- /dev/null
+++ b/tests/_runtime/test_lazy_import.py
@@ -0,0 +1,88 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import sys
+from typing import TYPE_CHECKING
+
+import pytest
+
+from marimo._ast.names import SETUP_CELL_NAME
+from marimo._messaging.errors import LazyImportError
+from marimo._runtime.commands import ExecuteCellCommand
+from marimo._runtime.runtime import Kernel
+from marimo._types.ids import CellId_t
+from tests.conftest import ExecReqProvider
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+ from pathlib import Path
+
+pytestmark = pytest.mark.skipif(
+ sys.version_info < (3, 15), reason="`lazy import` requires Python 3.15"
+)
+
+
+def lazy_module(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> Iterator[str]:
+ module_name = "marimo_lazy_import_test"
+ (tmp_path / f"{module_name}.py").write_text("def foo():\n return 1\n")
+ monkeypatch.syspath_prepend(tmp_path)
+ yield module_name
+ sys.modules.pop(module_name, None)
+
+
+class TestLazyImports:
+ async def test_lazy_import_in_regular_cell_is_a_syntax_error(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ er = exec_req.get("lazy import numpy")
+ await k.run([er])
+ assert set(k.errors.keys()) == {er.cell_id}
+ error = k.errors[er.cell_id][0]
+ assert isinstance(error, LazyImportError)
+ assert error.lineno == 1
+ assert error.msg == "`lazy import` is only allowed in the setup cell."
+
+ @pytest.mark.parametrize(
+ ("setup_code", "reader"),
+ [
+ ("lazy import {m}", "{m}.foo()"),
+ ("lazy from {m} import foo", "foo()"),
+ ],
+ )
+ async def test_setup_import_is_deferred_until_first_use(
+ self,
+ execution_kernel: Kernel,
+ exec_req: ExecReqProvider,
+ lazy_module: str,
+ setup_code: str,
+ reader: str,
+ ) -> None:
+ k = execution_kernel
+ await k.run(
+ [
+ ExecuteCellCommand(
+ cell_id=CellId_t(SETUP_CELL_NAME),
+ code=setup_code.format(m=lazy_module),
+ ),
+ ]
+ )
+ assert not k.errors
+ assert lazy_module not in sys.modules
+
+ await k.run(
+ [
+ exec_req.get(
+ f"def use_module():\n return {reader.format(m=lazy_module)}"
+ )
+ ]
+ )
+ assert not k.errors
+ assert lazy_module not in sys.modules
+
+ await k.run([exec_req.get("x = use_module()")])
+ assert not k.errors
+ assert k.globals["x"] == 1
+ assert lazy_module in sys.modules