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.

improvement: autofix some multiple definition errors in marimo convert (#1609)

Akshay Agrawal3dd7d5e26e28
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 306ef4b61b..394b5e3e5d 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -215,17 +215,18 @@ class App:
raise CycleError(
"This app can't be run because it has cycles."
)
- name = self._graph.get_multiply_defined()
- if name is not None:
+ multiply_defined_names = self._graph.get_multiply_defined()
+ if multiply_defined_names:
raise MultipleDefinitionError(
"This app can't be run because it has multiple "
- f"definitions of the name {name}"
+ f"definitions of the name {multiply_defined_names[0]}"
)
- ref = self._graph.get_deleted_nonlocal_ref()
- if ref is not None:
+ deleted_nonlocal_refs = self._graph.get_deleted_nonlocal_ref()
+ if deleted_nonlocal_refs:
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})"
+ "deletes one of its refs (the ref's name is "
+ f"{deleted_nonlocal_refs[0]})"
)
self._execution_order = dataflow.topological_sort(
self._graph, list(self._cell_manager.valid_cell_ids())
diff --git a/marimo/_ast/transformers.py b/marimo/_ast/transformers.py
new file mode 100644
index 0000000000..73bf2f57af
--- /dev/null
+++ b/marimo/_ast/transformers.py
@@ -0,0 +1,18 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+
+
+class NameTransformer(ast.NodeTransformer):
+ def __init__(self, name_substitutions: dict[str, str]) -> None:
+ self._name_substitutions = name_substitutions
+ super().__init__()
+
+ def visit_Name(self, node: ast.Name) -> ast.Name:
+ if node.id in self._name_substitutions:
+ return ast.Name(
+ **{**node.__dict__, "id": self._name_substitutions[node.id]}
+ )
+ else:
+ return node
diff --git a/marimo/_cli/convert/ipynb.py b/marimo/_cli/convert/ipynb.py
index 2987664e82..0a8256c756 100644
--- a/marimo/_cli/convert/ipynb.py
+++ b/marimo/_cli/convert/ipynb.py
@@ -1,13 +1,54 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import ast
import json
+import sys
+from marimo._ast.compiler import compile_cell
+from marimo._ast.transformers import NameTransformer
from marimo._cli.convert.utils import (
generate_from_sources,
load_external_file,
markdown_to_marimo,
)
+from marimo._runtime.dataflow import DirectedGraph
+
+
+def fixup_multiple_definitions(sources: list[str]) -> list[str]:
+ if sys.version_info < (3, 9):
+ # ast.unparse not available in Python 3.8
+ return sources
+
+ try:
+ cells = [
+ compile_cell(source, cell_id=str(i))
+ for i, source in enumerate(sources)
+ ]
+ except SyntaxError:
+ return sources
+
+ graph = DirectedGraph()
+ for cell in cells:
+ graph.register_cell(cell_id=cell.cell_id, cell=cell)
+
+ multiply_defined_names = graph.get_multiply_defined()
+ if not multiply_defined_names:
+ return sources
+
+ name_transformations = {}
+ for name in multiply_defined_names:
+ if not graph.get_referring_cells(name):
+ name_transformations[name] = (
+ "_" + name if not name.startswith("_") else name
+ )
+
+ return [
+ ast.unparse(
+ NameTransformer(name_transformations).visit(ast.parse(source))
+ )
+ for source in sources
+ ]
def convert_from_ipynb(raw_notebook: str) -> str:
@@ -28,7 +69,7 @@ def convert_from_ipynb(raw_notebook: str) -> str:
if has_markdown:
sources.append("import marimo as mo")
- return generate_from_sources(sources)
+ return generate_from_sources(fixup_multiple_definitions(sources))
def convert_from_ipynb_file(file_path: str) -> str:
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index b596829243..8f72bddfe1 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import threading
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple
+from typing import TYPE_CHECKING, Any, Callable, List, Tuple
from marimo import _loggers
from marimo._ast.cell import (
@@ -288,22 +288,20 @@ 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[Name]:
+ def get_multiply_defined(self) -> list[Name]:
+ names = []
for name, definers in self.definitions.items():
if len(definers) > 1:
- return name
- return None
+ names.append(name)
+ return names
- def get_deleted_nonlocal_ref(self) -> Optional[Name]:
+ def get_deleted_nonlocal_ref(self) -> list[Name]:
+ names = []
for cell in self.cells.values():
for ref in cell.deleted_refs:
if ref in self.definitions:
- return ref
- return None
+ names.append(ref)
+ return names
def descendants(self, cell_id: CellId_t) -> set[CellId_t]:
return transitive_closure(self, set([cell_id]), inclusive=False)
diff --git a/marimo/_smoke_tests/bugs/1602.py b/marimo/_smoke_tests/bugs/1602.py
index ac614c7123..bd344abb15 100644
--- a/marimo/_smoke_tests/bugs/1602.py
+++ b/marimo/_smoke_tests/bugs/1602.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
import marimo
__generated_with = "0.6.17"
diff --git a/marimo/_smoke_tests/no_mutating.py b/marimo/_smoke_tests/no_mutating.py
index 2037873efd..a378005aed 100644
--- a/marimo/_smoke_tests/no_mutating.py
+++ b/marimo/_smoke_tests/no_mutating.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
import marimo
__generated_with = "0.6.17"
diff --git a/tests/_cli/ipynb_data/multiple_defs.ipynb.txt b/tests/_cli/ipynb_data/multiple_defs.ipynb.txt
new file mode 100644
index 0000000000..e137f5e93c
--- /dev/null
+++ b/tests/_cli/ipynb_data/multiple_defs.ipynb.txt
@@ -0,0 +1,153 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "3e9ac90b-0be8-455c-9e0c-b564bc8d5ce0",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "0"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "x = 0\n",
+ "x"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "bcff4bca-c4d3-4d7a-8ed1-b9922c6251d1",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "x = 1\n",
+ "x"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "c11df909-8fb0-48e1-a238-4310398b7f03",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "y = 0"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "6c69caf3-3bb1-4f4b-9b2f-2f0269494ab2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "y = 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "b843eabd-99d5-4df3-bff3-c2ceb364f4b6",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "y"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "560e0fd7-7369-4560-ab07-66419a60d908",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "0\n",
+ "1\n",
+ "2\n"
+ ]
+ }
+ ],
+ "source": [
+ "for i in range(3):\n",
+ " print(i)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "c31791e5-151b-4a1b-9f1e-c5d8c05319bd",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "0\n",
+ "1\n",
+ "2\n",
+ "3\n"
+ ]
+ }
+ ],
+ "source": [
+ "for i in range(4):\n",
+ " print(i)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.9.19"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/tests/_cli/test_ipynb_to_marimo.py b/tests/_cli/test_ipynb_to_marimo.py
index 64f544b2f7..c6857a1267 100644
--- a/tests/_cli/test_ipynb_to_marimo.py
+++ b/tests/_cli/test_ipynb_to_marimo.py
@@ -2,10 +2,13 @@
from __future__ import annotations
import os
+import sys
import tempfile
import textwrap
from typing import TYPE_CHECKING
+import pytest
+
from marimo._ast import codegen
from marimo._cli.convert.ipynb import convert_from_ipynb_file
@@ -101,3 +104,36 @@ def test_unparsable() -> None:
assert codes[0] == "!echo hello, world\n\nx = 0"
assert codes[1] == "x"
assert names == ["__", "__"]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_multiple_defs() -> None:
+ codes, _ = get_codes("multiple_defs")
+
+ assert len(codes) == 7
+ assert codes[0] == "_x = 0\n_x"
+ assert codes[1] == "_x = 1\n_x"
+ assert codes[2] == "y = 0"
+ assert codes[3] == "y = 1"
+ assert codes[4] == "y"
+ assert (
+ codes[5]
+ == textwrap.dedent(
+ """
+ for _i in range(3):
+ print(_i)
+ """
+ ).strip()
+ )
+ assert (
+ codes[6]
+ == textwrap.dedent(
+ """
+ for _i in range(4):
+ print(_i)
+
+ """
+ ).strip()
+ )