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
fix: propagate notebook `__doc__` to cell execution namespace (#8634) (#8636)
Myles Scolnick7de9b9f12d35
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.pyindex 57f0771010..7251960322 100644--- a/marimo/_pyodide/bootstrap.py+++ b/marimo/_pyodide/bootstrap.py@@ -20,6 +20,7 @@ from marimo._runtime.commands import (SerializedQueryParams,UpdateUIElementCommand,)+from marimo._runtime.patches import extract_docstring_from_headerfrom marimo._server.app_defaults import AppDefaultsfrom marimo._server.models.models import SaveNotebookRequestfrom marimo._session.model import SessionMode@@ -145,6 +146,9 @@ def create_session(cli_args={},argv=[],app_config=app.config,+ docstring=extract_docstring_from_header(+ app_file_manager.app._app._header+ ),),user_config,)diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex cc62a35489..ead95cfd97 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -483,6 +483,7 @@ def _launch_pyodide_kernel(file=app_metadata.filename,input_override=input_override,print_override=None,+ doc=app_metadata.docstring,),enqueue_control_request=_enqueue_control_request,debugger_override=debugger,diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.pyindex 90ee7a98d7..1f94d9c682 100644--- a/marimo/_runtime/app/kernel_runner.py+++ b/marimo/_runtime/app/kernel_runner.py@@ -15,7 +15,10 @@ from marimo._runtime.commands import (UpdateUIElementCommand,)from marimo._runtime.context.types import get_context-from marimo._runtime.patches import create_main_module+from marimo._runtime.patches import (+ create_main_module,+ extract_docstring_from_header,+)from marimo._runtime.runner import cell_runner, hook_contextfrom marimo._session.model import SessionModefrom marimo._types.ids import CellId_t@@ -119,7 +122,10 @@ class AppKernelRunner:stderr=None,stdin=None,module=create_main_module(- filename, input_override=None, print_override=None+ filename,+ input_override=None,+ print_override=None,+ doc=extract_docstring_from_header(app._app._header),),user_config=DEFAULT_CONFIG,enqueue_control_request=lambda _: None,diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.pyindex f6551cd10f..0b14d944b9 100644--- a/marimo/_runtime/app/script_runner.py+++ b/marimo/_runtime/app/script_runner.py@@ -26,6 +26,7 @@ from marimo._runtime.executor import ()from marimo._runtime.patches import (create_main_module,+ extract_docstring_from_header,patch_main_module_context,)from marimo._types.ids import CellId_t@@ -45,6 +46,7 @@ class AppScriptRunner:) -> None:self.app = appself.filename = filename+ self._docstring = extract_docstring_from_header(app._app._header)self.cells_cancelled: set[CellId_t] = set()self._glbls = glbls if glbls else {}@@ -83,7 +85,10 @@ class AppScriptRunner:) -> RunOutput:with patch_main_module_context(create_main_module(- file=self.filename, input_override=None, print_override=None+ file=self.filename,+ input_override=None,+ print_override=None,+ doc=self._docstring,)) as module:glbls = module.__dict__@@ -125,7 +130,10 @@ class AppScriptRunner:) -> RunOutput:with patch_main_module_context(create_main_module(- file=self.filename, input_override=None, print_override=None+ file=self.filename,+ input_override=None,+ print_override=None,+ doc=self._docstring,)) as module:glbls = module.__dict__diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.pyindex 2c92acbf50..cde38d176d 100644--- a/marimo/_runtime/commands.py+++ b/marimo/_runtime/commands.py@@ -442,6 +442,7 @@ class AppMetadata(msgspec.Struct, rename="camel"):app_config: Application-level configuration.argv: Full argument vector if available.filename: Path to the notebook file.+ docstring: Module docstring extracted from the notebook header."""query_params: SerializedQueryParams@@ -450,6 +451,7 @@ class AppMetadata(msgspec.Struct, rename="camel"):argv: Union[list[str], None] = Nonefilename: Optional[str] = None+ docstring: Optional[str] = Noneclass UpdateCellConfigCommand(Command):diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.pyindex 07d1f3e24c..6bbafd030a 100644--- a/marimo/_runtime/patches.py+++ b/marimo/_runtime/patches.py@@ -1,6 +1,7 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import astimport contextlibimport functoolsimport sys@@ -8,6 +9,7 @@ import textwrapimport typesfrom typing import TYPE_CHECKING, Any, Callable+from marimo._ast.parse import ast_parsefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._runtime import marimo_browser, marimo_pdbfrom marimo._utils.platform import is_pyodide@@ -169,15 +171,28 @@ del Loader; del MetaPathFinderdel glbls["sys"]+def extract_docstring_from_header(header: str | None) -> str | None:+ """Extract the Python docstring value from a notebook header string."""+ if not header:+ return None+ try:+ tree = ast_parse(header)+ return ast.get_docstring(tree)+ except (SyntaxError, ValueError):+ return None++def create_main_module(file: str | None,input_override: Callable[[Any], str] | None,print_override: Callable[[Any], None] | None,+ doc: str | None = None,) -> types.ModuleType:# Every kernel gets its own main module, whose __dict__ attribute# serves as the global namespace_module = types.ModuleType(- "__main__", doc="Created for the marimo kernel."+ "__main__",+ doc=doc if doc is not None else "Created for the marimo kernel.",)_module.__dict__.setdefault("__builtin__", globals()["__builtins__"])_module.__dict__.setdefault("__builtins__", globals()["__builtins__"])@@ -205,13 +220,14 @@ def patch_main_module(file: str | None,input_override: Callable[[Any], str] | None,print_override: Callable[[Any], None] | None,+ doc: str | None = None,) -> types.ModuleType:"""Patches __main__ module- Makes functions pickleable- Loads some overrides and mocks into globals"""- _module = create_main_module(file, input_override, print_override)+ _module = create_main_module(file, input_override, print_override, doc=doc)# TODO(akshayka): In run mode, this can introduce races between different# kernel threads, since they each share sys.modules. Unfortunately, Pythondiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex cda289b7b1..cc00c0073a 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -1043,6 +1043,14 @@ class Kernel:if name in self.globals:del self.globals[name]+ # Restore module-level __doc__ so it doesn't fall+ # through to builtins.__doc__+ if name == "__doc__":+ self.globals["__doc__"] = (+ self.app_metadata.docstring+ or "Created for the marimo kernel."+ )+if ("__annotations__" in self.globalsand name in self.globals["__annotations__"]@@ -3506,6 +3514,7 @@ def launch_kernel(file=app_metadata.filename,input_override=input_override,print_override=print_override,+ doc=app_metadata.docstring,),debugger_override=debugger,user_config=user_config,diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex c5f542b48d..182916a3e8 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -29,6 +29,7 @@ from marimo._messaging.serde import deserialize_kernel_messagefrom marimo._messaging.types import KernelMessagefrom marimo._output.hypertext import patch_html_for_non_interactive_outputfrom marimo._runtime.commands import AppMetadata, SerializedCLIArgs+from marimo._runtime.patches import extract_docstring_from_headerfrom marimo._schemas.serialization import NotebookSerializationfrom marimo._server.export.exporter import Exporterfrom marimo._server.file_router import AppFileRouter@@ -511,6 +512,9 @@ async def run_app_until_completion(cli_args=cli_args,argv=argv,app_config=file_manager.app.config,+ docstring=extract_docstring_from_header(+ file_manager.app._app._header+ ),),app_file_manager=file_manager,config_manager=config_manager,diff --git a/marimo/_server/session_manager.py b/marimo/_server/session_manager.pyindex 6cb9db852d..a1c525fa61 100644--- a/marimo/_server/session_manager.py+++ b/marimo/_server/session_manager.py@@ -189,6 +189,7 @@ class SessionManager:# Create the sessionfrom marimo._runtime.commands import AppMetadata+ from marimo._runtime.patches import extract_docstring_from_headerextensions: list[SessionExtension] = []if self.watch:@@ -209,6 +210,9 @@ class SessionManager:cli_args=self.cli_args,argv=self.argv,app_config=app_file_manager.app.config,+ docstring=extract_docstring_from_header(+ app_file_manager.app._app._header+ ),),app_file_manager=app_file_manager,config_manager=self._config_manager,diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex 87f798a9d9..6a71612099 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -93,6 +93,33 @@ class TestApp:assert (defs["y"], defs["z"]) == (1, 2)assert defs["a"] == 2+ @staticmethod+ def test_run_with_docstring() -> None:+ """Test that __doc__ returns the notebook's docstring."""+ app = App()+ app._header = '"""This is a test"""'++ @app.cell+ def _() -> tuple[object]:+ doc = __doc__ # noqa: F821+ return (doc,)++ _, defs = app.run()+ assert defs["doc"] == "This is a test"++ @staticmethod+ def test_run_with_no_docstring() -> None:+ """Test that __doc__ has a default when no header docstring."""+ app = App()++ @app.cell+ def _() -> tuple[object]:+ doc = __doc__ # noqa: F821+ return (doc,)++ _, defs = app.run()+ assert defs["doc"] == "Created for the marimo kernel."+@staticmethoddef test_run_with_refs() -> None:"""Test that app.run() can override variables with provided defs."""diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex f36b9e1316..8fe7cbb1c4 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -149,6 +149,22 @@ class TestExecution:assert "y" not in k.globalsassert "z" not in k.globals+ async def test_delete_cell_restores_doc(self, any_kernel: Kernel) -> None:+ k = any_kernel+ # Simulate a notebook with a docstring in its header+ k.app_metadata.docstring = "Notebook docstring"+ k.globals["__doc__"] = "Notebook docstring"++ await k.run(+ [+ ExecuteCellCommand(cell_id="0", code='__doc__ = "cell doc"'),+ ]+ )+ assert k.globals["__doc__"] == "cell doc"++ await k.delete_cell(DeleteCellCommand(cell_id="0"))+ assert k.globals["__doc__"] == "Notebook docstring"+async def test_run_referrers_not_stale(self, any_kernel: Kernel) -> None:k = any_kernelgraph = k.graph