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.

chore: slimmed down interfaces for streams (#776)

Myles Scolnick5cf989ca0107
diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.py
index 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, CellOutput
if TYPE_CHECKING:
from typing import Optional
- from marimo._messaging.streams import Stream
+ from marimo._messaging.types import Stream
StreamT = 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 CellOp
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index a2321229ce..5929eea07e 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -29,7 +29,8 @@ from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.completion_option import CompletionOption
from marimo._messaging.errors import Error
from 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 Stream
from marimo._output.hypertext import Html
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import UIElement
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.py
index 5afe53b083..32515a7e12 100644
--- a/marimo/_messaging/streams.py
+++ b/marimo/_messaging/streams.py
@@ -13,7 +13,13 @@ from marimo import _loggers
from marimo._ast.cell import CellId_t
from marimo._messaging.cell_output import CellChannel
from 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 QueueType
from 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_stream
self.fd = self.standard_stream._original_fd
self.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.encoding
errors = sys.stdout.errors
_fileno: int | None = None
- def __init__(self, stream: Stream):
+ def __init__(self, stream: ThreadSafeStream):
self._stream = stream
self._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.encoding
errors = sys.stderr.errors
_fileno: int | None = None
- def __init__(self, stream: Stream):
+ def __init__(self, stream: ThreadSafeStream):
self._stream = stream
self._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.encoding
errors = sys.stdin.errors
- def __init__(self, stream: Stream):
+ def __init__(self, stream: ThreadSafeStream):
self._stream = stream
def 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()
yield
finally:
- 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.py
index 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 message
KernelMessage = 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):
+ pass
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index 473c280560..2cb51df290 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -10,7 +10,7 @@ import jedi.api # type: ignore # noqa: F401
from marimo import _loggers as loggers
from marimo._messaging.completion_option import CompletionOption
from marimo._messaging.ops import CompletionResult
-from marimo._messaging.streams import Stream
+from marimo._messaging.types import Stream
from marimo._output.md import _md
from marimo._runtime import dataflow
from marimo._runtime.requests import CompletionRequest
diff --git a/marimo/_runtime/context.py b/marimo/_runtime/context.py
index 9b47a0b074..3871e2435c 100644
--- a/marimo/_runtime/context.py
+++ b/marimo/_runtime/context.py
@@ -18,7 +18,7 @@ from marimo._runtime.functions import FunctionRegistry
if TYPE_CHECKING:
from marimo._ast.cell import CellId_t
- from marimo._messaging.streams import Stream
+ from marimo._messaging.types import Stream
from marimo._plugins.ui._core.registry import UIElementRegistry
from marimo._runtime.runtime import Kernel
from marimo._runtime.virtual_file import VirtualFileRegistry
diff --git a/marimo/_runtime/marimo_pdb.py b/marimo/_runtime/marimo_pdb.py
index afb974599f..43d37aa913 100644
--- a/marimo/_runtime/marimo_pdb.py
+++ b/marimo/_runtime/marimo_pdb.py
@@ -7,7 +7,7 @@ from pdb import Pdb
from types import FrameType
from marimo import _loggers
-from marimo._messaging.streams import Stdin, Stdout
+from marimo._messaging.types import Stdin, Stdout
LOGGER = _loggers.marimo_logger()
diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.py
index b7fca98bfb..d58aff9e91 100644
--- a/marimo/_runtime/redirect_streams.py
+++ b/marimo/_runtime/redirect_streams.py
@@ -7,7 +7,10 @@ import sys
from typing import Iterator
from 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, Stream
def forward_os_stream(stream_object: Stdout | Stderr, fd: int) -> None:
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 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 formatting
from marimo._output.hypertext import Html
from 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 None
kernel = 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.py
index a21028b9d3..89e9cda28b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -9,7 +9,12 @@ import pytest
from marimo._ast.app import CellManager
from 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: