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: preserve `TypeIs`/`TypeGuard` narrowing through `@app.function`, `@mo.cache`, and `@mo.lru_cache` (#8598)

Myles Scolnick7784ad50518c
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 848acf08e7..68d631be6a 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -70,6 +70,8 @@ if TYPE_CHECKING:
from collections.abc import Sequence
from types import FrameType, TracebackType
+ from typing_extensions import TypeGuard, TypeIs
+
from marimo._messaging.notification import HumanReadableStatus
from marimo._plugins.core.web_component import JSONType
from marimo._runtime.context.types import ExecutionContext
@@ -387,6 +389,16 @@ class App:
),
)
+ @overload
+ def function( # type: ignore[overload-overlap]
+ self, func: Callable[P, TypeIs[R]]
+ ) -> Callable[P, TypeIs[R]]: ...
+
+ @overload
+ def function(
+ self, func: Callable[P, TypeGuard[R]]
+ ) -> Callable[P, TypeGuard[R]]: ...
+
@overload
def function(self, func: Fn[P, R]) -> Fn[P, R]: ...
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index 3c9ee9645c..e5309fa601 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -20,7 +20,10 @@ from typing import (
TYPE_CHECKING,
Any,
Callable,
+ Generic,
Optional,
+ ParamSpec,
+ TypeVar,
Union,
cast,
overload,
@@ -69,8 +72,11 @@ if TYPE_CHECKING:
from marimo._runtime.dataflow import DirectedGraph
from marimo._save.stores import Store
+P = ParamSpec("P")
+R = TypeVar("R")
-class _cache_call(CacheContext):
+
+class _cache_call(CacheContext, Generic[P, R]):
"""Like functools.cache but notebook-aware. See `cache` docstring"""
__slots__ = (
@@ -372,7 +378,7 @@ class _cache_call(CacheContext):
def __get__(
self, instance: Any, _owner: Optional[type] = None
- ) -> _cache_call:
+ ) -> _cache_call[P, R]:
"""Enable @cache as a method decorator.
__get__ is invoked on instance access;
@@ -414,7 +420,7 @@ class _cache_call(CacheContext):
return copy
return self
- def __call__(self, *args: Any, **kwargs: Any) -> Any:
+ def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
# Capture the deferred call case
if self.__wrapped__ is None:
if len(args) != 1:
@@ -422,8 +428,9 @@ class _cache_call(CacheContext):
"cache() takes at most 1 argument (expecting function)"
)
# Check if the function is async - if so, create async variant
- if inspect.iscoroutinefunction(args[0]):
- async_copy = _cache_call_async(
+ fn = cast(Callable[..., Any], args[0])
+ if inspect.iscoroutinefunction(fn):
+ async_copy: _cache_call_async[P, R] = _cache_call_async(
None,
self._loader_partial,
pin_modules=self.pin_modules,
@@ -431,13 +438,13 @@ class _cache_call(CacheContext):
)
async_copy._frame_offset = self._frame_offset
async_copy._frame_offset -= 4
- async_copy._set_context(args[0])
- return async_copy
+ async_copy._set_context(fn)
+ return async_copy # type: ignore[return-value]
# Remove the additional frames from singledispatch, because invoking
# the function directly.
self._frame_offset -= 4
- self._set_context(args[0])
- return self
+ self._set_context(fn)
+ return self # type: ignore[return-value]
# Prepare execution context
scope, ctx, attempt = self._prepare_call_execution(args, kwargs)
@@ -447,7 +454,7 @@ class _cache_call(CacheContext):
try:
if attempt.hit:
attempt.restore(scope)
- return attempt.meta.get("return")
+ return cast(R, attempt.meta.get("return"))
start_time = time.time()
response = self.__wrapped__(*args, **kwargs)
@@ -462,10 +469,10 @@ class _cache_call(CacheContext):
if ctx and not failed:
ctx.cell_lifecycle_registry.add(SideEffect(attempt.hash))
self._misses += 1
- return response
+ return cast(R, response)
-class _cache_call_async(_cache_call):
+class _cache_call_async(_cache_call[P, R]):
"""Async variant of _cache_call for async/await functions.
Inherits all caching logic from _cache_call but provides an async
@@ -480,11 +487,13 @@ class _cache_call_async(_cache_call):
# WeakKeyDictionary ensures instances are cleaned up when garbage collected
# Key: cache instance, Value: dict of {cache_key: Task}
_pending_executions: weakref.WeakKeyDictionary[
- _cache_call_async, dict[str, asyncio.Task[Any]]
+ _cache_call_async[Any, Any], dict[str, asyncio.Task[Any]]
] = weakref.WeakKeyDictionary()
_pending_lock = threading.Lock()
- async def __call__(self, *args: Any, **kwargs: Any) -> Any:
+ async def __call__( # type: ignore[override]
+ self, *args: P.args, **kwargs: P.kwargs
+ ) -> R:
# Capture the deferred call case
if self.__wrapped__ is None:
if len(args) != 1:
@@ -494,8 +503,8 @@ class _cache_call_async(_cache_call):
# Remove the additional frames from singledispatch, because invoking
# the function directly.
self._frame_offset -= 4
- self._set_context(args[0])
- return self
+ self._set_context(cast(Callable[..., Any], args[0]))
+ return self # type: ignore[return-value]
# Prepare execution context to get cache key
scope, ctx, attempt = self._prepare_call_execution(args, kwargs)
@@ -514,7 +523,7 @@ class _cache_call_async(_cache_call):
# Await the existing task AFTER releasing the lock to avoid deadlock
if existing_task is not None:
- return await existing_task
+ return cast(R, await existing_task)
# No pending execution - create a new task
task = asyncio.create_task(
@@ -535,7 +544,7 @@ class _cache_call_async(_cache_call):
if not pending and self in self._pending_executions:
del self._pending_executions[self]
- return result
+ return cast(R, result)
async def _execute_cached(
self,
@@ -790,7 +799,7 @@ def _cache_invocation(
*args: Any,
frame_offset: int = 1,
**kwargs: Any,
-) -> Union[_cache_call, _cache_context]:
+) -> Union[_cache_call[Any, Any], _cache_context]:
del loader, args, kwargs, frame_offset
raise TypeError(f"Invalid type for cache: {type(arg)}")
@@ -801,7 +810,7 @@ def _invoke_call(
*args: Any,
frame_offset: int = 1,
**kwargs: Any,
-) -> Union[_cache_call, _cache_call_async]:
+) -> Union[_cache_call[Any, Any], _cache_call_async[Any, Any]]:
if isinstance(loader, Loader):
raise TypeError(
"A loader instance cannot be passed to cache directly. "
@@ -840,7 +849,7 @@ def _invoke_call_none(
*args: Any,
frame_offset: int = 1,
**kwargs: Any,
-) -> _cache_call:
+) -> _cache_call[Any, Any]:
return _invoke_call(
_fn, loader, *args, frame_offset=frame_offset + 1, **kwargs
)
@@ -854,7 +863,7 @@ def _invoke_call_fn(
*args: Any,
frame_offset: int = 1,
**kwargs: Any,
-) -> Union[_cache_call, _cache_call_async]:
+) -> Union[_cache_call[Any, Any], _cache_call_async[Any, Any]]:
return _invoke_call(
_fn, loader, *args, frame_offset=frame_offset + 1, **kwargs
)
@@ -888,10 +897,18 @@ def _invoke_context(
@overload
def cache(
- fn: Optional[Callable[..., Any]] = None,
+ fn: Callable[P, R],
+ pin_modules: bool = False,
+ loader: LoaderPartial | LoaderType = MemoryLoader,
+) -> _cache_call[P, R]: ...
+
+
+@overload
+def cache(
+ fn: None = None,
pin_modules: bool = False,
loader: LoaderPartial | LoaderType = MemoryLoader,
-) -> _cache_call: ...
+) -> Callable[[Callable[P, R]], _cache_call[P, R]]: ...
@overload
@@ -910,7 +927,7 @@ def cache( # type: ignore[misc]
_frame_offset: int = 1,
_internal_interface_not_for_external_use: None = None,
**kwargs: Any,
-) -> Union[_cache_call, _cache_context]:
+) -> Union[_cache_call[..., Any], _cache_context]:
"""## Cache the value of a function based on args and closed-over variables.
Decorating a function with `@mo.cache` will cache its value based on
@@ -997,10 +1014,18 @@ def cache( # type: ignore[misc]
@overload
def lru_cache(
- fn: Optional[Callable[..., Any]] = None,
+ fn: Callable[P, R],
+ maxsize: int = 128,
+ pin_modules: bool = False,
+) -> _cache_call[P, R]: ...
+
+
+@overload
+def lru_cache(
+ fn: None = None,
maxsize: int = 128,
pin_modules: bool = False,
-) -> _cache_call: ...
+) -> Callable[[Callable[P, R]], _cache_call[P, R]]: ...
@overload
@@ -1008,7 +1033,7 @@ def lru_cache(
name: str,
maxsize: int = 128,
pin_modules: bool = False,
-) -> _cache_call: ...
+) -> _cache_context: ...
def lru_cache( # type: ignore[misc]
@@ -1018,7 +1043,7 @@ def lru_cache( # type: ignore[misc]
pin_modules: bool = False,
_internal_interface_not_for_external_use: None = None,
**kwargs: Any,
-) -> Union[_cache_call, _cache_context]:
+) -> Union[_cache_call[..., Any], _cache_context]:
"""Decorator for LRU caching the return value of a function.
`mo.lru_cache` is a version of `mo.cache` with a bounded cache size. As an
@@ -1063,7 +1088,7 @@ def lru_cache( # type: ignore[misc]
)
return cast(
- Union[_cache_call, _cache_context],
+ Union[_cache_call[..., Any], _cache_context],
cache( # type: ignore[call-overload]
arg,
*args,
@@ -1090,7 +1115,7 @@ def persistent_cache(
save_path: str | None = None,
method: LoaderKey = "pickle",
pin_modules: bool = False,
-) -> _cache_call: ...
+) -> _cache_call[..., Any]: ...
def persistent_cache( # type: ignore[misc]
@@ -1103,7 +1128,7 @@ def persistent_cache( # type: ignore[misc]
pin_modules: bool = False,
_internal_interface_not_for_external_use: None = None,
**kwargs: Any,
-) -> Union[_cache_call, _cache_context]:
+) -> Union[_cache_call[..., Any], _cache_context]:
"""## Context manager to save variables to disk and restore them thereafter.
The `mo.persistent_cache` context manager lets you delimit a block of code
@@ -1212,7 +1237,7 @@ def persistent_cache( # type: ignore[misc]
raise TypeError("Do not use fn directly, use positional arguments.")
return cast(
- Union[_cache_call, _cache_context],
+ Union[_cache_call[..., Any], _cache_context],
cache( # type: ignore[call-overload]
arg,
*args,
diff --git a/pyproject.toml b/pyproject.toml
index eb6ea048b8..179b18f9a4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -207,6 +207,8 @@ test-optional = [
"pyzmq>=27.1.0",
# weave tracing integration
"weave>=0.51.0",
+ # For type-checking tests
+ "basedpyright>=1.28.0",
]
diff --git a/tests/_ast/test_app_typing.py b/tests/_ast/test_app_typing.py
new file mode 100644
index 0000000000..ba8e9c125c
--- /dev/null
+++ b/tests/_ast/test_app_typing.py
@@ -0,0 +1,157 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import shutil
+import subprocess
+import sys
+import tempfile
+import textwrap
+from pathlib import Path
+
+import pytest
+
+pytestmark = pytest.mark.skipif(
+ shutil.which("basedpyright") is None,
+ reason="basedpyright not installed",
+)
+
+
+def _check_pyright(code: str) -> None:
+ """Run basedpyright on *code* and assert zero errors."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ p = Path(tmpdir) / "check.py"
+ p.write_text(textwrap.dedent(code))
+ result = subprocess.run(
+ [
+ "basedpyright",
+ "--pythonpath",
+ sys.executable,
+ "--level",
+ "error",
+ str(p),
+ ],
+ capture_output=True,
+ text=True,
+ )
+ assert result.returncode == 0, (
+ f"basedpyright exited with code {result.returncode}\n"
+ f"STDOUT:\n{result.stdout}\n"
+ f"STDERR:\n{result.stderr}"
+ )
+
+
+_PREAMBLE = """
+ from typing_extensions import TypeGuard, TypeIs, assert_type
+ import marimo as mo
+
+ def _int_or_str() -> int | str:
+ return 0
+"""
+
+
+class TestAppFunctionTyping:
+ def test_typeis_narrowing(self) -> None:
+ _check_pyright("""
+ from typing_extensions import TypeIs, assert_type
+ import marimo
+
+ app = marimo.App()
+
+ @app.function
+ def is_int(x: object) -> TypeIs[int]:
+ return isinstance(x, int)
+
+ def _int_or_str() -> int | str:
+ return 0
+
+ val = _int_or_str()
+ if is_int(val):
+ assert_type(val, int)
+ """)
+
+ def test_typeguard_narrowing(self) -> None:
+ _check_pyright("""
+ from typing_extensions import TypeGuard, assert_type
+ import marimo
+
+ app = marimo.App()
+
+ @app.function
+ def guard_int(x: object) -> TypeGuard[int]:
+ return isinstance(x, int)
+
+ def _int_or_str() -> int | str:
+ return 0
+
+ val = _int_or_str()
+ if guard_int(val):
+ assert_type(val, int)
+ """)
+
+ def test_regular_function_signature(self) -> None:
+ _check_pyright("""
+ from typing_extensions import assert_type
+ import marimo
+
+ app = marimo.App()
+
+ @app.function
+ def add(a: int, b: int) -> int:
+ return a + b
+
+ assert_type(add(1, 2), int)
+ """)
+
+
+class TestCacheTyping:
+ def test_cache_preserves_return_type(self) -> None:
+ _check_pyright(
+ _PREAMBLE
+ + """
+ @mo.cache
+ def compute(x: int) -> int:
+ return x * 2
+
+ assert_type(compute(1), int)
+"""
+ )
+
+ def test_cache_exposes_cache_info(self) -> None:
+ _check_pyright(
+ _PREAMBLE
+ + """
+ @mo.cache
+ def compute(x: int) -> int:
+ return x * 2
+
+ info = compute.cache_info()
+ compute.cache_clear()
+"""
+ )
+
+
+class TestLruCacheTyping:
+ def test_lru_cache_preserves_return_type(self) -> None:
+ _check_pyright(
+ _PREAMBLE
+ + """
+ @mo.lru_cache
+ def compute(x: int) -> int:
+ return x * 2
+
+ assert_type(compute(1), int)
+"""
+ )
+
+ def test_lru_cache_exposes_cache_info(self) -> None:
+ _check_pyright(
+ _PREAMBLE
+ + """
+ @mo.lru_cache
+ def compute(x: int) -> int:
+ return x * 2
+
+ info = compute.cache_info()
+ compute.cache_clear()
+"""
+ )