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: mo.Thread (#2671)

Akshay Agrawalbef041603203
diff --git a/docs/api/miscellaneous.md b/docs/api/miscellaneous.md
index 7d4eaeafa9..f64a4d558b 100644
--- a/docs/api/miscellaneous.md
+++ b/docs/api/miscellaneous.md
@@ -15,3 +15,7 @@
```{eval-rst}
.. autofunction:: marimo.notebook_dir
```
+
+```{eval-rst}
+.. autoclass:: marimo.Thread
+```
diff --git a/marimo/__init__.py b/marimo/__init__.py
index b4c5f0c68a..2999de2e04 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -23,6 +23,7 @@ __all__ = [
"create_asgi_app",
"MarimoIslandGenerator",
"MarimoStopError",
+ "Thread",
# Other namespaces
"ai",
"ui",
@@ -130,6 +131,7 @@ from marimo._runtime.runtime import (
refs,
)
from marimo._runtime.state import state
+from marimo._runtime.threads import Thread
from marimo._save.save import cache, lru_cache, persistent_cache
from marimo._server.asgi import create_asgi_app
from marimo._sql.sql import sql
diff --git a/marimo/_cli/run_docker.py b/marimo/_cli/run_docker.py
index 5ab154680f..b2222130f9 100644
--- a/marimo/_cli/run_docker.py
+++ b/marimo/_cli/run_docker.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
import subprocess
diff --git a/marimo/_data/sql_summaries.py b/marimo/_data/sql_summaries.py
index bfaa65799c..6ba527d44f 100644
--- a/marimo/_data/sql_summaries.py
+++ b/marimo/_data/sql_summaries.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
from typing import List, Tuple
diff --git a/marimo/_runtime/threads.py b/marimo/_runtime/threads.py
new file mode 100644
index 0000000000..39c6a66f6e
--- /dev/null
+++ b/marimo/_runtime/threads.py
@@ -0,0 +1,34 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import threading
+from typing import Any
+
+from marimo._runtime.context.types import (
+ RuntimeContext,
+ get_context,
+ initialize_context,
+ runtime_context_installed,
+)
+
+
+class Thread(threading.Thread):
+ """A Thread subclass that is aware of marimo internals.
+
+ `mo.Thread` has the same API as threading.Thread,
+ but `mo.Thread`s are able to communicate with the marimo
+ frontend, whereas `threading.Thread` can't.
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+
+ self._marimo_ctx: RuntimeContext | None = None
+
+ if runtime_context_installed():
+ self._marimo_ctx = get_context()
+
+ def run(self) -> None:
+ if self._marimo_ctx is not None:
+ initialize_context(self._marimo_ctx)
+ super().run()
diff --git a/marimo/_smoke_tests/threads.py b/marimo/_smoke_tests/threads.py
new file mode 100644
index 0000000000..eb2672d829
--- /dev/null
+++ b/marimo/_smoke_tests/threads.py
@@ -0,0 +1,41 @@
+import marimo
+
+__generated_with = "0.9.10"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __():
+ def foo():
+ print("hi")
+ return (foo,)
+
+
+def __():
+ import threading
+ return (threading,)
+
+
+def __(foo, mo, threading):
+ with mo.redirect_stdout():
+ threading.Thread(target=foo).start()
+ return
+
+
+def __(foo, mo):
+ with mo.redirect_stdout():
+ mo.Thread(target=foo).start()
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.py
index 7dada53f31..89c2524243 100644
--- a/marimo/_utils/narwhals_utils.py
+++ b/marimo/_utils/narwhals_utils.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
import sys
diff --git a/tests/_runtime/test_threads.py b/tests/_runtime/test_threads.py
new file mode 100644
index 0000000000..b3cd4f3c94
--- /dev/null
+++ b/tests/_runtime/test_threads.py
@@ -0,0 +1,35 @@
+import time
+
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+
+async def test_set_ui_element_value_lensed(
+ any_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ """Test setting the value of a lensed element.
+
+ Make sure reactivity flows through its parent, and that its on_change
+ handler is called exactly once.
+ """
+ k = any_kernel
+
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("ctx_main = mo._runtime.context.get_context()"),
+ exec_req.get(
+ """
+ ctx_thread = None
+ def target():
+ global ctx_thread
+ ctx_thread = mo._runtime.context.get_context()
+ mo.Thread(target=target).start().join()
+ """
+ ),
+ ]
+ )
+
+ # thread run should be basically instantaneous, but sleep just in case ...
+ time.sleep(0.01) # noqa: ASYNC251
+ assert k.globals["ctx_main"] == k.globals["ctx_thread"]