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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: mo.Thread (#2671)
Akshay Agrawalbef041603203
diff --git a/docs/api/miscellaneous.md b/docs/api/miscellaneous.mdindex 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__.pyindex 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 Threadfrom marimo._save.save import cache, lru_cache, persistent_cachefrom marimo._server.asgi import create_asgi_appfrom marimo._sql.sql import sqldiff --git a/marimo/_cli/run_docker.py b/marimo/_cli/run_docker.pyindex 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 annotationsimport subprocessdiff --git a/marimo/_data/sql_summaries.py b/marimo/_data/sql_summaries.pyindex 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 annotationsfrom typing import List, Tuplediff --git a/marimo/_runtime/threads.py b/marimo/_runtime/threads.pynew file mode 100644index 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.pynew file mode 100644index 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.pyindex 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 annotationsimport sysdiff --git a/tests/_runtime/test_threads.py b/tests/_runtime/test_threads.pynew file mode 100644index 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"]