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: CLI args when running as a script (#1150)

Akshay Agrawal07ba1ba690b7
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 74b34fe3d6..9ff9161fac 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -32,13 +32,17 @@ from marimo._ast.errors import (
UnparsableError,
)
from marimo._messaging.mimetypes import KnownMimeType
+from marimo._messaging.types import NoopStream
from marimo._output.rich_help import mddoc
from marimo._runtime import dataflow
+from marimo._runtime.context.types import teardown_context
from marimo._runtime.patches import patch_main_module_context
if TYPE_CHECKING:
from collections.abc import Sequence
+ from marimo._runtime.context.types import ExecutionContext
+
LOGGER = _loggers.marimo_logger()
@@ -132,6 +136,7 @@ class App:
self._cell_manager = CellManager()
self._graph = dataflow.DirectedGraph()
+ self._execution_context: ExecutionContext | None = None
self._runner = dataflow.Runner(self._graph)
self._unparsable = False
@@ -245,6 +250,8 @@ class App:
)
def _run_sync(self) -> tuple[Sequence[Any], dict[str, Any]]:
+ from marimo._runtime.context.types import ExecutionContext
+
# No need to provide `file`, `input_override` here, since this
# function is only called when running as a script
with patch_main_module_context() as module:
@@ -254,10 +261,15 @@ class App:
for cid in self._execution_order:
cell = self._cell_manager.cell_data_at(cid).cell
if cell is not None:
+ self._execution_context = ExecutionContext(
+ cell_id=cid, setting_element_value=False
+ )
outputs[cid] = execute_cell(cell._cell, glbls)
return self._outputs_and_defs(outputs, glbls)
async def _run_async(self) -> tuple[Sequence[Any], dict[str, Any]]:
+ from marimo._runtime.context.types import ExecutionContext
+
# No need to provide `file`, `input_override` here, since this
# function is only called when running as a script
with patch_main_module_context() as module:
@@ -267,26 +279,26 @@ class App:
for cid in self._execution_order:
cell = self._cell_manager.cell_data_at(cid).cell
if cell is not None:
+ self._execution_context = ExecutionContext(
+ cell_id=cid, setting_element_value=False
+ )
outputs[cid] = await execute_cell_async(cell._cell, glbls)
+ self._execution_context = None
return self._outputs_and_defs(outputs, glbls)
def run(self) -> tuple[Sequence[Any], dict[str, Any]]:
- # formatters aren't automatically registered when running as a script
- from marimo._output.formatters.formatters import (
- register_formatters,
+ from marimo._runtime.context.script_context import (
+ initialize_script_context,
)
- from marimo._output.formatting import FORMATTERS
-
- if not FORMATTERS:
- register_formatters()
+ from marimo._runtime.context.types import runtime_context_installed
if self._unparsable:
raise UnparsableError(
"This app can't be run because it has unparsable cells."
)
-
self._maybe_initialize()
+
is_async = False
for cell in self._cell_manager.cells():
if cell is None:
@@ -299,10 +311,31 @@ class App:
is_async = True
break
- if is_async:
- return asyncio.run(self._run_async())
- else:
- return self._run_sync()
+ installed_script_context = False
+ try:
+ if not runtime_context_installed():
+ initialize_script_context(
+ app=InternalApp(self), stream=NoopStream()
+ )
+ installed_script_context = True
+
+ # formatters aren't automatically registered when running as a
+ # script
+ from marimo._output.formatters.formatters import (
+ register_formatters,
+ )
+ from marimo._output.formatting import FORMATTERS
+
+ if not FORMATTERS:
+ register_formatters()
+
+ if is_async:
+ return asyncio.run(self._run_async())
+ else:
+ return self._run_sync()
+ finally:
+ if installed_script_context:
+ teardown_context()
async def _run_cell_async(
self, cell: Cell, kwargs: dict[str, Any]
@@ -484,6 +517,15 @@ class InternalApp:
def cell_manager(self) -> CellManager:
return self._app._cell_manager
+ @property
+ def graph(self) -> dataflow.DirectedGraph:
+ self._app._maybe_initialize()
+ return self._app._graph
+
+ @property
+ def execution_context(self) -> ExecutionContext | None:
+ return self._app._execution_context
+
@property
def runner(self) -> dataflow.Runner:
self._app._maybe_initialize()
diff --git a/marimo/_cli/parse_args.py b/marimo/_cli/parse_args.py
index 4551cbb8c0..caf8b49e49 100644
--- a/marimo/_cli/parse_args.py
+++ b/marimo/_cli/parse_args.py
@@ -1,13 +1,17 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any
+import sys
+from typing import TYPE_CHECKING, Any
from marimo._runtime.requests import SerializedCLIArgs
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
def parse_args(
- args: tuple[str],
+ args: Iterable[str],
) -> SerializedCLIArgs:
"""
Parse command line arguments into a dictionary.
@@ -72,3 +76,7 @@ def parse_args(
args_dict[key] = value
return args_dict
+
+
+def args_from_argv() -> SerializedCLIArgs:
+ return parse_args(sys.argv[1:])
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.py
index 1ff792e3d6..0cb6306845 100644
--- a/marimo/_plugins/stateless/mpl/_mpl.py
+++ b/marimo/_plugins/stateless/mpl/_mpl.py
@@ -280,9 +280,9 @@ def interactive(figure: "Figure | Axes") -> Html: # type: ignore[name-defined]
return True
figure_managers.add(figure_manager)
- assert ctx.kernel.execution_context is not None
+ assert ctx.execution_context is not None
ctx.cell_lifecycle_registry.add(CleanupHandle())
- ctx.stream.cell_id = ctx.kernel.execution_context.cell_id
+ ctx.stream.cell_id = ctx.execution_context.cell_id
content = _template(host, port, str(figure_manager.num))
diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.py
index 92bfa35a19..60ec15a9a2 100644
--- a/marimo/_plugins/ui/_core/registry.py
+++ b/marimo/_plugins/ui/_core/registry.py
@@ -37,15 +37,15 @@ class UIElementRegistry:
object_id: UIElementId,
ui_element: UIElement[Any, Any],
) -> None:
- kernel = get_context().kernel
+ execution_context = get_context().execution_context
if object_id in self._objects:
# on cell re-run, a UI element may be (re)-registered before
# its destructor was called, so manually delete the old element
# here
self.delete(object_id, id(self._objects[object_id]))
self._objects[object_id] = weakref.ref(ui_element)
- assert kernel.execution_context is not None
- self._constructing_cells[object_id] = kernel.execution_context.cell_id
+ assert execution_context is not None
+ self._constructing_cells[object_id] = execution_context.cell_id
# bindings must be lazily registered, since there aren't any
# bindings at UIElement object creation time
if object_id in self._bindings:
@@ -94,10 +94,13 @@ class UIElementRegistry:
return bindings
def _register_bindings(self, object_id: UIElementId) -> None:
- kernel = get_context().kernel
- self._bindings[object_id] = self._find_bindings_in_namespace(
- object_id, kernel.globals
- )
+ from marimo._runtime.context.kernel_context import KernelRuntimeContext
+
+ ctx = get_context()
+ if isinstance(ctx, KernelRuntimeContext):
+ self._bindings[object_id] = self._find_bindings_in_namespace(
+ object_id, ctx.globals
+ )
def get_object(self, object_id: UIElementId) -> UIElement[Any, Any]:
if object_id not in self._objects:
@@ -169,3 +172,41 @@ class UIElementRegistry:
del self._bindings[object_id]
if object_id in self._constructing_cells:
del self._constructing_cells[object_id]
+
+
+class NoopUIElementRegistry(UIElementRegistry):
+ def __init__(self) -> None:
+ pass
+
+ def register(
+ self,
+ object_id: UIElementId,
+ ui_element: UIElement[Any, Any],
+ ) -> None:
+ del object_id
+ del ui_element
+ pass
+
+ def bound_names(self, object_id: UIElementId) -> Iterable[str]:
+ del object_id
+ return []
+
+ def get_object(self, object_id: UIElementId) -> UIElement[Any, Any]:
+ del object_id
+ raise NotImplementedError
+
+ def get_cell(self, object_id: UIElementId) -> CellId_t:
+ del object_id
+ raise NotImplementedError
+
+ def resolve_lens(
+ self, object_id: UIElementId, value: LensValue[T]
+ ) -> tuple[str, LensValue[T]]:
+ del object_id
+ del value
+ raise NotImplementedError
+
+ def delete(self, object_id: UIElementId, python_id: int) -> None:
+ del object_id
+ del python_id
+ pass
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index d9ca85dbba..f04aedac3c 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -192,9 +192,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
# TODO(akshayka): parametrize UIElement with an optional
# string ID, so users can provide their own IDs to make
# sure a mismatch never happens ...
- initial_value = cast(
- S, ctx.kernel.get_ui_initial_value(self._id)
- )
+ initial_value = cast(S, ctx.get_ui_initial_value(self._id))
except KeyError:
# we weren't asked to override the UI element's value
pass
@@ -262,10 +260,10 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
return self._value
if (
- ctx.kernel.execution_context is not None
- and not ctx.kernel.execution_context.setting_element_value
+ ctx.execution_context is not None
+ and not ctx.execution_context.setting_element_value
and (
- ctx.kernel.execution_context.cell_id
+ ctx.execution_context.cell_id
== ctx.ui_element_registry.get_cell(self._id)
)
):
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 6e7b77b3a3..12c2055691 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -20,7 +20,7 @@ from marimo._pyodide.streams import (
PyodideStream,
)
from marimo._runtime import handlers, patches, requests
-from marimo._runtime.context import initialize_context
+from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.input_override import input_override
from marimo._runtime.marimo_pdb import MarimoPdb
from marimo._runtime.requests import (
@@ -390,7 +390,7 @@ def launch_pyodide_kernel(
debugger_override=debugger,
user_config=user_config,
)
- initialize_context(
+ initialize_kernel_context(
kernel=kernel,
stream=stream,
virtual_files_supported=False,
diff --git a/marimo/_runtime/cell_lifecycle_item.py b/marimo/_runtime/cell_lifecycle_item.py
index 0ee13bb697..14eeb89d79 100644
--- a/marimo/_runtime/cell_lifecycle_item.py
+++ b/marimo/_runtime/cell_lifecycle_item.py
@@ -5,7 +5,7 @@ import abc
from typing import TYPE_CHECKING
if TYPE_CHECKING:
- from marimo._runtime.context import RuntimeContext
+ from marimo._runtime.context.types import RuntimeContext
class CellLifecycleItem(abc.ABC):
diff --git a/marimo/_runtime/context/__init__.py b/marimo/_runtime/context/__init__.py
new file mode 100644
index 0000000000..9f66370677
--- /dev/null
+++ b/marimo/_runtime/context/__init__.py
@@ -0,0 +1,19 @@
+# Copyright 2024 Marimo. All rights reserved.
+__all__ = [
+ "get_context",
+ "get_global_context",
+ "ContextNotInitializedError",
+ "ExecutionContext",
+ "RuntimeContext",
+ "runtime_context_installed",
+ "teardown_context",
+]
+from marimo._runtime.context.types import (
+ ContextNotInitializedError,
+ ExecutionContext,
+ RuntimeContext,
+ get_context,
+ get_global_context,
+ runtime_context_installed,
+ teardown_context,
+)
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.py
new file mode 100644
index 0000000000..bf0061e667
--- /dev/null
+++ b/marimo/_runtime/context/kernel_context.py
@@ -0,0 +1,101 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from contextlib import contextmanager
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Iterator, Optional
+
+from marimo._plugins.ui._core.ids import IDProvider, NoIDProviderException
+from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistry
+from marimo._runtime.context.types import (
+ ExecutionContext,
+ RuntimeContext,
+ initialize_context,
+)
+from marimo._runtime.dataflow import DirectedGraph
+from marimo._runtime.functions import FunctionRegistry
+from marimo._runtime.params import CLIArgs, QueryParams
+
+if TYPE_CHECKING:
+ from marimo._ast.cell import CellId_t
+ from marimo._messaging.types import Stream
+ from marimo._runtime.runtime import Kernel
+ from marimo._runtime.state import State
+
+
+@dataclass
+class KernelRuntimeContext(RuntimeContext):
+ """Encapsulates runtime state for a session."""
+
+ _kernel: Kernel
+ _id_provider: Optional[IDProvider] = None
+
+ @property
+ def graph(self) -> DirectedGraph:
+ return self._kernel.graph
+
+ @property
+ def execution_context(self) -> ExecutionContext | None:
+ return self._kernel.execution_context
+
+ @property
+ def cell_id(self) -> Optional[CellId_t]:
+ """Get the cell id of the currently executing cell, if any."""
+ if self._kernel.execution_context is not None:
+ return self._kernel.execution_context.cell_id
+ return None
+
+ @property
+ def cli_args(self) -> CLIArgs:
+ """Get the CLI args."""
+ return self._kernel.cli_args
+
+ @property
+ def query_params(self) -> QueryParams:
+ """Get the query params."""
+ return self._kernel.query_params
+
+ @contextmanager
+ def provide_ui_ids(self, prefix: str) -> Iterator[None]:
+ try:
+ self._id_provider = IDProvider(prefix)
+ yield
+ finally:
+ self._id_provider = None
+
+ def take_id(self) -> str:
+ if self._id_provider is None:
+ raise NoIDProviderException
+ return self._id_provider.take_id()
+
+ @property
+ def globals(self) -> dict[str, Any]:
+ return self._kernel.globals
+
+ def get_ui_initial_value(self, object_id: str) -> Any:
+ return self._kernel.get_ui_initial_value(object_id)
+
+ def register_state_update(self, state: State[Any]) -> None:
+ return self._kernel.register_state_update(state)
+
+
+def initialize_kernel_context(
+ kernel: Kernel, stream: Stream, virtual_files_supported: bool = True
+) -> None:
+ """Initializes thread-local/session-specific context.
+
+ Must be called exactly once for each client thread.
+ """
+ from marimo._plugins.ui._core.registry import UIElementRegistry
+ from marimo._runtime.virtual_file import VirtualFileRegistry
+
+ runtime_context = KernelRuntimeContext(
+ _kernel=kernel,
+ ui_element_registry=UIElementRegistry(),
+ function_registry=FunctionRegistry(),
+ cell_lifecycle_registry=CellLifecycleRegistry(),
+ virtual_file_registry=VirtualFileRegistry(),
+ virtual_files_supported=virtual_files_supported,
+ stream=stream,
+ )
+ initialize_context(runtime_context=runtime_context)
diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.py
new file mode 100644
index 0000000000..571e831b61
--- /dev/null
+++ b/marimo/_runtime/context/script_context.py
@@ -0,0 +1,98 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from contextlib import contextmanager
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Iterator, Optional
+
+from marimo._ast.app import InternalApp
+from marimo._cli.parse_args import args_from_argv
+from marimo._plugins.ui._core.ids import NoIDProviderException
+from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistry
+from marimo._runtime.context.types import (
+ ExecutionContext,
+ RuntimeContext,
+ initialize_context,
+)
+from marimo._runtime.dataflow import DirectedGraph
+from marimo._runtime.functions import FunctionRegistry
+from marimo._runtime.params import CLIArgs, QueryParams
+
+if TYPE_CHECKING:
+ from marimo._ast.cell import CellId_t
+ from marimo._messaging.types import Stream
+ from marimo._runtime.state import State
+
+
+@dataclass
+class ScriptRuntimeContext(RuntimeContext):
+ """Encapsulates runtime state when running as a script."""
+
+ _app: InternalApp
+
+ def __post_init__(self) -> None:
+ self._cli_args: CLIArgs | None = None
+ self._query_params = QueryParams({})
+
+ @property
+ def graph(self) -> DirectedGraph:
+ return self._app.graph
+
+ @property
+ def execution_context(self) -> ExecutionContext | None:
+ return self._app.execution_context
+
+ @property
+ def cell_id(self) -> Optional[CellId_t]:
+ """Get the cell id of the currently executing cell, if any."""
+ if self.execution_context is not None:
+ return self.execution_context.cell_id
+ return None
+
+ @property
+ def cli_args(self) -> CLIArgs:
+ """Get the CLI args."""
+ if self._cli_args is None:
+ self._cli_args = CLIArgs(args_from_argv())
+ return self._cli_args
+
+ @property
+ def query_params(self) -> QueryParams:
+ """Get the query params."""
+ return self._query_params
+
+ def get_ui_initial_value(self, object_id: str) -> Any:
+ del object_id
+ raise KeyError
+
+ @contextmanager
+ def provide_ui_ids(self, prefix: str) -> Iterator[None]:
+ del prefix
+ yield
+
+ def take_id(self) -> str:
+ raise NoIDProviderException
+
+ def register_state_update(self, state: State[Any]) -> None:
+ del state
+ return
+
+
+def initialize_script_context(app: InternalApp, stream: Stream) -> None:
+ """Initializes thread-local/session-specific context.
+
+ Must be called exactly once for each client thread.
+ """
+ from marimo._plugins.ui._core.registry import NoopUIElementRegistry
+ from marimo._runtime.virtual_file import VirtualFileRegistry
+
+ runtime_context = ScriptRuntimeContext(
+ _app=app,
+ ui_element_registry=NoopUIElementRegistry(),
+ function_registry=FunctionRegistry(),
+ cell_lifecycle_registry=CellLifecycleRegistry(),
+ virtual_file_registry=VirtualFileRegistry(),
+ virtual_files_supported=False,
+ stream=stream,
+ )
+ initialize_context(runtime_context=runtime_context)
diff --git a/marimo/_runtime/context.py b/marimo/_runtime/context/types.py
similarity index 68%
rename from marimo/_runtime/context.py
rename to marimo/_runtime/context/types.py
index 454d0201cd..58e0d3e096 100644
--- a/marimo/_runtime/context.py
+++ b/marimo/_runtime/context/types.py
@@ -6,20 +6,23 @@ Each client gets its own context.
from __future__ import annotations
+import abc
import threading
from contextlib import contextmanager
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Iterator, Optional
+from typing import TYPE_CHECKING, Any, Iterator, Optional
-from marimo._plugins.ui._core.ids import IDProvider, NoIDProviderException
+from marimo._runtime import dataflow
from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistry
from marimo._runtime.functions import FunctionRegistry
if TYPE_CHECKING:
from marimo._ast.cell import CellId_t
from marimo._messaging.types import Stream
+ from marimo._output.hypertext import Html
from marimo._plugins.ui._core.registry import UIElementRegistry
- from marimo._runtime.runtime import Kernel
+ from marimo._runtime.params import CLIArgs, QueryParams
+ from marimo._runtime.state import State
from marimo._runtime.virtual_file import VirtualFileRegistry
@@ -45,37 +48,66 @@ def get_global_context() -> GlobalContext:
@dataclass
-class RuntimeContext:
- """Encapsulates runtime state for a session."""
+class ExecutionContext:
+ cell_id: CellId_t
+ setting_element_value: bool
+ # output object set imperatively
+ output: Optional[list[Html]] = None
- kernel: Kernel
+
+@dataclass
+class RuntimeContext(abc.ABC):
ui_element_registry: UIElementRegistry
function_registry: FunctionRegistry
cell_lifecycle_registry: CellLifecycleRegistry
virtual_file_registry: VirtualFileRegistry
virtual_files_supported: bool
stream: Stream
- _id_provider: Optional[IDProvider] = None
@property
+ @abc.abstractmethod
+ def graph(self) -> dataflow.DirectedGraph:
+ pass
+
+ @property
+ @abc.abstractmethod
+ def execution_context(self) -> ExecutionContext | None:
+ pass
+
+ @property
+ @abc.abstractmethod
def cell_id(self) -> Optional[CellId_t]:
"""Get the cell id of the currently executing cell, if any."""
- if self.kernel.execution_context is not None:
- return self.kernel.execution_context.cell_id
- return None
+ pass
+
+ @property
+ @abc.abstractmethod
+ def cli_args(self) -> CLIArgs:
+ """Get the CLI args."""
+ pass
+
+ @property
+ @abc.abstractmethod
+ def query_params(self) -> QueryParams:
+ """Get the query params."""
+ pass
+
+ @abc.abstractmethod
+ def get_ui_initial_value(self, object_id: str) -> Any:
+ pass
@contextmanager
+ @abc.abstractmethod
def provide_ui_ids(self, prefix: str) -> Iterator[None]:
- try:
- self._id_provider = IDProvider(prefix)
- yield
- finally:
- self._id_provider = None
+ pass
+ @abc.abstractmethod
def take_id(self) -> str:
- if self._id_provider is None:
- raise NoIDProviderException
- return self._id_provider.take_id()
+ pass
+
+ @abc.abstractmethod
+ def register_state_update(self, state: State[Any]) -> None:
+ pass
class _ThreadLocalContext(threading.local):
@@ -98,30 +130,12 @@ class ContextNotInitializedError(Exception):
_THREAD_LOCAL_CONTEXT = _ThreadLocalContext()
-def initialize_context(
- kernel: Kernel, stream: Stream, virtual_files_supported: bool = True
-) -> None:
- """Initializes thread-local/session-specific context.
-
- Must be called exactly once for each client thread.
- """
- from marimo._plugins.ui._core.registry import UIElementRegistry
- from marimo._runtime.virtual_file import VirtualFileRegistry
-
+def initialize_context(runtime_context: RuntimeContext) -> None:
try:
get_context()
raise RuntimeError("RuntimeContext was already initialized.")
except ContextNotInitializedError:
global _THREAD_LOCAL_CONTEXT
- runtime_context = RuntimeContext(
- kernel=kernel,
- ui_element_registry=UIElementRegistry(),
- function_registry=FunctionRegistry(),
- cell_lifecycle_registry=CellLifecycleRegistry(),
- virtual_file_registry=VirtualFileRegistry(),
- virtual_files_supported=virtual_files_supported,
- stream=stream,
- )
_THREAD_LOCAL_CONTEXT.initialize(runtime_context=runtime_context)
diff --git a/marimo/_runtime/functions.py b/marimo/_runtime/functions.py
index ebcc28a0bb..3bbdfcf770 100644
--- a/marimo/_runtime/functions.py
+++ b/marimo/_runtime/functions.py
@@ -47,8 +47,8 @@ class Function(Generic[S, T]):
except ContextNotInitializedError:
ctx = None
- if ctx is not None and ctx.kernel.execution_context is not None:
- self.cell_id = ctx.kernel.execution_context.cell_id
+ if ctx is not None and ctx.execution_context is not None:
+ self.cell_id = ctx.execution_context.cell_id
else:
self.cell_id = None
diff --git a/marimo/_runtime/output/_output.py b/marimo/_runtime/output/_output.py
index 3b1b804e4c..7d8f6fc733 100644
--- a/marimo/_runtime/output/_output.py
+++ b/marimo/_runtime/output/_output.py
@@ -35,13 +35,13 @@ def replace(value: object) -> None:
- `value`: object to output
"""
ctx = get_context()
- if ctx.kernel.execution_context is None:
+ if ctx.execution_context is None:
return
elif value is None:
- ctx.kernel.execution_context.output = None
+ ctx.execution_context.output = None
else:
- ctx.kernel.execution_context.output = [formatting.as_html(value)]
- write_internal(cell_id=ctx.kernel.execution_context.cell_id, value=value)
+ ctx.execution_context.output = [formatting.as_html(value)]
+ write_internal(cell_id=ctx.execution_context.cell_id, value=value)
@mddoc
@@ -56,16 +56,16 @@ def append(value: object) -> None:
- `value`: object to output
"""
ctx = get_context()
- if ctx.kernel.execution_context is None:
+ if ctx.execution_context is None:
return
- if ctx.kernel.execution_context.output is None:
- ctx.kernel.execution_context.output = [formatting.as_html(value)]
+ if ctx.execution_context.output is None:
+ ctx.execution_context.output = [formatting.as_html(value)]
else:
- ctx.kernel.execution_context.output.append(formatting.as_html(value))
+ ctx.execution_context.output.append(formatting.as_html(value))
write_internal(
- cell_id=ctx.kernel.execution_context.cell_id,
- value=vstack(ctx.kernel.execution_context.output),
+ cell_id=ctx.execution_context.cell_id,
+ value=vstack(ctx.execution_context.output),
)
@@ -78,28 +78,23 @@ def clear() -> None:
def flush() -> None:
"""Internal function to re-render the cell's output."""
ctx = get_context()
- if ctx.kernel.execution_context is None:
+ if ctx.execution_context is None:
return
- if ctx.kernel.execution_context.output is not None:
- value = vstack(ctx.kernel.execution_context.output)
+ if ctx.execution_context.output is not None:
+ value = vstack(ctx.execution_context.output)
else:
value = None
- write_internal(cell_id=ctx.kernel.execution_context.cell_id, value=value)
+ write_internal(cell_id=ctx.execution_context.cell_id, value=value)
def remove(value: object) -> None:
"""Internal function to remove an object from a cell's output."""
ctx = get_context()
- if (
- ctx.kernel.execution_context is None
- or ctx.kernel.execution_context.output is None
- ):
+ if ctx.execution_context is None or ctx.execution_context.output is None:
return
output = [
- item
- for item in ctx.kernel.execution_context.output
- if item is not value
+ item for item in ctx.execution_context.output if item is not value
]
- ctx.kernel.execution_context.output = output if output else None
+ ctx.execution_context.output = output if output else None
flush()
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index ba441887e4..a02f67b3dd 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -60,7 +60,6 @@ from marimo._messaging.types import (
Stream,
)
from marimo._output import formatting
-from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import MarimoConvertValueException
@@ -74,10 +73,11 @@ from marimo._runtime import (
from marimo._runtime.complete import complete, completion_worker
from marimo._runtime.context import (
ContextNotInitializedError,
+ ExecutionContext,
get_context,
get_global_context,
- initialize_context,
)
+from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
from marimo._runtime.input_override import input_override
from marimo._runtime.packages.module_registry import ModuleRegistry
@@ -130,13 +130,11 @@ def defs() -> tuple[str, ...]:
except ContextNotInitializedError:
return tuple()
- if ctx.kernel.execution_context is not None:
+ if ctx.execution_context is not None:
return tuple(
sorted(
defn
- for defn in ctx.kernel.graph.cells[
- ctx.kernel.execution_context.cell_id
- ].defs
+ for defn in ctx.graph.cells[ctx.execution_context.cell_id].defs
)
)
return tuple()
@@ -157,16 +155,14 @@ def refs() -> tuple[str, ...]:
# builtins that have not been shadowed by the user
unshadowed_builtins = set(builtins.__dict__.keys()).difference(
- set(ctx.kernel.graph.definitions.keys())
+ set(ctx.graph.definitions.keys())
)
- if ctx.kernel.execution_context is not None:
+ if ctx.execution_context is not None:
return tuple(
sorted(
defn
- for defn in ctx.kernel.graph.cells[
- ctx.kernel.execution_context.cell_id
- ].refs
+ for defn in ctx.graph.cells[ctx.execution_context.cell_id].refs
# exclude builtins that have not been shadowed
if defn not in unshadowed_builtins
)
@@ -212,7 +208,7 @@ def query_params() -> QueryParams:
query parameters and any other cells referencing the query parameters
will automatically re-run.
"""
- return get_context().kernel.query_params
+ return get_context().query_params
@mddoc
@@ -236,15 +232,7 @@ def cli_args() -> CLIArgs:
- A dictionary containing the command line arguments.
This dictionary is read-only and cannot be mutated.
"""
- return get_context().kernel.cli_args
-
-
-class ExecutionContext:
- cell_id: CellId_t
- setting_element_value: bool
- # output object set imperatively
- output: Optional[list[Html]] = None
+ return get_context().cli_args
@dataclasses.dataclass
@@ -1479,7 +1467,7 @@ def launch_kernel(
ExecuteStaleRequest()
),
)
- initialize_context(
+ initialize_kernel_context(
kernel=kernel,
stream=stream,
virtual_files_supported=virtual_files_supported,
diff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.py
index 8c7caf7f9c..44a12d766e 100644
--- a/marimo/_runtime/state.py
+++ b/marimo/_runtime/state.py
@@ -31,9 +31,7 @@ class State(Generic[T]):
ctx = get_context()
except ContextNotInitializedError:
return
- kernel = ctx.kernel
- assert kernel is not None
- kernel.register_state_update(self)
+ ctx.register_state_update(self)
@mddoc
diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.py
index 5bafdf506e..86e59adfe1 100644
--- a/marimo/_runtime/virtual_file.py
+++ b/marimo/_runtime/virtual_file.py
@@ -21,7 +21,7 @@ from marimo._utils.platform import is_pyodide
if TYPE_CHECKING:
from collections.abc import Iterable
- from marimo._runtime.context import RuntimeContext
+ from marimo._runtime.context.types import RuntimeContext
LOGGER = _loggers.marimo_logger()
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index 3907e26afa..1c865b4bfc 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -1,7 +1,9 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any
+import subprocess
+import textwrap
+from typing import TYPE_CHECKING, Any
import pytest
@@ -13,6 +15,9 @@ from marimo._ast.errors import (
UnparsableError,
)
+if TYPE_CHECKING:
+ import pathlib
+
# don't complain for useless expressions (cell outputs)
# ruff: noqa: B018
@@ -395,3 +400,31 @@ def test_app_config_extra_args_ignored() -> None:
assert config.width == "full"
assert config.layout_file is None
assert config.asdict() == {"width": "full", "layout_file": None}
+
+
+def test_cli_args(tmp_path: pathlib.Path) -> None:
+ py_file = tmp_path / "cli_args_script.py"
+ content = """
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def __():
+ import marimo as mo
+ print(mo.cli_args())
+ return mo,
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ py_file.write_text(textwrap.dedent(content))
+ p = subprocess.run(
+ ["python", str(py_file), "--foo", "value1", "--bar", "value2"],
+ stdout=subprocess.PIPE,
+ )
+ assert p.returncode == 0
+ output = p.stdout.decode()
+ assert "foo" in output
+ assert "value1" in output
+ assert "bar" in output
+ assert "value2" in output
diff --git a/tests/conftest.py b/tests/conftest.py
index 3590b88770..72bcd52cdd 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -18,7 +18,8 @@ from marimo._messaging.streams import (
ThreadSafeStdout,
ThreadSafeStream,
)
-from marimo._runtime.context import initialize_context, teardown_context
+from marimo._runtime.context import teardown_context
+from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.marimo_pdb import MarimoPdb
from marimo._runtime.requests import AppMetadata, ExecutionRequest
from marimo._runtime.runtime import Kernel
@@ -99,7 +100,7 @@ class MockedKernel:
execute_stale_cells_callback=lambda: None,
)
- initialize_context(
+ initialize_kernel_context(
kernel=self.k,
stream=self.stream, # type: ignore
)