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: mo.show_code(output) (#2342)

Akshay Agrawal2b64e215e025
diff --git a/docs/api/outputs.md b/docs/api/outputs.md
index f419f3037a..ff75353bd3 100644
--- a/docs/api/outputs.md
+++ b/docs/api/outputs.md
@@ -38,6 +38,15 @@ already written. Wrap the last expression in `mo.output.append` if you want
to add to an existing output instead of replacing it.
```
+### Display cell code in marimo's app views
+
+Use `mo.show_code()` to display the cell's code in the output area, which
+will then be visible in all app views.
+
+```{eval-rst}
+.. autofunction:: marimo.show_code
+```
+
## Console outputs
```{admonition} Console outputs
diff --git a/docs/faq.md b/docs/faq.md
index 8329cea186..0b7b736ed5 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -18,6 +18,7 @@
- [How do I prevent matplotlib plots from being cut off?](#faq-mpl-cutoff)
- [How do I display interactive matplotlib plots?](#faq-interactive-plots)
- [How do I display objects in rows and columns?](#faq-rows-columns)
+ - [How do I show cell code in the app view?](#faq-show-code)
- [How do I create an output with a dynamic number of UI elements?](#faq-dynamic-ui-elements)
- [Why aren't my `on_change` handlers being called?](#faq-on-change-called)
- [Why are my `on_change` handlers in an array all referencing the last element?](#faq-on-change-last)
@@ -310,6 +311,12 @@ Use `marimo.hstack` and `marimo.vstack`. See the layout tutorial for details:
marimo tutorial layout
```
+<a name="faq-show-code"></a>
+
+### How do I show cell code in the app view?(#faq-show-code)
+
+Use [`mo.show_code`](/api/outputs.md#marimo.show_code).
+
<a name="faq-dynamic-ui-elements"></a>
### How do I create an output with a dynamic number of UI elements?
diff --git a/marimo/__init__.py b/marimo/__init__.py
index c471151587..35dc9d87b7 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -56,6 +56,7 @@ __all__ = [
"right",
"running_in_notebook",
"routes",
+ "show_code",
"sidebar",
"stat",
"state",
@@ -79,6 +80,7 @@ from marimo._output.formatting import as_html, plain
from marimo._output.hypertext import Html
from marimo._output.justify import center, left, right
from marimo._output.md import md
+from marimo._output.show_code import show_code
from marimo._plugins import ui
from marimo._plugins.stateless import mpl, status
from marimo._plugins.stateless.accordion import accordion
diff --git a/marimo/_output/show_code.py b/marimo/_output/show_code.py
new file mode 100644
index 0000000000..e863d202f8
--- /dev/null
+++ b/marimo/_output/show_code.py
@@ -0,0 +1,88 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import re
+from typing import Literal
+
+from marimo._output.formatting import as_html
+from marimo._output.hypertext import Html
+from marimo._plugins.stateless.flex import vstack
+from marimo._plugins.ui._impl.input import code_editor
+from marimo._runtime.context import get_context
+from marimo._runtime.context.types import ContextNotInitializedError
+
+
+def show_code(
+ output: object = None, position: Literal["above", "below"] = "below"
+) -> Html:
+ """Display an output along with the code of the current cell.
+
+ Use `mo.show_code` to show the code of the current cell along with
+ the cell's output. This is useful if you want a cell's code to
+ appear in the app preview or when running the notebook as an app
+ with `marimo run`.
+
+ In the displayed code, all occurrences of mo.show_code(...) will be
+ replaced with ...
+
+ Show code that produces the output `factorial(5)`:
+
+ ```python
+ def factorial(n: int) -> int:
+ if n == 0:
+ return 1
+ return n * factorial(n - 1)
+
+
+ mo.show_code(factorial(5))
+ ```
+
+ Show code of a cell, without an output:
+
+ ```python
+ def factorial(n: int) -> int:
+ if n == 0:
+ return 1
+ return n * factorial(n - 1)
+
+
+ mo.show_code()
+ ```
+
+ **Args:**
+
+ - output: the output to display above the cell's code; omit the output
+ to just show the cel's code, without an output.
+ - position: whether the output should be above or below the code
+
+ **Returns:**
+
+ HTML of the `output` arg displayed with its code.
+ """
+ try:
+ context = get_context()
+ except ContextNotInitializedError:
+ return as_html(output)
+
+ cell_id = context.cell_id
+ if cell_id is None:
+ return as_html(output)
+
+ cell = context.graph.cells[cell_id]
+ pattern = r"mo\.show_code\((.*?)\)"
+ code = re.sub(pattern, r"\1", cell.code, flags=re.DOTALL).strip()
+
+ if output is not None:
+ return vstack(
+ [
+ code_editor(value=code, disabled=True, min_height=1),
+ as_html(output),
+ ]
+ if position == "below"
+ else [
+ as_html(output),
+ code_editor(value=code, disabled=True, min_height=1),
+ ]
+ )
+ else:
+ return code_editor(value=code, disabled=True, min_height=1)
diff --git a/tests/_output/test_show_code.py b/tests/_output/test_show_code.py
new file mode 100644
index 0000000000..e377f274c0
--- /dev/null
+++ b/tests/_output/test_show_code.py
@@ -0,0 +1,39 @@
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+
+async def test_show_code_basic(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run([exec_req.get("import marimo as mo; x = mo.show_code(1)")])
+ assert "x = 1" in k.globals["x"].text
+
+
+async def test_show_code_no_output(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run([exec_req.get("import marimo as mo; x = mo.show_code()")])
+ assert "import marimo as mo; x =" in k.globals["x"].text, k.globals[
+ "x"
+ ].text
+ assert "mo.show_code()" not in k.globals["x"].text
+
+
+async def test_show_code_multiline(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo;
+ x = mo.show_code('''
+ hello world
+ '''
+ )
+ """
+ )
+ ]
+ )
+ assert "hello world" in k.globals["x"].text
+ assert "(" not in k.globals["x"].text
+ assert ")" not in k.globals["x"].text
+ assert "mo.show_code" not in k.globals["x"].text