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.

improvement: mo.lazy supports async functions (#1300)

Myles Scolnick86ad6e0f84a9
diff --git a/marimo/_plugins/stateless/lazy.py b/marimo/_plugins/stateless/lazy.py
index b9daee24c6..f0df4d0b9f 100644
--- a/marimo/_plugins/stateless/lazy.py
+++ b/marimo/_plugins/stateless/lazy.py
@@ -1,8 +1,9 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import asyncio
from dataclasses import dataclass
-from typing import Callable, Final, Union
+from typing import Callable, Coroutine, Final, Union
from marimo._output.formatting import as_html
from marimo._output.rich_help import mddoc
@@ -25,7 +26,8 @@ class lazy(UIElement[None, None]):
The argument to `mo.lazy` can be an object to render lazily, or a function
that returns the object to render (that is, functions are lazily
- evaluated). Using a function is useful when the item to render is
+ evaluated). The function can be synchronous or asynchronous.
+ Using a function is useful when the item to render is
the result of a database query or some other expensive operation.
**Examples.**
@@ -44,6 +46,16 @@ class lazy(UIElement[None, None]):
accordion = mo.ui.accordion({"Charts": mo.lazy(expensive_component)})
```
+ Usage with async functions:
+
+ ```python
+ async def expensive_component(): ...
+
+
+ mo.lazy(expensive_component)
+ ```
+
+
**Initialization Args.**
- `element`: object or callable that returns content to be lazily loaded
@@ -56,7 +68,11 @@ class lazy(UIElement[None, None]):
def __init__(
self,
- element: Union[Callable[[], object], object],
+ element: Union[
+ Callable[[], object],
+ object,
+ Callable[[], Coroutine[None, None, object]],
+ ],
show_loading_indicator: bool = False,
) -> None:
self._element = element
@@ -81,11 +97,13 @@ class lazy(UIElement[None, None]):
def _convert_value(self, value: None) -> None:
return value
- def load(self, _args: EmptyArgs) -> LoadResponse:
+ async def load(self, _args: EmptyArgs) -> LoadResponse:
if callable(self._element) and not isinstance(
self._element, UIElement
):
el = self._element()
+ if asyncio.iscoroutine(el):
+ el = await el
return LoadResponse(html=as_html(el).text)
else:
return LoadResponse(html=as_html(self._element).text)
diff --git a/marimo/_runtime/functions.py b/marimo/_runtime/functions.py
index 3bbdfcf770..bdae3fbf23 100644
--- a/marimo/_runtime/functions.py
+++ b/marimo/_runtime/functions.py
@@ -4,7 +4,7 @@
from __future__ import annotations
import dataclasses
-from typing import Any, Callable, Generic, Type, TypeVar
+from typing import Any, Callable, Coroutine, Generic, Type, TypeVar
from marimo._ast.cell import CellId_t
from marimo._utils.parse_dataclass import build_dataclass
@@ -24,7 +24,7 @@ class EmptyArgs:
class Function(Generic[S, T]):
name: str
arg_cls: Type[S]
- function: Callable[[S], T]
+ function: Callable[[S], T] | Callable[[S], Coroutine[Any, Any, T]]
cell_id: CellId_t | None
def __init__(
@@ -52,7 +52,7 @@ class Function(Generic[S, T]):
else:
self.cell_id = None
- def __call__(self, args: dict[Any, Any]) -> T:
+ def __call__(self, args: dict[Any, Any]) -> T | Coroutine[Any, Any, T]:
return self.function(build_dataclass(args, self.arg_cls))
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index b4d98ea85f..e45c0e8e1e 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -15,7 +15,7 @@ import threading
import time
import traceback
from multiprocessing import connection
-from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional
+from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, cast
from marimo import _loggers
from marimo._ast.cell import CellConfig, CellId_t
@@ -1265,7 +1265,7 @@ class Kernel:
def reset_ui_initializers(self) -> None:
self.ui_initializers = {}
- def function_call_request(
+ async def function_call_request(
self, request: FunctionCallRequest
) -> tuple[HumanReadableStatus, JSONType]:
function = get_context().function_registry.get_function(
@@ -1291,8 +1291,12 @@ class Kernel:
else:
with self._install_execution_context(cell_id=function.cell_id):
try:
- return HumanReadableStatus(code="ok"), function(
- request.args
+ response = function(request.args)
+ if asyncio.iscoroutine(response):
+ response = await response
+ return HumanReadableStatus(code="ok"), response
+ return HumanReadableStatus(code="ok"), cast(
+ JSONType, response
)
except MarimoInterrupt:
error_title = "Interrupted"
@@ -1415,7 +1419,7 @@ class Kernel:
await self.set_ui_element_value(request)
CompletedRun().broadcast()
elif isinstance(request, FunctionCallRequest):
- status, ret = self.function_call_request(request)
+ status, ret = await self.function_call_request(request)
FunctionCallResult(
function_call_id=request.function_call_id,
return_value=ret,
diff --git a/marimo/_smoke_tests/lazy.py b/marimo/_smoke_tests/lazy.py
index f8a1757f5f..e65be2ad60 100644
--- a/marimo/_smoke_tests/lazy.py
+++ b/marimo/_smoke_tests/lazy.py
@@ -2,7 +2,7 @@
import marimo
-__generated_with = "0.3.8"
+__generated_with = "0.4.10"
app = marimo.App(width="full")
@@ -45,6 +45,24 @@ def __(generate_number, mo):
return
+def __(generate_number_async, mo):
+ mo.accordion({"Lazy async function": mo.lazy(generate_number_async, show_loading_indicator=True)})
+ return
+
+
+def __(random):
+ import asyncio
+ async def generate_number_async():
+ print("Loading...")
+ await asyncio.sleep(1)
+ print("Loaded!")
+ num = random.randint(0, 100)
+ return num
+ return asyncio, generate_number_async
+
+
@app.cell
def __(random, time):
def generate_number():
diff --git a/tests/_plugins/stateless/test_lazy.py b/tests/_plugins/stateless/test_lazy.py
new file mode 100644
index 0000000000..89cbe27254
--- /dev/null
+++ b/tests/_plugins/stateless/test_lazy.py
@@ -0,0 +1,73 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any
+
+from marimo._runtime.context import get_context
+from marimo._runtime.context.types import RuntimeContext
+from marimo._runtime.functions import Function
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+
+def get_only_function() -> Function[Any, Any]:
+ context: RuntimeContext = get_context()
+ assert len(context.function_registry.namespaces.values()) == 1
+ first_namespace = next(iter(context.function_registry.namespaces.values()))
+ assert len(first_namespace.functions) == 1
+ return next(iter(first_namespace.functions.values()))
+
+
+async def test_lazy(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ lazy = mo.lazy(42)
+ """
+ ),
+ ]
+ )
+ first_function = get_only_function()
+ assert first_function.name == "load"
+ res = await first_function({})
+ assert res.html == "<span>42</span>"
+
+
+async def test_lazy_function(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ lazy = mo.lazy(lambda: 42)
+ """
+ ),
+ ]
+ )
+ first_function = get_only_function()
+ assert first_function.name == "load"
+ res = await first_function({})
+ assert res.html == "<span>42</span>"
+
+
+async def test_lazy_async_function(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ async def get_value():
+ return 42
+ lazy = mo.lazy(get_value)
+ """
+ ),
+ ]
+ )
+ first_function = get_only_function()
+ assert first_function.name == "load"
+ res = await first_function({})
+ assert res.html == "<span>42</span>"
diff --git a/tests/_runtime/test_functions.py b/tests/_runtime/test_functions.py
new file mode 100644
index 0000000000..03cf1b4c2c
--- /dev/null
+++ b/tests/_runtime/test_functions.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+import dataclasses
+
+from marimo._runtime.functions import (
+ Function,
+ FunctionNamespace,
+ FunctionRegistry,
+)
+
+
+class Args:
+ value: int
+
+
+def test_function_init() -> None:
+ function = Function(
+ name="test_function",
+ arg_cls=Args,
+ function=lambda x: x.value + 1,
+ )
+
+ assert function.name == "test_function"
+ assert function.arg_cls == Args
+ assert callable(function.function)
+ assert function.cell_id is None
+
+
+def test_function_call() -> None:
+ function = Function(
+ name="test_function",
+ arg_cls=Args,
+ function=lambda x: x.value + 1,
+ )
+
+ result = function({"value": 1})
+ assert result == 2
+
+
+async def test_function_async_call() -> None:
+ async def async_function(x: Args) -> int:
+ return x.value + 1
+
+ function = Function(
+ name="test_function",
+ arg_cls=Args,
+ function=async_function,
+ )
+
+ result = await function({"value": 1})
+ assert result == 2
+
+
+def test_function_namespace() -> None:
+ namespace = FunctionNamespace(namespace="test_namespace")
+ function = Function(
+ name="test_function",
+ arg_cls=Args,
+ function=lambda x: x.value + 1,
+ )
+
+ namespace.add(function)
+ assert namespace.get("test_function") == function
+ assert namespace.get("non_existent_function") is None
+
+
+def test_function_registry() -> None:
+ registry = FunctionRegistry()
+ namespace = "test_namespace"
+ function = Function(
+ name="test_function",
+ arg_cls=Args,
+ function=lambda x: x.value + 1,
+ )
+
+ registry.register(namespace, function)
+ assert registry.get_function(namespace, "test_function") == function
+ assert registry.get_function(namespace, "non_existent_function") is None
+ assert (
+ registry.get_function("non_existent_namespace", "test_function")
+ is None
+ )
+
+ registry.delete(namespace)
+ assert registry.get_function(namespace, "test_function") is None