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
chore: slimmed down interfaces for streams (#776)
Myles Scolnick5cf989ca0107
diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.pyindex c0ae6478ec..9ad63400b5 100644--- a/marimo/_messaging/console_output_worker.py+++ b/marimo/_messaging/console_output_worker.py@@ -13,7 +13,7 @@ from marimo._messaging.cell_output import CellChannel, CellOutputif TYPE_CHECKING:from typing import Optional- from marimo._messaging.streams import Stream+ from marimo._messaging.types import StreamStreamT = Literal[CellChannel.STDERR, CellChannel.STDOUT, CellChannel.STDIN]@@ -29,7 +29,10 @@ class ConsoleMsg:def _write_console_output(- stream: Stream, stream_type: StreamT, cell_id: CellId_t, data: str+ stream: Stream,+ stream_type: StreamT,+ cell_id: CellId_t,+ data: str,) -> None:from marimo._messaging.ops import CellOpdiff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex a2321229ce..5929eea07e 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -29,7 +29,8 @@ from marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.completion_option import CompletionOptionfrom marimo._messaging.errors import Errorfrom marimo._messaging.mimetypes import KnownMimeType-from marimo._messaging.streams import OUTPUT_MAX_BYTES, Stream+from marimo._messaging.streams import OUTPUT_MAX_BYTES+from marimo._messaging.types import Streamfrom marimo._output.hypertext import Htmlfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElementdiff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex 5afe53b083..32515a7e12 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -13,7 +13,13 @@ from marimo import _loggersfrom marimo._ast.cell import CellId_tfrom marimo._messaging.cell_output import CellChannelfrom marimo._messaging.console_output_worker import ConsoleMsg, buffered_writer-from marimo._messaging.types import KernelMessage+from marimo._messaging.types import (+ KernelMessage,+ Stderr,+ Stdin,+ Stdout,+ Stream,+)from marimo._server.types import QueueTypefrom marimo._utils.typed_connection import TypedConnection@@ -45,7 +51,7 @@ OUTPUT_MAX_BYTES = int(os.getenv("MARIMO_OUTPUT_MAX_BYTES", 5_000_000))STD_STREAM_MAX_BYTES = int(os.getenv("MARIMO_STD_STREAM_MAX_BYTES", 1_000_000))-class Stream:+class ThreadSafeStream(Stream):"""A thread-safe wrapper around a pipe."""def __init__(@@ -105,7 +111,9 @@ def _forward_os_stream(standard_stream: Stdout | Stderr, fd: int) -> None:class Watcher:"""Watches and redirects a standard stream."""- def __init__(self, standard_stream: Stdout | Stderr) -> None:+ def __init__(+ self, standard_stream: ThreadSafeStdout | ThreadSafeStderr+ ) -> None:self.standard_stream = standard_streamself.fd = self.standard_stream._original_fdself.read_fd, self.write_fd = os.pipe()@@ -139,13 +147,13 @@ class Watcher:# NB: Python doesn't provide a standard out class to inherit from, so# we inherit from TextIOBase.-class Stdout(io.TextIOBase):+class ThreadSafeStdout(Stdout):name = "stdout"encoding = sys.stdout.encodingerrors = sys.stdout.errors_fileno: int | None = None- def __init__(self, stream: Stream):+ def __init__(self, stream: ThreadSafeStream):self._stream = streamself._original_fd = sys.stdout.fileno()self._watcher = Watcher(self)@@ -199,13 +207,13 @@ class Stdout(io.TextIOBase):self.write(line)-class Stderr(io.TextIOBase):+class ThreadSafeStderr(Stderr):name = "stderr"encoding = sys.stderr.encodingerrors = sys.stderr.errors_fileno: int | None = None- def __init__(self, stream: Stream):+ def __init__(self, stream: ThreadSafeStream):self._stream = streamself._original_fd = sys.stderr.fileno()self._watcher = Watcher(self)@@ -260,14 +268,14 @@ class Stderr(io.TextIOBase):self.write(line)-class Stdin(io.TextIOBase):+class ThreadSafeStdin(Stdin):"""Implements a subset of stdin."""name = "stdin"encoding = sys.stdin.encodingerrors = sys.stdin.errors- def __init__(self, stream: Stream):+ def __init__(self, stream: ThreadSafeStream):self._stream = streamdef fileno(self) -> int:@@ -327,7 +335,13 @@ class Stdin(io.TextIOBase):def redirect(standard_stream: Stdout | Stderr) -> Iterator[None]:"""Redirect a standard stream to the frontend."""try:- standard_stream._watcher.start()+ if isinstance(standard_stream, ThreadSafeStdout) or isinstance(+ standard_stream, ThreadSafeStderr+ ):+ standard_stream._watcher.start()yieldfinally:- standard_stream._watcher.pause()+ if isinstance(standard_stream, ThreadSafeStdout) or isinstance(+ standard_stream, ThreadSafeStderr+ ):+ standard_stream._watcher.pause()diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.pyindex 8ed1990e26..5879dec48e 100644--- a/marimo/_messaging/types.py+++ b/marimo/_messaging/types.py@@ -1,6 +1,40 @@# Copyright 2024 Marimo. All rights reserved.-from typing import Any, Tuple+import abc+import io+from typing import Any, Dict, Optional, Tuple++from marimo._ast.cell import CellId_t# The message from the kernel is a tuple of message type# and a json representation of the messageKernelMessage = Tuple[str, Any]+++class Stream(abc.ABC):+ """+ A stream is a class that can write messages from the kernel to+ some output.+ The `write` method is called by the kernel.+ """++ cell_id: Optional[CellId_t] = None++ @abc.abstractmethod+ def write(self, op: str, data: Dict[Any, Any]) -> None:+ pass+++class Stdout(io.TextIOBase):+ @abc.abstractmethod+ def write(self, __s: str) -> int:+ pass+++class Stderr(io.TextIOBase):+ @abc.abstractmethod+ def write(self, __s: str) -> int:+ pass+++class Stdin(io.TextIOBase):+ passdiff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.pyindex 473c280560..2cb51df290 100644--- a/marimo/_runtime/complete.py+++ b/marimo/_runtime/complete.py@@ -10,7 +10,7 @@ import jedi.api # type: ignore # noqa: F401from marimo import _loggers as loggersfrom marimo._messaging.completion_option import CompletionOptionfrom marimo._messaging.ops import CompletionResult-from marimo._messaging.streams import Stream+from marimo._messaging.types import Streamfrom marimo._output.md import _mdfrom marimo._runtime import dataflowfrom marimo._runtime.requests import CompletionRequestdiff --git a/marimo/_runtime/context.py b/marimo/_runtime/context.pyindex 9b47a0b074..3871e2435c 100644--- a/marimo/_runtime/context.py+++ b/marimo/_runtime/context.py@@ -18,7 +18,7 @@ from marimo._runtime.functions import FunctionRegistryif TYPE_CHECKING:from marimo._ast.cell import CellId_t- from marimo._messaging.streams import Stream+ from marimo._messaging.types import Streamfrom marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.runtime import Kernelfrom marimo._runtime.virtual_file import VirtualFileRegistrydiff --git a/marimo/_runtime/marimo_pdb.py b/marimo/_runtime/marimo_pdb.pyindex afb974599f..43d37aa913 100644--- a/marimo/_runtime/marimo_pdb.py+++ b/marimo/_runtime/marimo_pdb.py@@ -7,7 +7,7 @@ from pdb import Pdbfrom types import FrameTypefrom marimo import _loggers-from marimo._messaging.streams import Stdin, Stdout+from marimo._messaging.types import Stdin, StdoutLOGGER = _loggers.marimo_logger()diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.pyindex b7fca98bfb..d58aff9e91 100644--- a/marimo/_runtime/redirect_streams.py+++ b/marimo/_runtime/redirect_streams.py@@ -7,7 +7,10 @@ import sysfrom typing import Iteratorfrom marimo._ast.cell import CellId_t-from marimo._messaging.streams import Stderr, Stdin, Stdout, Stream, redirect+from marimo._messaging.streams import (+ redirect,+)+from marimo._messaging.types import Stderr, Stdin, Stdout, Streamdef forward_os_stream(stream_object: Stdout | Stderr, fd: int) -> None:diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 6448d9d4fc..05777fdbf0 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -42,8 +42,19 @@ from marimo._messaging.ops import (VariableValue,VariableValues,)-from marimo._messaging.streams import Stderr, Stdin, Stdout, Stream-from marimo._messaging.types import KernelMessage+from marimo._messaging.streams import (+ ThreadSafeStderr,+ ThreadSafeStdin,+ ThreadSafeStdout,+ ThreadSafeStream,+)+from marimo._messaging.types import (+ KernelMessage,+ Stderr,+ Stdin,+ Stdout,+ Stream,+)from marimo._output import formattingfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc@@ -1099,14 +1110,14 @@ def launch_kernel(return# Create communication channels- stream = Stream(pipe=pipe, input_queue=input_queue)+ stream = ThreadSafeStream(pipe=pipe, input_queue=input_queue)# Console output is hidden in run mode, so no need to redirect# (redirection of console outputs is not thread-safe anyway)- stdout = Stdout(stream) if is_edit_mode else None- stderr = Stderr(stream) if is_edit_mode else None+ stdout = ThreadSafeStdout(stream) if is_edit_mode else None+ stderr = ThreadSafeStderr(stream) if is_edit_mode else None# TODO(akshayka): stdin in run mode? input(prompt) uses stdout, which# isn't currently available in run mode.- stdin = Stdin(stream) if is_edit_mode else None+ stdin = ThreadSafeStdin(stream) if is_edit_mode else Nonekernel = Kernel(cell_configs=configs,@@ -1229,8 +1240,8 @@ def launch_kernel(else:raise ValueError(f"Unknown request {request}")- if stdout is not None:+ if stdout is not None and isinstance(stdout, ThreadSafeStdout):stdout._watcher.stop()- if stderr is not None:+ if stderr is not None and isinstance(stderr, ThreadSafeStderr):stderr._watcher.stop()get_context().virtual_file_registry.shutdown()diff --git a/tests/conftest.py b/tests/conftest.pyindex a21028b9d3..89e9cda28b 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -9,7 +9,12 @@ import pytestfrom marimo._ast.app import CellManagerfrom marimo._ast.cell import CellId_t-from marimo._messaging.streams import Stderr, Stdin, Stdout+from marimo._messaging.streams import (+ ThreadSafeStderr,+ ThreadSafeStdin,+ ThreadSafeStdout,+ ThreadSafeStream,+)from marimo._runtime.context import (initialize_context,teardown_context,@@ -19,7 +24,7 @@ from marimo._runtime.runtime import Kernel@dataclasses.dataclass-class _MockStream:+class _MockStream(ThreadSafeStream):"""Captures the ops sent through the stream"""messages: list[tuple[str, dict[Any, Any]]] = dataclasses.field(@@ -30,7 +35,7 @@ class _MockStream:self.messages.append((op, data))-class MockStdout(Stdout):+class MockStdout(ThreadSafeStdout):"""Captures the output sent through the stream"""def __init__(self, stream: _MockStream) -> None:@@ -42,7 +47,7 @@ class MockStdout(Stdout):return len(data)-class MockStderr(Stderr):+class MockStderr(ThreadSafeStderr):"""Captures the output sent through the stream"""messages: list[str] = dataclasses.field(default_factory=list)@@ -56,7 +61,7 @@ class MockStderr(Stderr):return len(data)-class MockStdin(Stdin):+class MockStdin(ThreadSafeStdin):"""Echoes the prompt."""def __init__(self, stream: _MockStream) -> None: