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
feat: marimo.output (#164)
Akshay Agrawalc103adfcbb7a
diff --git a/examples/embeddings/embedding_numbers.py b/examples/embeddings/embedding_numbers.pyindex 7930406ddb..7b030d7596 100644--- a/examples/embeddings/embedding_numbers.py+++ b/examples/embeddings/embedding_numbers.py@@ -1,6 +1,6 @@import marimo-__generated_with = "0.1.0"+__generated_with = "0.1.19"app = marimo.App()@@ -63,12 +63,6 @@ def __(mo):return params,-def __(params):- params.value- return--@app.celldef __(params):if params.value is not None:@@ -108,13 +102,12 @@ def __(plt.tight_layout()return plt.gca()-show_embedding() if embedding_dimension is not None else Nonereturn show_embedding,@app.cell-def __(mnist, pymde, torch):+def __(mnist, mo, pymde, torch):embedding_cache = {}@@ -122,6 +115,9 @@ def __(mnist, pymde, torch):key = (embedding_dim, constraint)if key in embedding_cache:return embedding_cache[key]+ mo.output.append(+ mo.md("Your embedding is being computed ... hang tight!").callout(kind="warn")+ )mde = pymde.preserve_neighbors(mnist.data,diff --git a/frontend/src/components/data-table/mime-cell.tsx b/frontend/src/components/data-table/mime-cell.tsxindex 88790682dc..ff29ee63d4 100644--- a/frontend/src/components/data-table/mime-cell.tsx+++ b/frontend/src/components/data-table/mime-cell.tsx@@ -23,7 +23,7 @@ export const MimeCell = ({ value }: MimeCellProps) => {channel: "output",data: value.data,mimetype: value.mimetype,- timestamp: "",+ timestamp: 0,} as OutputMessage,})}</div>diff --git a/frontend/src/core/kernel/messages.tsx b/frontend/src/core/kernel/messages.tsxindex bb00498d0f..a9afa74da4 100644--- a/frontend/src/core/kernel/messages.tsx+++ b/frontend/src/core/kernel/messages.tsx@@ -33,7 +33,7 @@ export type OutputMessage =channel: OutputChannel;mimetype: "application/vnd.marimo+error";data: MarimoError[];- timestamp: string;+ timestamp: number;}| {channel: OutputChannel;@@ -51,13 +51,13 @@ export type OutputMessage =| "video/mp4"| "video/mpeg";data: string;- timestamp: string;+ timestamp: number;}| {channel: OutputChannel;mimetype: "application/json";data: unknown;- timestamp: string;+ timestamp: number;};/**diff --git a/frontend/src/core/model/__tests__/collapseConsoleOutputs.test.ts b/frontend/src/core/model/__tests__/collapseConsoleOutputs.test.tsindex 3b431e1d8a..d0bd731da7 100644--- a/frontend/src/core/model/__tests__/collapseConsoleOutputs.test.ts+++ b/frontend/src/core/model/__tests__/collapseConsoleOutputs.test.ts@@ -11,13 +11,13 @@ describe("collapseConsoleOutputs", () => {mimetype: "text/plain",channel: "output",data: "Hello ",- timestamp: "",+ timestamp: 0,},{mimetype: "text/plain",channel: "output",data: "World",- timestamp: "",+ timestamp: 0,},];const result = collapseConsoleOutputs(consoleOutputs);@@ -30,13 +30,13 @@ describe("collapseConsoleOutputs", () => {mimetype: "text/plain",channel: "output",data: "Hello ",- timestamp: "",+ timestamp: 0,},{mimetype: "text/plain",channel: "console",data: "World",- timestamp: "",+ timestamp: 0,},];const result = collapseConsoleOutputs(consoleOutputs);@@ -49,13 +49,13 @@ describe("collapseConsoleOutputs", () => {mimetype: "text/plain",channel: "output",data: "Hello ",- timestamp: "",+ timestamp: 0,},{mimetype: "text/html",channel: "output",data: "World",- timestamp: "",+ timestamp: 0,},];const result = collapseConsoleOutputs(consoleOutputs);@@ -68,7 +68,7 @@ describe("collapseConsoleOutputs", () => {mimetype: "text/plain",channel: "output",data: "Hello\rWorld",- timestamp: "",+ timestamp: 0,},];const result = collapseConsoleOutputs(consoleOutputs);@@ -81,7 +81,7 @@ describe("collapseConsoleOutputs", () => {mimetype: "text/plain",channel: "output",data: "Hello\rWorld\r!",- timestamp: "",+ timestamp: 0,},];const result = collapseConsoleOutputs(consoleOutputs);@@ -94,7 +94,7 @@ describe("collapseConsoleOutputs", () => {mimetype: "text/plain",channel: "output",data: "Hello\nWorld\r!",- timestamp: "",+ timestamp: 0,},];const result = collapseConsoleOutputs(consoleOutputs);diff --git a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snapindex ce29be02ed..999b32ce7e 100644--- a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap+++ b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap@@ -170,7 +170,7 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `"channel": "console","data": "hello!","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},],"edited": false,@@ -200,7 +200,7 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `"channel": "console","data": "hello!hello!","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},],"edited": false,@@ -213,7 +213,7 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `"channel": "output","data": "ok","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},"ref": {"current": null,@@ -236,7 +236,7 @@ import numpy","channel": "console","data": "hello!hello!","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},],"edited": true,@@ -249,7 +249,7 @@ import numpy","channel": "output","data": "ok","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},"ref": {"current": null,@@ -271,7 +271,7 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `"channel": "console","data": "hello!hello!","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},],"edited": false,@@ -284,7 +284,7 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `"channel": "output","data": "ok","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},"ref": {"current": null,@@ -307,7 +307,7 @@ import numpy","channel": "console","data": "hello!hello!","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},],"edited": true,@@ -320,7 +320,7 @@ import numpy","channel": "output","data": "ok","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},"ref": {"current": null,@@ -343,7 +343,7 @@ import numpy","channel": "console","data": "hello!hello!","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},],"edited": false,@@ -363,7 +363,7 @@ import numpy",},],"mimetype": "application/vnd.marimo+error",- "timestamp": "",+ "timestamp": 0,},"ref": {"current": null,@@ -386,7 +386,7 @@ import numpy","channel": "console","data": "hello!hello!","mimetype": "text/plain",- "timestamp": "",+ "timestamp": 0,},],"edited": false,@@ -403,7 +403,7 @@ import numpy",},],"mimetype": "application/vnd.marimo+error",- "timestamp": "",+ "timestamp": 0,},"ref": {"current": null,diff --git a/frontend/src/core/state/__tests__/cells.test.ts b/frontend/src/core/state/__tests__/cells.test.tsindex 1096e675d4..8a30b5226d 100644--- a/frontend/src/core/state/__tests__/cells.test.ts+++ b/frontend/src/core/state/__tests__/cells.test.ts@@ -276,7 +276,7 @@ describe("cell reducer", () => {channel: "console",mimetype: "text/plain",data: "hello!",- timestamp: "",+ timestamp: 0,},status: null,timestamp: new Date(22).getTime(),@@ -298,13 +298,13 @@ describe("cell reducer", () => {channel: "output",mimetype: "text/plain",data: "ok",- timestamp: "",+ timestamp: 0,},console: {channel: "console",mimetype: "text/plain",data: "hello!",- timestamp: "",+ timestamp: 0,},status: "idle",timestamp: new Date(33).getTime(),@@ -397,7 +397,7 @@ describe("cell reducer", () => {data: [{ type: "exception", exception_type: "ValueError", msg: "Oh no!" },],- timestamp: "",+ timestamp: 0,},console: null,status: "idle",@@ -456,7 +456,7 @@ describe("cell reducer", () => {channel: "marimo-error",mimetype: "application/vnd.marimo+error",data: [{ type: "interruption" }],- timestamp: "",+ timestamp: 0,},console: null,status: "idle",@@ -560,13 +560,13 @@ describe("cell reducer", () => {channel: "output",mimetype: "text/plain",data: "ok",- timestamp: "",+ timestamp: 0,},console: {channel: "console",mimetype: "text/plain",data: "hello!",- timestamp: "",+ timestamp: 0,},status: "idle",timestamp: new Date(33).getTime(),diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsxindex f676c7ff00..c3edd81f29 100644--- a/frontend/src/editor/Cell.tsx+++ b/frontend/src/editor/Cell.tsx@@ -71,6 +71,7 @@ export interface CellProps| "interrupted"| "config"| "stopped"+ | "runStartTimestamp"| "runElapsedTimeMs">,Pick<@@ -110,6 +111,7 @@ const CellComponent = (output,consoleOutputs,status,+ runStartTimestamp,runElapsedTimeMs,edited,interrupted,@@ -143,6 +145,22 @@ const CellComponent = (const needsRun = edited || interrupted;const loading = status === "running" || status === "queued";+ // output may or may not be refreshed while a cell is running, so+ // we need to check if an output was received+ const outputReceivedWhileRunning =+ status === "running" &&+ output !== null &&+ runStartTimestamp !== null &&+ output.timestamp > runStartTimestamp;+ const outputStale =+ ((loading && !outputReceivedWhileRunning) ||+ edited ||+ status === "stale") &&+ !interrupted;+ // console output is cleared immediately on run, so check for queued instead+ // of loading to determine staleness+ const consoleOutputStale =+ (status === "queued" || edited || status === "stale") && !interrupted;const editing = mode === "edit";const reading = mode === "read";const { sendToTop, sendToBottom } = useCellActions();@@ -385,7 +403,7 @@ const CellComponent = (output={output}className="output-area"cellId={cellId}- stale={(loading || edited || status === "stale") && !interrupted}+ stale={outputStale}/>);@@ -504,10 +522,7 @@ const CellComponent = (</div><ConsoleOutputconsoleOutputs={consoleOutputs}- stale={- (status === "queued" || edited || status === "stale") &&- !interrupted- }+ stale={consoleOutputStale}/></SortableCell></CellActionsContextMenu>diff --git a/frontend/src/editor/renderers/CellArray.tsx b/frontend/src/editor/renderers/CellArray.tsxindex 8521332833..eba82aeb38 100644--- a/frontend/src/editor/renderers/CellArray.tsx+++ b/frontend/src/editor/renderers/CellArray.tsx@@ -104,6 +104,7 @@ export const CellArray: React.FC<CellArrayProps> = ({interrupted={cell.interrupted}errored={cell.errored}stopped={cell.stopped}+ runStartTimestamp={cell.runStartTimestamp}runElapsedTimeMs={cell.runElapsedTimeMs}registerRunStart={registerRunStart}serializedEditorState={cell.serializedEditorState}diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 1ce26303f6..075b246970 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -28,6 +28,7 @@ const props: CellProps = {updateCellCode: console.log,prepareForRun: console.log,registerRunStart: console.log,+ runStartTimestamp: 0,runElapsedTimeMs: 10,serializedEditorState: null,mode: "edit",@@ -80,7 +81,7 @@ export const WithOutput: Story = {channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>@@ -100,7 +101,7 @@ export const UnsavedEditsOutput: Story = {channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>@@ -120,7 +121,7 @@ export const InterruptedOutput: Story = {channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>@@ -140,7 +141,7 @@ export const WithError: Story = {channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>@@ -162,7 +163,7 @@ export const Disabled: Story = {channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>@@ -182,7 +183,7 @@ export const DisabledTransitively: Story = {channel: "output",data: "This data is stale because a parent is disabled",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>@@ -202,7 +203,7 @@ export const StaleStatus: Story = {channel: "output",data: "This data is stale because a parent is disabled",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>@@ -222,7 +223,7 @@ export const StaleAndEditedStatus: Story = {channel: "output",data: "This data is stale because a parent is disabled, but this cell has been edited since.",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>@@ -245,7 +246,7 @@ export const DisabledAndStaleStatus: Story = {channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>@@ -265,7 +266,7 @@ export const Running: Story = {channel: "output",data: "<span class='markdown'><h1>Layout</h1>\n<p><code>marimo</code> provides functions to help you lay out your output, such as\nin rows and columns, accordions, tabs, and callouts. This tutorial\nshows some examples.</p></span>",mimetype: "text/html",- timestamp: "1686863788",+ timestamp: 1_686_863_688,}}/></TooltipProvider>diff --git a/marimo/__init__.py b/marimo/__init__.pyindex ef68391423..46a8422556 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -29,6 +29,7 @@ __all__ = ["left","md","mpl",+ "output","pdf","refs","right",@@ -58,6 +59,7 @@ from marimo._plugins.stateless.image import imagefrom marimo._plugins.stateless.pdf import pdffrom marimo._plugins.stateless.tabs import tabsfrom marimo._plugins.stateless.tree import tree+from marimo._runtime import outputfrom marimo._runtime.control_flow import MarimoStopError, stopfrom marimo._runtime.runtime import defs, refsfrom marimo._runtime.state import statediff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 9a4153b50c..0dc23a2310 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -118,6 +118,25 @@ class CellOp(Op):status=status,).broadcast()+ @staticmethod+ def broadcast_empty_output(+ cell_id: Optional[CellId_t],+ status: Optional[CellStatusType],+ ) -> None:+ cell_id = (+ cell_id if cell_id is not None else get_context().stream.cell_id+ )+ assert cell_id is not None+ CellOp(+ cell_id=cell_id,+ output=CellOutput(+ channel="output",+ mimetype="text/plain",+ data="",+ ),+ status=status,+ ).broadcast()+@staticmethoddef broadcast_console_output(channel: str,diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.pyindex f52b9c091f..bb39d3c162 100644--- a/marimo/_output/formatting.py+++ b/marimo/_output/formatting.py@@ -18,8 +18,12 @@ taking precedence over the MIME protocol.from __future__ import annotationsimport inspect+import ioimport json+import pprint+import tracebackimport types+from dataclasses import dataclassfrom html import escapefrom typing import Any, Callable, Optional, Tuple, Type, TypeVar@@ -100,13 +104,42 @@ def get_formatter(obj: T) -> Optional[Formatter[T]]:return None-def get_mimetype_and_data(obj: Any) -> tuple[str, str]:- f = get_formatter(obj)- if f is None:- LOGGER.error("Failed to retrieve formatter for %s", obj)- return "text/plain", f"Failed to retrieve formatter for {obj}"+@dataclass+class FormattedOutput:+ mimetype: str+ data: str+ traceback: Optional[str] = None+++def try_format(obj: Any) -> FormattedOutput:+ obj = "" if obj is None else obj+ if (formatter := get_formatter(obj)) is not None:+ try:+ mimetype, data = formatter(obj)+ return FormattedOutput(mimetype=mimetype, data=data)+ except Exception: # noqa: E722+ return FormattedOutput(+ mimetype="text/plain",+ data="",+ traceback=traceback.format_exc(),+ )else:- return f(obj)+ tmpio = io.StringIO()+ tb = None+ if isinstance(obj, str):+ tmpio.write(obj)+ else:+ try:+ pprint.pprint(obj, stream=tmpio)+ except Exception: # noqa: E722+ tmpio.write("")+ tb = traceback.format_exc()+ tmpio.seek(0)+ return FormattedOutput(+ mimetype="text/plain",+ data=tmpio.read(),+ traceback=tb,+ )@mddocdiff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/cell_runner.pyindex 4625c6d100..2951e98f43 100644--- a/marimo/_runtime/cell_runner.py+++ b/marimo/_runtime/cell_runner.py@@ -1,8 +1,6 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations-import io-import pprintimport reimport sysimport traceback@@ -11,7 +9,6 @@ from dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Optionalfrom marimo._ast.cell import CellId_t, execute_cell-from marimo._output import formattingfrom marimo._runtime import dataflowfrom marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError@@ -80,17 +77,6 @@ def format_traceback(graph: dataflow.DirectedGraph) -> str:)-@dataclass-class FormattedOutput:- """Cell output transformed to wire format."""-- channel: str- mimetype: str- data: str- # non-None if there was an error in formatting the cell output.- traceback: Optional[str] = None--@dataclassclass RunResult:# Raw output of cell@@ -102,41 +88,6 @@ class RunResult:"""Whether the cell exected successfully"""return self.exception is None- def format_output(self) -> FormattedOutput:- """Formats raw output to wire format."""- return_value = "" if self.output is None else self.output- if (formatter := formatting.get_formatter(return_value)) is not None:- try:- mimetype, data = formatter(return_value)- return FormattedOutput(- channel="output", mimetype=mimetype, data=data- )- except Exception: # noqa: E722- return FormattedOutput(- channel="output",- mimetype="text/plain",- data="",- traceback=traceback.format_exc(),- )- else:- tmpio = io.StringIO()- tb = None- if isinstance(return_value, str):- tmpio.write(return_value)- else:- try:- pprint.pprint(return_value, stream=tmpio)- except Exception: # noqa: E722- tmpio.write("")- tb = traceback.format_exc()- tmpio.seek(0)- return FormattedOutput(- channel="output",- mimetype="text/plain",- data=tmpio.read(),- traceback=tb,- )-class Runner:"""Runner for a collection of cells."""diff --git a/marimo/_runtime/output/__init__.py b/marimo/_runtime/output/__init__.pynew file mode 100644index 0000000000..5db9bca045--- /dev/null+++ b/marimo/_runtime/output/__init__.py@@ -0,0 +1,11 @@+# Copyright 2023 Marimo. All rights reserved.+"""Write to a cell's output area."""+++__all__ = [+ "append",+ "clear",+ "replace",+]++from marimo._runtime.output._output import append, clear, replacediff --git a/marimo/_runtime/output/_output.py b/marimo/_runtime/output/_output.pynew file mode 100644index 0000000000..dd3827e9aa--- /dev/null+++ b/marimo/_runtime/output/_output.py@@ -0,0 +1,71 @@+# Copyright 2023 Marimo. All rights reserved.+import sys++from marimo._ast.cell import CellId_t+from marimo._messaging.ops import CellOp+from marimo._output import formatting+from marimo._output.rich_help import mddoc+from marimo._plugins.stateless.flex import vstack+from marimo._runtime.context import get_context+++def write_internal(cell_id: CellId_t, value: object) -> None:+ output = formatting.try_format(value)+ if output.traceback is not None:+ sys.stderr.write(output.traceback)+ CellOp.broadcast_output(+ channel="output",+ mimetype=output.mimetype,+ data=output.data,+ cell_id=cell_id,+ status=None,+ )+++@mddoc+def replace(value: object) -> None:+ """Replace a cell's output with a new one.++ Call `mo.output.replace()` to write to a cell's output area, replacing+ the existing output, if any.++ **Args:**++ - `value`: object to output+ """+ ctx = get_context()+ if ctx.kernel.execution_context is None:+ return+ ctx.kernel.execution_context.output = [value]+ write_internal(cell_id=ctx.kernel.execution_context.cell_id, value=value)+++@mddoc+def append(value: object) -> None:+ """Append a new object to a cell's output.++ Call this function to incrementally build a cell's output. Appended+ outputs are stacked vertically.++ **Args:**++ - `value`: object to output+ """+ ctx = get_context()+ if ctx.kernel.execution_context is None:+ return++ if ctx.kernel.execution_context.output is None:+ ctx.kernel.execution_context.output = [value]+ else:+ ctx.kernel.execution_context.output.append(value)+ write_internal(+ cell_id=ctx.kernel.execution_context.cell_id,+ value=vstack(ctx.kernel.execution_context.output),+ )+++@mddoc+def clear() -> None:+ """Clear a cell's output."""+ return replace(None)diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 1fe97f3534..5f375ba485 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -38,6 +38,7 @@ from marimo._messaging.ops import (VariableValues,)from marimo._messaging.streams import Stderr, Stdout, Stream, redirect_streams+from marimo._output import formattingfrom marimo._output.rich_help import mddocfrom marimo._plugins.stateless.mpl._mpl import InteractiveMplRegistryfrom marimo._plugins.ui._core.registry import UIElementRegistry@@ -120,6 +121,8 @@ def refs() -> tuple[str, ...]:class ExecutionContext:cell_id: CellId_tsetting_element_value: bool+ # output object set imperatively+ output: Optional[list[object]] = None@dataclasses.dataclass@@ -162,7 +165,7 @@ class Kernel:@contextlib.contextmanagerdef _install_execution_context(self, cell_id: CellId_t, setting_element_value: bool = False- ) -> Iterator[None]:+ ) -> Iterator[ExecutionContext]:self.execution_context = ExecutionContext(cell_id, setting_element_value)@@ -170,7 +173,7 @@ class Kernel:cell_id):try:- yield+ yield self.execution_contextfinally:self.execution_context = None@@ -571,8 +574,16 @@ class Kernel:LOGGER.debug("running cell %s", cell_id)cell.set_status(status="running")- with self._install_execution_context(cell_id):+ with self._install_execution_context(cell_id) as exc_ctx:run_result = runner.run(cell_id)+ # Don't rebroadcast an output that was already sent+ #+ # 1. if run_result.output is not None, need to send it+ # 2. otherwise if exc_ctx.output is None, then need to send+ # the (empty) output (to clear it)+ new_output = (+ run_result.output is not None or exc_ctx.output is None+ )values = [VariableValue(@@ -590,26 +601,16 @@ class Kernel:VariableValues(variables=values).broadcast()cell.set_status(status="idle")- if run_result.success():- formatted_output = run_result.format_output()- if formatted_output.traceback is not None:- with self._install_execution_context(cell_id):- sys.stderr.write(formatted_output.traceback)- CellOp.broadcast_output(- channel=formatted_output.channel,- mimetype=formatted_output.mimetype,- data=formatted_output.data,- cell_id=cell_id,- status=cell.status,- )- elif isinstance(run_result.exception, MarimoStopError):- LOGGER.debug("Cell %s was stopped via mo.stop()", cell_id)- formatted_output = run_result.format_output()+ if (+ run_result.success()+ or isinstance(run_result.exception, MarimoStopError)+ ) and new_output:+ formatted_output = formatting.try_format(run_result.output)if formatted_output.traceback is not None:with self._install_execution_context(cell_id):sys.stderr.write(formatted_output.traceback)CellOp.broadcast_output(- channel=formatted_output.channel,+ channel="output",mimetype=formatted_output.mimetype,data=formatted_output.data,cell_id=cell_id,diff --git a/marimo/_smoke_tests/output.py b/marimo/_smoke_tests/output.pynew file mode 100644index 0000000000..2ddc6a4ed8--- /dev/null+++ b/marimo/_smoke_tests/output.py@@ -0,0 +1,110 @@+# Copyright 2023 Marimo. All rights reserved.+import marimo++__generated_with = "0.1.19"+app = marimo.App()+++def __():+ import marimo as mo+ return mo,+++def __():+ import time+ return time,+++def __(mo, time):+ def loop_replace():+ for i in range(5):+ mo.output.replace(mo.md(f"Loading {i}/5"))+ time.sleep(.1)++ def loop_append():+ for i in range(5):+ mo.output.append(mo.md(f"Loading {i}/5"))+ time.sleep(.1)+ return loop_append, loop_replace+++def __(mo):+ mo.md("### Replace")+ return+++def __(loop_replace, mo):+ loop_replace()+ mo.md("Done!")+ return+++def __(loop_replace, mo):+ loop_replace()+ mo.output.replace(mo.md(f"Done"))+ return+++def __(mo):+ mo.md("### Append")+ return+++def __(loop_append, mo):+ loop_append()+ mo.md("Done!")+ return+++def __(loop_append, mo):+ loop_append()+ mo.output.append(mo.md("Done!"))+ return+++def __(mo):+ mo.md("### Clear")+ return+++def __(loop_append, mo):+ loop_append()+ mo.output.append(mo.md("Done!"))+ mo.output.clear()+ return+++def __(loop_append, mo):+ loop_append()+ mo.output.append(mo.md("Done!"))+ mo.output.replace(None)+ return+++def __(mo):+ mo.md("### Sleep (stale)")+ return+++def __(time):+ time.sleep(2)+ "hello"+ return+++if __name__ == "__main__":+ app.run()