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: add more CellOutput static builders (#4110)
Myles Scolnickfc524a2cc2cf
diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/ConsoleOutput.tsxindex d711b6683c..0077d3f04b 100644--- a/frontend/src/components/editor/output/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/ConsoleOutput.tsx@@ -10,6 +10,7 @@ import { Input } from "@/components/ui/input";import { AnsiUp } from "ansi_up";import type { WithResponse } from "@/core/cells/types";import { invariant } from "@/utils/invariant";+import { ErrorBoundary } from "../boundary/ErrorBoundary";const ansiUp = new AnsiUp();@@ -24,7 +25,15 @@ interface Props {onSubmitDebugger: (text: string, index: number) => void;}-export const ConsoleOutput = (props: Props): React.ReactNode => {+export const ConsoleOutput = (props: Props) => {+ return (+ <ErrorBoundary>+ <ConsoleOutputInternal {...props} />+ </ErrorBoundary>+ );+};++const ConsoleOutputInternal = (props: Props): React.ReactNode => {const ref = React.useRef<HTMLDivElement>(null);const {consoleOutputs,diff --git a/marimo/_messaging/cell_output.py b/marimo/_messaging/cell_output.pyindex d656c987e6..6df52e03b0 100644--- a/marimo/_messaging/cell_output.py+++ b/marimo/_messaging/cell_output.py@@ -9,7 +9,7 @@ from enum import Enumfrom typing import Any, Unionfrom marimo._messaging.errors import Error-from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.mimetypes import ConsoleMimeType, KnownMimeTypeclass CellChannel(str, Enum):@@ -42,18 +42,22 @@ class CellOutput:return asdict(self)@staticmethod- def stdout(data: str) -> CellOutput:+ def stdout(+ data: str, mimetype: ConsoleMimeType = "text/plain"+ ) -> CellOutput:return CellOutput(channel=CellChannel.STDOUT,- mimetype="text/plain",+ mimetype=mimetype,data=data,)@staticmethod- def stderr(data: str) -> CellOutput:+ def stderr(+ data: str, mimetype: ConsoleMimeType = "text/plain"+ ) -> CellOutput:return CellOutput(channel=CellChannel.STDERR,- mimetype="text/plain",+ mimetype=mimetype,data=data,)@@ -62,3 +66,19 @@ class CellOutput:return CellOutput(channel=CellChannel.STDIN, mimetype="text/plain", data=data)++ @staticmethod+ def empty() -> CellOutput:+ return CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="",+ )++ @staticmethod+ def errors(data: list[Error]) -> CellOutput:+ return CellOutput(+ channel=CellChannel.MARIMO_ERROR,+ mimetype="application/vnd.marimo+error",+ data=data,+ )diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.pyindex f2a5bc4eee..f357e1bbc5 100644--- a/marimo/_messaging/console_output_worker.py+++ b/marimo/_messaging/console_output_worker.py@@ -6,7 +6,7 @@ from dataclasses import dataclassfrom typing import TYPE_CHECKING, Literalfrom marimo._messaging.cell_output import CellChannel, CellOutput-from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.mimetypes import ConsoleMimeTypefrom marimo._types.ids import CellId_tif TYPE_CHECKING:@@ -27,7 +27,7 @@ class ConsoleMsg:stream: StreamTcell_id: CellId_tdata: str- mimetype: KnownMimeType+ mimetype: ConsoleMimeTypedef _write_console_output(@@ -35,7 +35,7 @@ def _write_console_output(stream_type: StreamT,cell_id: CellId_t,data: str,- mimetype: KnownMimeType,+ mimetype: ConsoleMimeType,) -> None:from marimo._messaging.ops import CellOpdiff --git a/marimo/_messaging/mimetypes.py b/marimo/_messaging/mimetypes.pyindex 7500d660b0..199a4f2b0e 100644--- a/marimo/_messaging/mimetypes.py+++ b/marimo/_messaging/mimetypes.py@@ -29,5 +29,11 @@ KnownMimeType = Literal["text/csv",]+ConsoleMimeType = Literal[+ "application/vnd.marimo+traceback",+ "text/plain",+ "image/png",+]+MimeBundle = dict[KnownMimeType, Any]MimeBundleOrTuple = Union[MimeBundle, tuple[MimeBundle, Any]]diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 624e9911e6..d332a788f0 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -230,11 +230,7 @@ class CellOp(Op):assert cell_id is not NoneCellOp(cell_id=cell_id,- output=CellOutput(- channel=CellChannel.OUTPUT,- mimetype="text/plain",- data="",- ),+ output=CellOutput.empty(),status=status,).broadcast(stream=stream)@@ -305,11 +301,7 @@ class CellOp(Op):CellOp(cell_id=cell_id,- output=CellOutput(- channel=CellChannel.MARIMO_ERROR,- mimetype="application/vnd.marimo+error",- data=safe_errors,- ),+ output=CellOutput.errors(safe_errors),console=console,status=None,).broadcast()diff --git a/marimo/_messaging/print_override.py b/marimo/_messaging/print_override.pyindex 03032549df..ab9430d23e 100644--- a/marimo/_messaging/print_override.py+++ b/marimo/_messaging/print_override.py@@ -5,7 +5,7 @@ import functoolsimport threadingfrom typing import Any-from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.cell_output import CellOutputfrom marimo._messaging.ops import CellOpfrom marimo._runtime.context.types import (ContextNotInitializedError,@@ -52,9 +52,5 @@ def print_override(*args: Any, **kwargs: Any) -> None:CellOp(cell_id=cell_id,- console=CellOutput(- channel=CellChannel.STDOUT,- mimetype="text/plain",- data=msg,- ),+ console=CellOutput.stdout(msg),).broadcast(ctx.stream)diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex 90c4b745df..11d69696f2 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -17,7 +17,7 @@ from typing import (from marimo import _loggersfrom marimo._messaging.cell_output import CellChannelfrom marimo._messaging.console_output_worker import ConsoleMsg, buffered_writer-from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.mimetypes import ConsoleMimeTypefrom marimo._messaging.types import (KernelMessage,Stderr,@@ -236,7 +236,9 @@ class ThreadSafeStdout(Stdout):# TODO(akshayka): maybe force the buffered writer to writereturn- def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ def _write_with_mimetype(+ self, data: str, mimetype: ConsoleMimeType+ ) -> int:assert self._stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(@@ -300,7 +302,9 @@ class ThreadSafeStderr(Stderr):# TODO(akshayka): maybe force the buffered writer to writereturn- def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ def _write_with_mimetype(+ self, data: str, mimetype: ConsoleMimeType+ ) -> int:assert self._stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.pyindex dd5b18ccc7..baa7d10d7e 100644--- a/marimo/_messaging/types.py+++ b/marimo/_messaging/types.py@@ -5,7 +5,7 @@ import abcimport iofrom typing import Any, Optional-from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.mimetypes import ConsoleMimeTypefrom marimo._types.ids import CellId_t# The message from the kernel is a tuple of message type@@ -40,7 +40,9 @@ class Stdout(io.TextIOBase):name = "stdout"@abc.abstractmethod- def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ def _write_with_mimetype(+ self, data: str, mimetype: ConsoleMimeType+ ) -> int:passdef write(self, __s: str) -> int:@@ -55,7 +57,9 @@ class Stderr(io.TextIOBase):name = "stderr"@abc.abstractmethod- def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ def _write_with_mimetype(+ self, data: str, mimetype: ConsoleMimeType+ ) -> int:passdef write(self, __s: str) -> int:diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.pyindex 9890cb2a2d..3dd34904d0 100644--- a/marimo/_pyodide/streams.py+++ b/marimo/_pyodide/streams.py@@ -6,8 +6,8 @@ import sysfrom typing import TYPE_CHECKING, Any, Callable, Optionalfrom marimo import _loggers-from marimo._messaging.cell_output import CellChannel, CellOutput-from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.cell_output import CellOutput+from marimo._messaging.mimetypes import ConsoleMimeTypefrom marimo._messaging.ops import CellOpfrom marimo._messaging.streams import std_stream_max_bytesfrom marimo._messaging.types import (@@ -59,7 +59,9 @@ class PyodideStdout(Stdout):def seekable(self) -> bool:return False- def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ def _write_with_mimetype(+ self, data: str, mimetype: ConsoleMimeType+ ) -> int:assert self.stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(@@ -73,11 +75,7 @@ class PyodideStdout(Stdout):data = data[: int(max_bytes)] + " ... "CellOp(cell_id=self.stream.cell_id,- console=CellOutput(- channel=CellChannel.STDOUT,- mimetype=mimetype,- data=data,- ),+ console=CellOutput.stdout(data, mimetype),).broadcast(self.stream)return len(data)@@ -104,7 +102,9 @@ class PyodideStderr(Stderr):def seekable(self) -> bool:return False- def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ def _write_with_mimetype(+ self, data: str, mimetype: ConsoleMimeType+ ) -> int:assert self.stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(@@ -120,11 +120,7 @@ class PyodideStderr(Stderr):CellOp(cell_id=self.stream.cell_id,- console=CellOutput(- channel=CellChannel.STDERR,- mimetype=mimetype,- data=data,- ),+ console=CellOutput.stderr(data, mimetype),).broadcast(self.stream)return len(data)@@ -163,11 +159,7 @@ class PyodideStdin(Stdin):CellOp(cell_id=self.stream.cell_id,- console=CellOutput(- channel=CellChannel.STDIN,- mimetype="text/plain",- data=prompt,- ),+ console=CellOutput.stdin(prompt),).broadcast(self.stream)loop = asyncio.get_event_loop()diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.pyindex b0537504fe..7a0901cdc4 100644--- a/marimo/_server/session/serialize.py+++ b/marimo/_server/session/serialize.py@@ -121,10 +121,8 @@ def deserialize_session(session: NotebookSessionV1) -> SessionView:for output in cell["outputs"]:if output["type"] == "error":cell_outputs.append(- CellOutput(- channel=CellChannel.MARIMO_ERROR,- mimetype="application/vnd.marimo+error",- data=[+ CellOutput.errors(+ [MarimoExceptionRaisedError(type="exception",exception_type=output["ename"],diff --git a/tests/_messaging/test_cell_output.py b/tests/_messaging/test_cell_output.pyindex fe8daf883e..47a6923cd6 100644--- a/tests/_messaging/test_cell_output.py+++ b/tests/_messaging/test_cell_output.py@@ -97,3 +97,72 @@ def test_serialize_cell_output():def test_identity(subject: CellOutput):serialized = serialize(subject)assert subject == parse_raw(serialized, CellOutput)+++def test_cell_output_static_methods():+ # Test empty output+ empty = CellOutput.empty()+ assert empty.channel == CellChannel.OUTPUT+ assert empty.mimetype == "text/plain"+ assert empty.data == ""++ # Test stdout method+ stdout = CellOutput.stdout("Hello world")+ assert stdout.channel == CellChannel.STDOUT+ assert stdout.mimetype == "text/plain"+ assert stdout.data == "Hello world"++ # Test stderr method+ stderr = CellOutput.stderr("Error message")+ assert stderr.channel == CellChannel.STDERR+ assert stderr.mimetype == "text/plain"+ assert stderr.data == "Error message"++ # Test stdin method+ stdin = CellOutput.stdin("User input")+ assert stdin.channel == CellChannel.STDIN+ assert stdin.mimetype == "text/plain"+ assert stdin.data == "User input"++ # Test errors method+ errors = CellOutput.errors([MarimoSyntaxError(msg="Test error")])+ assert errors.channel == CellChannel.MARIMO_ERROR+ assert errors.mimetype == "application/vnd.marimo+error"+ assert isinstance(errors.data, list)+ assert len(errors.data) == 1+ assert errors.data[0].msg == "Test error"+++def test_cell_output_repr():+ output = CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="test data",+ timestamp=123.456,+ )+ repr_str = repr(output)+ assert "CellOutput" in repr_str+ assert "channel=" in repr_str+ assert "mimetype=text/plain" in repr_str+ assert "timestamp=123.456" in repr_str+++def test_cell_output_asdict():+ output = CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="test data",+ timestamp=123.456,+ )+ result = output.asdict()+ assert result["channel"] == "output"+ assert result["mimetype"] == "text/plain"+ assert result["data"] == "test data"+ assert result["timestamp"] == 123.456+++def test_cell_channel_repr():+ assert repr(CellChannel.STDOUT) == "stdout"+ assert repr(CellChannel.STDERR) == "stderr"+ assert repr(CellChannel.OUTPUT) == "output"+ assert repr(CellChannel.MARIMO_ERROR) == "marimo-error"diff --git a/tests/conftest.py b/tests/conftest.pyindex b6834c6d4c..57dcc2ca20 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -15,7 +15,7 @@ from _pytest import runnerfrom marimo._ast.app import App, CellManagerfrom marimo._config.config import DEFAULT_CONFIG-from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.mimetypes import ConsoleMimeTypefrom marimo._messaging.ops import CellOp, MessageOperationfrom marimo._messaging.print_override import print_overridefrom marimo._messaging.streams import (@@ -94,7 +94,9 @@ class MockStdout(ThreadSafeStdout):super().__init__(stream)self.messages: list[str] = []- def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ def _write_with_mimetype(+ self, data: str, mimetype: ConsoleMimeType+ ) -> int:del mimetypeself.messages.append(data)return len(data)@@ -112,7 +114,9 @@ class MockStderr(ThreadSafeStderr):super().__init__(stream)self.messages: list[str] = []- def _write_with_mimetype(self, data: str, mimetype: KnownMimeType) -> int:+ def _write_with_mimetype(+ self, data: str, mimetype: ConsoleMimeType+ ) -> int:del mimetypeself.messages.append(data)return len(data)