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.

Support hiding code in setup cells (#5852)

Trevor Manz113cd4eed67f
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 029f585cb6..a98385b064 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -1053,6 +1053,14 @@ const SetupCellComponent = ({
// Callback to get the editor view.
const getEditorView = useCallback(() => editorView.current, [editorView]);
+ const { isCellCodeShown, showHiddenCode } = useCellHiddenLogic({
+ cellId,
+ cellConfig,
+ languageAdapter: "python",
+ editorView,
+ editorViewParentRef,
+ });
+
// Use the extracted hooks
const { closeCompletionHandler, resumeCompletionHandler } = useCellCompletion(
cellRef,
@@ -1120,7 +1128,7 @@ const SetupCellComponent = ({
title={renderCellTitle()}
data-setup-cell={true}
>
- <div className={cn("tray")} data-hidden={false}>
+ <div className={cn("tray")} data-hidden={!isCellCodeShown}>
<div className="absolute right-2 -top-4 z-10">
<CellToolbar
edited={edited}
@@ -1135,7 +1143,7 @@ const SetupCellComponent = ({
name={name}
getEditorView={getEditorView}
onRun={runCell}
- includeCellActions={false}
+ includeCellActions={true}
/>
</div>
<CellEditor
@@ -1151,9 +1159,9 @@ const SetupCellComponent = ({
userConfig={userConfig}
editorViewRef={editorView}
editorViewParentRef={editorViewParentRef}
- hidden={false}
+ hidden={!isCellCodeShown}
hasOutput={hasOutput}
- showHiddenCode={Functions.NOOP}
+ showHiddenCode={showHiddenCode}
languageAdapter={"python"}
setLanguageAdapter={Functions.NOOP}
showLanguageToggles={false}
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 24c2e47cbb..ca9bf094be 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -109,9 +109,16 @@ class _SetupContext:
See design discussion in MEP-0008 (github:marimo-team/meps/pull/8).
"""
- def __init__(self, cell: Cell):
+ def __init__(
+ self,
+ cell: Cell,
+ app: App,
+ hide_code: bool,
+ ):
super().__init__()
+ self._app = app
self._cell = cell
+ self._hide_code = hide_code
self._glbls: dict[str, Any] = {}
self._frame: Optional[FrameType] = None
self._previous: dict[str, Any] = {}
@@ -158,6 +165,23 @@ class _SetupContext:
self._glbls[var] = self._frame.f_locals.get(var)
return False
+ def __call__(
+ self,
+ *,
+ hide_code: bool = False,
+ **kwargs: Any, # noqa: ARG002
+ ) -> _SetupContext:
+ """When called with parameters, create a new context with those parameters."""
+ cell = self._app._cell_manager.cell_context(
+ app=InternalApp(self._app),
+ frame=inspect.stack()[1].frame,
+ config=CellConfig(hide_code=hide_code),
+ )
+ self._app._setup = _SetupContext(
+ app=self._app, cell=cell, hide_code=hide_code
+ )
+ return self._app._setup
+
@dataclass
class AppEmbedResult:
@@ -457,22 +481,34 @@ class App:
"""Provides a context manager to initialize the setup cell.
This block should only be utilized at the start of a marimo notebook.
- It's used as following:
+ Usage:
```
+ # As a property (default behavior)
with app.setup:
import my_libraries
from typing import Any
+ CONSTANT = "my constant"
+
+ # As a method with hide_code
+ with app.setup(hide_code=True):
+ import my_libraries
+ from typing import Any
+
CONSTANT = "my constant"
```
+
+ Args (when called as method):
+ hide_code: Whether to hide the setup cell's code. Defaults to False.
+ **kwargs: For forward-compatibility with future arguments.
"""
# Get the calling context to extract the location of the cell
frame = inspect.stack()[1].frame
cell = self._cell_manager.cell_context(
app=InternalApp(self), frame=frame
)
- self._setup = _SetupContext(cell)
+ self._setup = _SetupContext(app=self, cell=cell, hide_code=False)
return self._setup
def _unparsable_cell(
diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.py
index 0a8d3c40ba..281909c0b9 100644
--- a/marimo/_ast/cell_manager.py
+++ b/marimo/_ast/cell_manager.py
@@ -192,6 +192,7 @@ class CellManager:
self,
frame: FrameType,
app: InternalApp | None = None,
+ config: Optional[CellConfig] = None,
) -> Cell:
"""Registers cells when called through a context block."""
cell = context_cell_factory(
@@ -199,7 +200,7 @@ class CellManager:
# NB. carry along the frame from the initial call.
frame=frame,
)
- cell._cell.configure(CellConfig())
+ cell._cell.configure(config or CellConfig())
self._register_cell(cell, app=app)
return cell
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 3d47dc403f..a8bc12f04f 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -158,9 +158,14 @@ def build_setup_section(setup_cell: Optional[CellImpl]) -> str:
if has_only_comments:
block += "\npass"
+ if setup_cell.config.hide_code:
+ setup_line = f"{prefix}with app.setup(hide_code=True):"
+ else:
+ setup_line = f"{prefix}with app.setup:"
+
return "\n".join(
[
- f"{prefix}with app.setup:",
+ setup_line,
indent_text(block),
"\n",
]
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index 53f3968458..40e1f31864 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -1042,6 +1042,44 @@ class TestAppComposition:
assert defs["x"] == 0
assert "app" not in defs
+ @staticmethod
+ def test_setup_hide_code() -> None:
+ # Test property access (default behavior, hide_code=False)
+ app1 = App()
+ with app1.setup:
+ x = 1
+
+ setup_cell = app1._cell_manager._cell_data.get("setup")
+ assert setup_cell is not None
+ assert setup_cell.config.hide_code is False
+
+ # Test method call with default (hide_code=False)
+ app2 = App()
+ with app2.setup():
+ x2 = 1
+
+ setup_cell = app2._cell_manager._cell_data.get("setup")
+ assert setup_cell is not None
+ assert setup_cell.config.hide_code is False
+
+ # Test hide_code=True
+ app3 = App()
+ with app3.setup(hide_code=True):
+ y = 2
+
+ setup_cell = app3._cell_manager._cell_data.get("setup")
+ assert setup_cell is not None
+ assert setup_cell.config.hide_code is True
+
+ # Test explicit hide_code=False
+ app4 = App()
+ with app4.setup(hide_code=False):
+ z = 3
+
+ setup_cell = app4._cell_manager._cell_data.get("setup")
+ assert setup_cell is not None
+ assert setup_cell.config.hide_code is False
+
class TestAppKernelRunnerRegistry:
def test_get_runner(self, k: Kernel) -> None: