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: Cleanup app.py file, initialize empty App() (#644)

Myles Scolnickc986ef2a62f3
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index b31dedebde..726728dd2a 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -3,8 +3,18 @@ from __future__ import annotations
from collections.abc import Sequence
from dataclasses import asdict, dataclass
-from typing import Any, Callable, Iterable, Literal, Optional, Union, cast
+from typing import (
+ Any,
+ Callable,
+ Iterable,
+ Literal,
+ Optional,
+ OrderedDict,
+ Union,
+ cast,
+)
+from marimo import _loggers
from marimo._ast.cell import (
CellConfig,
CellFunction,
@@ -23,6 +33,8 @@ from marimo._ast.errors import (
from marimo._output.rich_help import mddoc
from marimo._runtime.dataflow import DirectedGraph, topological_sort
+LOGGER = _loggers.marimo_logger()
+
@dataclass
class _AppConfig:
@@ -82,25 +94,12 @@ class App:
if key in kwargs:
self._config.__setattr__(key, kwargs.pop(key))
- self._cell_data: dict[CellId_t, CellData] = {}
- self._registration_order: list[CellId_t] = []
+ self._cell_manager = CellManager()
+ self._graph = DirectedGraph()
- self._cell_id_counter = 0
self._unparsable = False
self._initialized = False
- def _cell_configs(self) -> dict[CellId_t, CellConfig]:
- return {cid: cd.config for cid, cd in self._cell_data.items()}
-
- def _create_cell_id(
- self, cell_function: Optional[CellFunction[CellFuncTypeBound]]
- ) -> CellId_t:
- del cell_function
- cell_id = str(self._cell_id_counter)
- self._registration_order.append(cell_id)
- self._cell_id_counter += 1
- return str(cell_id)
-
def cell(
self,
func: Optional[CellFuncTypeBound] = None,
@@ -138,6 +137,118 @@ class App:
"""
del kwargs
+ return self._cell_manager.cell_decorator(func, disabled, hide_code)
+
+ def _unparsable_cell(
+ self,
+ code: str,
+ name: Optional[str] = None,
+ **config: Any,
+ ) -> None:
+ self._cell_manager.register_unparsable_cell(
+ code,
+ name,
+ CellConfig.from_dict(config),
+ )
+ self._unparsable = True
+
+ def _maybe_initialize(self) -> None:
+ assert not self._unparsable
+
+ if self._initialized:
+ LOGGER.warning(
+ "App was initialized twice. This is probably a bug in marimo."
+ )
+ return
+
+ # Add cells to graph
+ for cell_id, cell_fn in self._cell_manager.valid_cells():
+ self._graph.register_cell(cell_id, cell_fn.cell)
+ self._defs = self._graph.definitions.keys()
+
+ try:
+ # Check for cycles, multiply defined names, and deleted nonlocal
+ if self._graph.cycles:
+ raise CycleError(
+ "This app can't be run because it has cycles."
+ )
+ name = self._graph.get_multiply_defined()
+ if name is not None:
+ raise MultipleDefinitionError(
+ "This app can't be run because it has multiple "
+ f"definitions of the name {name}"
+ )
+ ref = self._graph.get_deleted_nonlocal_ref()
+ if ref is not None:
+ raise DeleteNonlocalError(
+ "This app can't be run because at least one cell "
+ f"deletes one of its refs (the ref's name is {ref})"
+ )
+ self._execution_order = topological_sort(
+ self._graph, list(self._cell_manager.valid_cell_ids())
+ )
+ finally:
+ self._initialized = True
+
+ def run(self) -> tuple[Sequence[Any], dict[str, Any]]:
+ if self._unparsable:
+ raise UnparsableError(
+ "This app can't be run because it has unparsable cells."
+ )
+
+ self._maybe_initialize()
+ glbls: dict[Any, Any] = {}
+
+ # Execute cells and collect outputs
+ outputs: dict[CellId_t, Any] = {}
+ for cid in self._execution_order:
+ cell_function = self._cell_manager.cell_data_at(cid).cell_function
+ if cell_function is not None:
+ outputs[cid] = execute_cell(cell_function.cell, glbls)
+
+ # Return
+ # - the outputs, sorted in the order that cells were added to the
+ # graph
+ # - dict of defs -> values
+ return (
+ tuple(outputs[cid] for cid in self._cell_manager.valid_cell_ids()),
+ # omit defs that were never defined at runtime, eg due to
+ # conditional definitions like
+ #
+ # if cond:
+ # x = 0
+ {name: glbls[name] for name in self._defs if name in glbls},
+ )
+
+
+class CellManager:
+ """
+ A manager for cells.
+
+ This holds the cells that have been registered with the app, and
+ provides methods to access them.
+ """
+
+ def __init__(self) -> None:
+ self._cell_data: dict[CellId_t, CellData] = {}
+ self._cell_data = OrderedDict()
+ self._cell_id_counter = 0
+ self.unparsable = False
+
+ def create_cell_id(self) -> CellId_t:
+ cell_id = str(self._cell_id_counter)
+ self._cell_id_counter += 1
+ return cell_id
+
+ def cell_decorator(
+ self,
+ func: Optional[CellFuncTypeBound],
+ disabled: bool,
+ hide_code: bool,
+ ) -> Union[
+ Callable[[CellFuncType], CellFunction[CellFuncTypeBound]],
+ CellFunction[CellFuncTypeBound],
+ ]:
cell_config = CellConfig(disabled=disabled, hide_code=hide_code)
if func is None:
@@ -151,59 +262,53 @@ class App:
func, cell_id=str(self._cell_id_counter)
)
cell_function.cell.configure(cell_config)
- self._register_cell(cell_function)
+ self._register_cell_function(cell_function)
return cell_function
return cast(
Callable[[CellFuncType], CellFunction[CellFuncTypeBound]],
decorator,
)
- else:
- # If the decorator was used without parentheses, func will be the
- # decorated function
- cell_function = cell_factory(
- func, cell_id=str(self._cell_id_counter)
- )
- cell_function.cell.configure(cell_config)
- self._register_cell(cell_function)
- return cell_function
- def _register_cell(
+ # If the decorator was used without parentheses, func will be the
+ # decorated function
+ cell_function = cell_factory(func, cell_id=str(self._cell_id_counter))
+ cell_function.cell.configure(cell_config)
+ self._register_cell_function(cell_function)
+ return cell_function
+
+ def _register_cell_function(
self, cell_function: CellFunction[CellFuncTypeBound]
) -> None:
- cell_id = self._create_cell_id(cell_function)
- self._cell_data[cell_id] = CellData(
- cell_id=cell_id,
+ self.register_cell(
code=cell_function.cell.code,
name=cell_function.__name__,
config=cell_function.cell.config,
cell_function=cast(CellFunction[CellFuncType], cell_function),
)
- def _names(self) -> Iterable[str]:
- return (cell_data.name for cell_data in self._cell_data.values())
-
- def _codes(self) -> Iterable[str]:
- return (cell_data.code for cell_data in self._cell_data.values())
-
- def _configs(self) -> Iterable[CellConfig]:
- return (cell_data.config for cell_data in self._cell_data.values())
-
- def _cell_functions(
+ def register_cell(
self,
- ) -> Iterable[Optional[CellFunction[CellFuncType]]]:
- return (
- cell_data.cell_function for cell_data in self._cell_data.values()
+ code: str,
+ config: Optional[CellConfig],
+ name: str = "__",
+ cell_function: Optional[CellFunction[CellFuncType]] = None,
+ ) -> None:
+ cell_id = self.create_cell_id()
+ self._cell_data[cell_id] = CellData(
+ cell_id=cell_id,
+ code=code,
+ name=name,
+ config=config or CellConfig(),
+ cell_function=cell_function,
)
- def _unparsable_cell(
+ def register_unparsable_cell(
self,
code: str,
- name: Optional[str] = None,
- **config: Any,
+ name: Optional[str],
+ cell_config: CellConfig,
) -> None:
- cell_id = self._create_cell_id(None)
- name = name if name is not None else "__"
# - code.split("\n")[1:-1] disregards first and last lines, which are
# empty
# - line[4:] removes leading indent in multiline string
@@ -212,102 +317,74 @@ class App:
code = "\n".join(
[line[4:].replace('\\"', '"') for line in code.split("\n")[1:-1]]
)
- self._cell_data[cell_id] = CellData(
- cell_id=cell_id,
- code=code,
- name=name,
- config=CellConfig.from_dict(config),
+
+ self.register_cell(
+ code,
+ cell_config,
+ name or "__",
cell_function=None,
)
- self._unparsable = True
- def _maybe_initialize(self) -> None:
- assert not self._unparsable
- if not self._initialized:
- # ids of cells to add to the graph, in the order that they
- # were registered with the app
- self._cell_ids = [
- # exclude unparsable cells from graph
- cell_data.cell_id
- for cell_data in self._cell_data.values()
- if cell_data.cell_function is not None
- ]
- self._graph = DirectedGraph()
- for cell_id in self._cell_ids:
- cell_function = self._cell_data[cell_id].cell_function
- assert cell_function is not None
- self._graph.register_cell(cell_id, cell_function.cell)
- self._defs = self._graph.definitions.keys()
-
- # these two helper functions could be written as concise
- # `any` expressions using assignment expressions, but
- # that's a silly reason to make Python < 3.8 incompatible
- # with marimo.
- def get_multiply_defined() -> Optional[str]:
- for name, definers in self._graph.definitions.items():
- if len(definers) > 1:
- return name
- return None
-
- def get_deleted_nonlocal_ref() -> Optional[str]:
- for cell in self._graph.cells.values():
- for ref in cell.deleted_refs:
- if ref in self._graph.definitions:
- return ref
- return None
-
- try:
- if self._graph.cycles:
- raise CycleError(
- "This app can't be run because it has cycles."
- )
- name = get_multiply_defined()
- if name is not None:
- raise MultipleDefinitionError(
- "This app can't be run because it has multiple "
- f"definitions of the name {name}"
- )
- ref = get_deleted_nonlocal_ref()
- if ref is not None:
- raise DeleteNonlocalError(
- "This app can't be run because at least one cell "
- f"deletes one of its refs (the ref's name is {ref})"
- )
- self._execution_order = topological_sort(
- self._graph, self._cell_ids
- )
- finally:
- self._initialized = True
+ def names(self) -> Iterable[str]:
+ for cell_data in self._cell_data.values():
+ yield cell_data.name
- def run(self) -> tuple[Sequence[Any], dict[str, Any]]:
- if self._unparsable:
- raise UnparsableError(
- "This app can't be run because it has unparsable cells."
- )
+ def codes(self) -> Iterable[str]:
+ for cell_data in self._cell_data.values():
+ yield cell_data.code
- self._maybe_initialize()
- glbls: dict[Any, Any] = {}
- outputs = {
- cid: execute_cell(cell_function.cell, glbls)
- for cid in self._execution_order
- if (cell_function := self._cell_data[cid].cell_function)
- is not None
- }
- # Return
- # - the outputs, sorted in the order that cells were added to the
- # graph
- # - dict of defs -> values
- return (
- tuple(
- outputs[cid]
- for cid in self._registration_order
- # exclude unparsable cells
- if cid in outputs
- ),
- # omit defs that were never defined at runtime, eg due to
- # conditional definitions like
- #
- # if cond:
- # x = 0
- {name: glbls[name] for name in self._defs if name in glbls},
- )
+ def configs(self) -> Iterable[CellConfig]:
+ for cell_data in self._cell_data.values():
+ yield cell_data.config
+
+ def valid_cells(
+ self,
+ ) -> Iterable[tuple[CellId_t, CellFunction[CellFuncType]]]:
+ """Return cells and functions for each valid cell."""
+ for cell_data in self._cell_data.values():
+ if cell_data.cell_function is not None:
+ yield (cell_data.cell_id, cell_data.cell_function)
+
+ def valid_cell_ids(self) -> Iterable[CellId_t]:
+ for cell_data in self._cell_data.values():
+ if cell_data.cell_function is not None:
+ yield cell_data.cell_id
+
+ def cell_ids(self) -> Iterable[CellId_t]:
+ """Cell IDs in the order they were registered."""
+ return self._cell_data.keys()
+
+ def cell_functions(
+ self,
+ ) -> Iterable[Optional[CellFunction[CellFuncType]]]:
+ for cell_data in self._cell_data.values():
+ yield cell_data.cell_function
+
+ def config_map(self) -> dict[CellId_t, CellConfig]:
+ return {cid: cd.config for cid, cd in self._cell_data.items()}
+
+ def cell_data(self) -> Iterable[CellData]:
+ return self._cell_data.values()
+
+ def cell_data_at(self, cell_id: CellId_t) -> CellData:
+ return self._cell_data[cell_id]
+
+
+class InternalApp:
+ """
+ Internal representation of an app.
+
+ This exposes private APIs that are used by the server and other
+ internal components.
+ """
+
+ def __init__(self, app: App) -> None:
+ self._app = app
+
+ @property
+ def config(self) -> _AppConfig:
+ return self._app._config
+
+ @property
+ def cell_manager(self) -> CellManager:
+ return self._app._cell_manager
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index fcfbcc8d6b..f0999c83ea 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import threading
from collections.abc import Collection
from dataclasses import dataclass, field
-from typing import Tuple
+from typing import Optional, Tuple
from marimo import _loggers
from marimo._ast.cell import Cell, CellId_t
@@ -254,6 +254,23 @@ class DirectedGraph:
queue.append(parent_id)
return False
+ # these two helper functions could be written as concise
+ # `any` expressions using assignment expressions, but
+ # that's a silly reason to make Python < 3.8 incompatible
+ # with marimo.
+ def get_multiply_defined(self) -> Optional[str]:
+ for name, definers in self.definitions.items():
+ if len(definers) > 1:
+ return name
+ return None
+
+ def get_deleted_nonlocal_ref(self) -> Optional[str]:
+ for cell in self.cells.values():
+ for ref in cell.deleted_refs:
+ if ref in self.definitions:
+ return ref
+ return None
+
def transitive_closure(
graph: DirectedGraph, cell_ids: set[CellId_t]
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index 809a68642d..eb157d2f7c 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -5,7 +5,6 @@ from starlette.authentication import requires
from starlette.requests import Request
from marimo import _loggers
-from marimo._ast.app import App
from marimo._runtime import requests
from marimo._runtime.requests import (
CreationRequest,
@@ -65,17 +64,10 @@ async def instantiate(
body = await parse_request(request, cls=InstantiateRequest)
execution_requests: tuple[ExecutionRequest, ...]
- if notebook is None:
- # Instantiating an empty app
- # TODO(akshayka): In this case, don't need to run anything ...
- execution_requests = (
- ExecutionRequest(cell_id=App()._create_cell_id(None), code=""),
- )
- else:
- execution_requests = tuple(
- ExecutionRequest(cell_id=cell_data.cell_id, code=cell_data.code)
- for cell_data in notebook._cell_data.values()
- )
+ execution_requests = tuple(
+ ExecutionRequest(cell_id=cell_data.cell_id, code=cell_data.code)
+ for cell_data in notebook.cell_manager.cell_data()
+ )
app_state.require_current_session().put_request(
CreationRequest(
diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.py
index 59ba3a70c9..536e1619aa 100644
--- a/marimo/_server/api/endpoints/files.py
+++ b/marimo/_server/api/endpoints/files.py
@@ -205,14 +205,16 @@ async def save_app_config(
body = await parse_request(request, cls=SaveAppConfigurationRequest)
mgr = app_state.session_manager
mgr.update_app_config(body.config)
+
# Update the file with the latest app config
# TODO(akshayka): Only change the `app = marimo.App` line (at top level
# of file), instead of overwriting the whole file.
app = mgr.load_app()
- if app is not None and mgr.filename is not None:
- codes = list(app._codes())
- names = list(app._names())
- configs = list(app._configs())
+
+ if mgr.filename is not None:
+ codes = list(app.cell_manager.codes())
+ names = list(app.cell_manager.names())
+ configs = list(app.cell_manager.configs())
# Try to save the app under the name `mgr.filename`
contents = codegen.generate_filecontents(
diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.py
index 987f743c8d..fdd47151e3 100644
--- a/marimo/_server/api/endpoints/ws.py
+++ b/marimo/_server/api/endpoints/ws.py
@@ -87,16 +87,12 @@ class WebsocketHandler(SessionHandler):
configs: tuple[CellConfig, ...]
app = mgr.load_app()
layout: Optional[LayoutConfig] = None
- if app is None:
- codes = ("",)
- names = ("__",)
- configs = (CellConfig(),)
- elif mgr.should_send_code_to_frontend():
+ if mgr.should_send_code_to_frontend():
codes, names, configs = tuple(
zip(
*tuple(
(cell_data.code, cell_data.name, cell_data.config)
- for cell_data in app._cell_data.values()
+ for cell_data in app.cell_manager.cell_data()
)
)
)
@@ -106,18 +102,18 @@ class WebsocketHandler(SessionHandler):
*tuple(
# Don't send code to frontend in run mode
("", "", cell_data.config)
- for cell_data in app._cell_data.values()
+ for cell_data in app.cell_manager.cell_data()
)
)
)
if (
app
- and app._config.layout_file is not None
+ and app.config.layout_file is not None
and isinstance(mgr.filename, str)
):
app_dir = os.path.dirname(mgr.filename)
- layout = read_layout_config(app_dir, app._config.layout_file)
+ layout = read_layout_config(app_dir, app.config.layout_file)
await self.message_queue.put(
(
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 6faa2aacb4..7657532969 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -28,7 +28,7 @@ from uuid import uuid4
from marimo import _loggers
from marimo._ast import codegen
-from marimo._ast.app import App, _AppConfig
+from marimo._ast.app import App, InternalApp, _AppConfig
from marimo._ast.cell import CellConfig, CellId_t
from marimo._messaging.ops import Alert, serialize
from marimo._output.formatters.formatters import register_formatters
@@ -198,9 +198,9 @@ class Session:
cls,
session_handler: SessionHandler,
mode: SessionMode,
- app: Optional[App],
+ app: InternalApp,
) -> Session:
- configs = app._cell_configs() if app else {}
+ configs = app.cell_manager.config_map()
use_multiprocessing = mode == SessionMode.EDIT
queue_manager = QueueManager(use_multiprocessing)
kernel_manager = KernelManager(queue_manager, mode, configs)
@@ -278,13 +278,11 @@ class SessionManager:
self.development_mode = development_mode
self.quiet = quiet
self.sessions: dict[str, Session] = {}
- self.app_config: Optional[_AppConfig]
+ self.app_config: _AppConfig
self.include_code = include_code
- if (app := self.load_app()) is not None:
- self.app_config = app._config
- else:
- self.app_config = None
+ app = self.load_app()
+ self.app_config = app.config
if mode == SessionMode.EDIT:
# In edit mode, the server gets a random token to prevent
@@ -296,17 +294,27 @@ class SessionManager:
# the frontend's app matches the server's app.
assert app is not None
self.server_token = str(
- hash("".join(code for code in app._codes()))
+ hash("".join(code for code in app.cell_manager.codes()))
)
- def load_app(self) -> Optional[App]:
- return codegen.get_app(self.filename)
+ def load_app(self) -> InternalApp:
+ """
+ Load the app from the current file.
+ Otherwise, return an empty app.
+ """
+
+ app = codegen.get_app(self.filename)
+ if app is None:
+ empty_app = InternalApp(App())
+ empty_app.cell_manager.register_cell(
+ code="",
+ config=CellConfig(),
+ )
+ return empty_app
+ return InternalApp(app)
def update_app_config(self, config: dict[str, Any]) -> None:
- if self.app_config is not None:
- self.app_config.update(config)
- else:
- self.app_config = _AppConfig(**config)
+ self.app_config.update(config)
def rename(self, filename: Optional[str]) -> None:
"""Register a change in filename.
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index 160bc58f7f..56054810a5 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -37,12 +37,13 @@ class TestApp:
z = y + 1
return y, z
- cell_names = tuple(app._names())
+ cell_manager = app._cell_manager
+ cell_names = tuple(cell_manager.names())
assert cell_names[0] == "one"
assert cell_names[1] == "two"
assert cell_names[2] == "__"
- codes = tuple(app._codes())
+ codes = tuple(cell_manager.codes())
assert codes[0] == "x = 0\nx"
assert codes[1] == "a = x + z\na + 1"
assert codes[2] == "y = x + 1\nz = y + 1"
@@ -290,7 +291,8 @@ class TestApp:
assert __x__ == 0
return
- configs = tuple(app._configs())
+ cell_manager = app._cell_manager
+ configs = tuple(cell_manager.configs())
assert configs[0].disabled
assert configs[1].hide_code
diff --git a/tests/_ast/test_app_cell.py b/tests/_ast/test_app_cell.py
index 9a0aa7c5bd..fbd7ae00c0 100644
--- a/tests/_ast/test_app_cell.py
+++ b/tests/_ast/test_app_cell.py
@@ -14,7 +14,7 @@ def mock_register_cell(cf: CellFunction[CellFuncType]) -> None:
app = App()
-app._register_cell = mock_register_cell # type: ignore[method-assign, assignment] # noqa: E501
+app._cell_manager._register_cell_function = mock_register_cell # type: ignore[method-assign, assignment] # noqa: E501
def test_decorator_called() -> None:
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index 4119850df7..1b3745361c 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -148,8 +148,15 @@ class TestGetCodes:
def test_get_codes() -> None:
app = codegen.get_app(get_filepath("test_generate_filecontents"))
assert app is not None
- assert list(app._names()) == ["one", "two", "three", "four", "five"]
- assert list(app._codes()) == [
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == [
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ ]
+ assert list(cell_manager.codes()) == [
"import numpy as np",
"x = 0\nxx = 1",
"y = x + 1",
@@ -163,8 +170,15 @@ class TestGetCodes:
get_filepath("test_get_codes_with_incorrect_args_rets")
)
assert app is not None
- assert list(app._names()) == ["one", "two", "three", "four", "five"]
- assert list(app._codes()) == [
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == [
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ ]
+ assert list(cell_manager.codes()) == [
"import numpy as np",
"x = 0\nxx = 1",
"y = x + 1",
@@ -177,8 +191,9 @@ class TestGetCodes:
# name mo is not defined --- make sure this file is still parseable
app = codegen.get_app(get_filepath("test_get_codes_with_name_error"))
assert app is not None
- assert list(app._names()) == ["one"]
- assert list(app._codes()) == [
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == [
"mo",
]
@@ -186,8 +201,9 @@ class TestGetCodes:
def test_get_codes_multiline_fndef() -> None:
app = codegen.get_app(get_filepath("test_get_codes_multiline_fndef"))
assert app is not None
- assert list(app._names()) == ["one"]
- assert list(app._codes()) == [
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == [
"# comment\nx = 0 + a + b + c + d",
]
@@ -195,8 +211,9 @@ class TestGetCodes:
def test_get_codes_messy() -> None:
app = codegen.get_app(get_filepath("test_get_codes_messy"))
assert app is not None
- assert list(app._names()) == ["__"]
- assert list(app._codes()) == [
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["__"]
+ assert list(cell_manager.codes()) == [
"# comment\n# another comment\n\n# yet another comment\n"
+ "x = 0 + a + b + c + d",
]
@@ -205,29 +222,33 @@ class TestGetCodes:
def test_get_codes_single_line_fn() -> None:
app = codegen.get_app(get_filepath("test_get_codes_single_line_fn"))
assert app is not None
- assert list(app._names()) == ["one"]
- assert list(app._codes()) == ["c = a + b; print(c); "]
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == ["c = a + b; print(c); "]
@staticmethod
def test_get_codes_multiline_string() -> None:
app = codegen.get_app(get_filepath("test_get_codes_multiline_string"))
assert app is not None
- assert list(app._names()) == ["one"]
- assert list(app._codes()) == ['c = """\n a, b"""; ']
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == ['c = """\n a, b"""; ']
@staticmethod
def test_get_codes_comment_after_sig() -> None:
app = codegen.get_app(get_filepath("test_get_codes_comment_after_sig"))
assert app is not None
- assert list(app._names()) == ["one"]
- assert list(app._codes()) == ['print("hi")']
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == ['print("hi")']
@staticmethod
def test_get_codes_empty() -> None:
app = codegen.get_app(get_filepath("test_get_codes_empty"))
assert app is not None
- assert list(app._names()) == ["one", "two"]
- assert [c.strip() for c in app._codes()] == ["", ""]
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one", "two"]
+ assert [c.strip() for c in cell_manager.codes()] == ["", ""]
@staticmethod
def test_get_codes_syntax_error() -> None:
@@ -235,8 +256,9 @@ class TestGetCodes:
get_filepath("test_generate_filecontents_with_syntax_error")
)
assert app is not None
- assert list(app._names()) == ["one", "two", "__", "__"]
- assert list(app._codes()) == [
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one", "two", "__", "__"]
+ assert list(cell_manager.codes()) == [
"import numpy as np",
"_ error",
"'all good'",
diff --git a/tests/_cli/test_ipynb_to_marimo.py b/tests/_cli/test_ipynb_to_marimo.py
index f65892bfc0..2f002aaf5a 100644
--- a/tests/_cli/test_ipynb_to_marimo.py
+++ b/tests/_cli/test_ipynb_to_marimo.py
@@ -29,7 +29,8 @@ def get_codes(ipynb_name: str) -> tuple[Sequence[str], Sequence[str]]:
f.seek(0)
app = codegen.get_app(f.name)
assert app is not None
- return list(app._codes()), list(app._names())
+ cell_manager = app._cell_manager
+ return list(cell_manager.codes()), list(cell_manager.names())
finally:
os.remove(tempfile_name)