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: improve convert with smart renaming, magics, dedupe imports, and more (#2422)

Myles Scolnick59338becda7c
diff --git a/marimo/_ast/transformers.py b/marimo/_ast/transformers.py
index 73bf2f57af..fc5452adb6 100644
--- a/marimo/_ast/transformers.py
+++ b/marimo/_ast/transformers.py
@@ -2,17 +2,63 @@
from __future__ import annotations
import ast
+from typing import Any
class NameTransformer(ast.NodeTransformer):
def __init__(self, name_substitutions: dict[str, str]) -> None:
self._name_substitutions = name_substitutions
+ self.made_changes = False
super().__init__()
def visit_Name(self, node: ast.Name) -> ast.Name:
if node.id in self._name_substitutions:
+ self.made_changes = True
return ast.Name(
**{**node.__dict__, "id": self._name_substitutions[node.id]}
)
- else:
- return node
+ return node
+
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
+ if node.name in self._name_substitutions:
+ self.made_changes = True
+ return ast.FunctionDef(
+ **{
+ **node.__dict__,
+ "name": self._name_substitutions[node.name],
+ }
+ )
+ return node
+
+ def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
+ if node.name in self._name_substitutions:
+ self.made_changes = True
+ return ast.ClassDef(
+ **{
+ **node.__dict__,
+ "name": self._name_substitutions[node.name],
+ }
+ )
+ return node
+
+ def visit_Assign(self, node: ast.Assign) -> ast.Assign:
+ new_targets: list[Any] = []
+ for target in node.targets:
+ if (
+ isinstance(target, ast.Name)
+ and target.id in self._name_substitutions
+ ):
+ self.made_changes = True
+ new_targets.append(
+ ast.Name(
+ id=self._name_substitutions[target.id], ctx=ast.Store()
+ )
+ )
+ else:
+ new_targets.append(target)
+ return ast.Assign(
+ **{
+ **node.__dict__,
+ "targets": new_targets,
+ }
+ )
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index eb307176c8..84d7cc28ff 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -6,7 +6,7 @@ import itertools
import sys
from collections import defaultdict
from dataclasses import dataclass, field
-from typing import Literal, Optional
+from typing import Callable, Literal, Optional, Union
from uuid import uuid4
from marimo import _loggers
@@ -114,9 +114,29 @@ class RefData:
parent_blocks: list[Block]
+NamedNode = Union[
+ ast.Name,
+ ast.ClassDef,
+ ast.FunctionDef,
+ ast.AsyncFunctionDef,
+ ast.arg,
+ ast.Global,
+ "ast.MatchAs", # type: ignore
+ "ast.MatchMapping", # type: ignore
+ "ast.MatchStar", # type: ignore
+ "ast.TypeVar", # type: ignore
+ "ast.ParamSpec", # type: ignore
+ "ast.TypeVarTuple", # type: ignore
+]
+
+
class ScopedVisitor(ast.NodeVisitor):
def __init__(
- self, mangle_prefix: Optional[str] = None, ignore_local: bool = False
+ self,
+ mangle_prefix: Optional[str] = None,
+ ignore_local: bool = False,
+ on_def: Callable[[NamedNode, str, list[Block]], None] | None = None,
+ on_ref: Callable[[NamedNode], None] | None = None,
) -> None:
self.block_stack: list[Block] = [Block()]
# Names to be loaded into a variable required_refs
@@ -124,6 +144,10 @@ class ScopedVisitor(ast.NodeVisitor):
self.obscured_scope_stack: list[ObscuredScope] = []
# Mapping from referenced names to their metadata
self._refs: dict[Name, RefData] = {}
+ # Function (node, name, block stack) -> None
+ self._on_def = on_def if on_def is not None else lambda *_: None
+ # Function (node) -> None
+ self._on_ref = on_ref if on_ref is not None else lambda *_: None
# Unique prefix used to mangle cell-local variable names
self.id = (
str(uuid4()).replace("-", "_")
@@ -196,13 +220,17 @@ class ScopedVisitor(ast.NodeVisitor):
"""Check if `identifier` is defined in any block."""
return any(block.is_defined(identifier) for block in self.block_stack)
- def _add_ref(self, name: Name, deleted: bool) -> None:
+ def _add_ref(
+ self, node: NamedNode | None, name: Name, deleted: bool
+ ) -> None:
"""Register a referenced name."""
self._refs[name] = RefData(
deleted=deleted,
parent_blocks=self.block_stack[:-1],
)
self.ref_stack[-1].add(name)
+ if node is not None:
+ self._on_ref(node)
def _remove_ref(self, name: Name) -> None:
"""Remove a referenced name."""
@@ -231,7 +259,9 @@ class ScopedVisitor(ast.NodeVisitor):
# `name` was used as a capture, not a reference
self._remove_ref(name)
- def _define(self, name: Name, variable_data: VariableData) -> None:
+ def _define(
+ self, node: NamedNode | None, name: Name, variable_data: VariableData
+ ) -> None:
"""Define a name in the current block.
Names created with the global keyword are added to the top-level
@@ -239,6 +269,8 @@ class ScopedVisitor(ast.NodeVisitor):
"""
block_idx = 0 if name in self.block_stack[-1].global_names else -1
self._define_in_block(name, variable_data, block_idx=block_idx)
+ if node is not None:
+ self._on_def(node, name, self.block_stack)
def _push_block(self, is_comprehension: bool) -> None:
"""Push a block onto the block stack."""
@@ -256,7 +288,7 @@ class ScopedVisitor(ast.NodeVisitor):
"""Pop scope from the stack."""
self.obscured_scope_stack.pop()
- def generic_visit(self, node: ast.AST) -> None:
+ def generic_visit(self, node: ast.AST) -> ast.AST:
"""Visits the children of node and manages the block stack.
Note: visit calls visit_ClassName, or generic_visit() if the former
@@ -331,6 +363,7 @@ class ScopedVisitor(ast.NodeVisitor):
else:
# Other nodes that don't introduce a new scope
super().generic_visit(node)
+ return node
def _visit_and_get_refs(self, node: ast.AST) -> set[Name]:
"""Create a ref scope for the variable to be declared (e.g. function,
@@ -351,31 +384,39 @@ class ScopedVisitor(ast.NodeVisitor):
return refs
# ClassDef and FunctionDef nodes don't have ast.Name nodes as children
- def visit_ClassDef(self, node: ast.ClassDef) -> None:
+ def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
node.name = self._if_local_then_mangle(node.name)
refs = self._visit_and_get_refs(node)
self._define(
+ node,
node.name,
VariableData(kind="class", required_refs=refs),
)
+ return node
- def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
+ def visit_AsyncFunctionDef(
+ self, node: ast.AsyncFunctionDef
+ ) -> ast.AsyncFunctionDef:
node.name = self._if_local_then_mangle(node.name)
refs = self._visit_and_get_refs(node)
self._define(
+ node,
node.name,
VariableData(kind="function", required_refs=refs),
)
+ return node
- def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
node.name = self._if_local_then_mangle(node.name)
refs = self._visit_and_get_refs(node)
self._define(
+ node,
node.name,
VariableData(kind="function", required_refs=refs),
)
+ return node
- def visit_Call(self, node: ast.Call) -> None:
+ def visit_Call(self, node: ast.Call) -> ast.Call:
# If the call name is sql and has one argument, and the argument is
# a string literal, then it's likely to be a SQL query.
# It must also come from the `mo` or `duckdb` module.
@@ -427,14 +468,14 @@ class ScopedVisitor(ast.NodeVisitor):
# or duckdb failed for an unknown reason; don't
# break marimo.
self.generic_visit(node)
- return
+ return node
except BaseException as e:
# We catch base exceptions because we don't want to
# fail due to bugs in duckdb -- users code should
# be saveable no matter what
LOGGER.warning("Unexpected duckdb error %s", e)
self.generic_visit(node)
- return
+ return node
for statement in statements:
# Parse the refs and defs of each statement
@@ -456,7 +497,7 @@ class ScopedVisitor(ast.NodeVisitor):
# Name (table, db) may be a URL or something else that
# isn't a Python variable
if name.isidentifier():
- self._add_ref(name, deleted=False)
+ self._add_ref(None, name, deleted=False)
# Add all tables/dbs created in the query to the defs
try:
@@ -470,28 +511,31 @@ class ScopedVisitor(ast.NodeVisitor):
continue
for _table in sql_defs.tables:
- self._define(_table, VariableData("table"))
+ self._define(None, _table, VariableData("table"))
for _view in sql_defs.views:
- self._define(_view, VariableData("view"))
+ self._define(None, _view, VariableData("view"))
for _schema in sql_defs.schemas:
- self._define(_schema, VariableData("schema"))
+ self._define(None, _schema, VariableData("schema"))
# Visit arguments, keyword args, etc.
self.generic_visit(node)
+ return node
- def visit_Lambda(self, node: ast.Lambda) -> None:
+ def visit_Lambda(self, node: ast.Lambda) -> ast.Lambda:
# Inject the dummy name `_lambda` into ref scope to denote there's a
# callable that might require additional refs.
self.ref_stack[-1].add("_lambda")
self.generic_visit(node)
+ return node
- def visit_arg(self, node: ast.arg) -> None:
+ def visit_arg(self, node: ast.arg) -> ast.arg:
node.arg = self._if_local_then_mangle(node.arg)
- self._define(node.arg, VariableData(kind="variable"))
+ self._define(node, node.arg, VariableData(kind="variable"))
if node.annotation is not None:
self.visit(node.annotation)
+ return node
- def visit_arguments(self, node: ast.arguments) -> None:
+ def visit_arguments(self, node: ast.arguments) -> ast.arguments:
# process potential refs before defs, to handle patterns like
#
# def f(x=x):
@@ -513,8 +557,9 @@ class ScopedVisitor(ast.NodeVisitor):
self.visit(node.vararg)
if node.kwarg is not None:
self.visit(node.kwarg)
+ return node
- def visit_Assign(self, node: ast.Assign) -> None:
+ def visit_Assign(self, node: ast.Assign) -> ast.Assign:
# Visit the value first, to handle cases like
#
# class A:
@@ -527,8 +572,9 @@ class ScopedVisitor(ast.NodeVisitor):
self.visit(target)
refs = self.ref_stack.pop()
self.ref_stack[-1].update(refs)
+ return node
- def visit_AugAssign(self, node: ast.AugAssign) -> None:
+ def visit_AugAssign(self, node: ast.AugAssign) -> ast.AugAssign:
# Augmented assign (has op)
# e.g., x += 1
self.ref_stack.append(set())
@@ -536,8 +582,9 @@ class ScopedVisitor(ast.NodeVisitor):
self.visit(node.target)
refs = self.ref_stack.pop()
self.ref_stack[-1].update(refs)
+ return node
- def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
+ def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign:
# Annotated assign
# e.g., x: int = 0
self.ref_stack.append(set())
@@ -547,8 +594,23 @@ class ScopedVisitor(ast.NodeVisitor):
self.visit(node.target)
refs = self.ref_stack.pop()
self.ref_stack[-1].update(refs)
+ return node
+
+ def visit_comprehension(
+ self, node: ast.comprehension
+ ) -> ast.comprehension:
+ # process potential refs before defs, to handle patterns like
+ #
+ # [ ... for x in x]
+ #
+ # In defining scoping, Python parses iter first, then target, then ifs
+ self.visit(node.iter)
+ self.visit(node.target)
+ for _if in node.ifs:
+ self.visit(_if)
+ return node
- def visit_NamedExpr(self, node: ast.NamedExpr) -> None:
+ def visit_NamedExpr(self, node: ast.NamedExpr) -> ast.NamedExpr:
self.visit(node.value)
if self.block_stack[-1].is_comprehension and isinstance(
node.target, ast.Name
@@ -571,8 +633,9 @@ class ScopedVisitor(ast.NodeVisitor):
break
else:
self.generic_visit(node)
+ return node
- def visit_Name(self, node: ast.Name) -> None:
+ def visit_Name(self, node: ast.Name) -> ast.Name:
# NB: AugAssign has a Store ctx; this means that mutating a var
# will create a def, which we can catch as an error later if
# that var was defined by another cell
@@ -594,11 +657,12 @@ class ScopedVisitor(ast.NodeVisitor):
for scope in self.obscured_scope_stack:
if node.id == scope.obscured:
self.generic_visit(node)
- return
+ return node
if isinstance(node.ctx, ast.Store):
node.id = self._if_local_then_mangle(node.id)
self._define(
+ node,
node.id,
VariableData(
kind="variable", required_refs=self.ref_stack[-1]
@@ -609,13 +673,13 @@ class ScopedVisitor(ast.NodeVisitor):
and not self._is_defined(node.id)
and not self.is_local(node.id)
):
- self._add_ref(node.id, deleted=False)
+ self._add_ref(node, node.id, deleted=False)
elif (
isinstance(node.ctx, ast.Del)
and not self._is_defined(node.id)
and not self.is_local(node.id)
):
- self._add_ref(node.id, deleted=True)
+ self._add_ref(node, node.id, deleted=True)
elif self.is_local(node.id):
mangled_name = self._if_local_then_mangle(
node.id, ignore_scope=True
@@ -627,6 +691,11 @@ class ScopedVisitor(ast.NodeVisitor):
node.id = mangled_name
elif block.is_defined(node.id):
break
+ else:
+ # Not a reference; ast.Load, ast.Del on a variable that's already
+ # defined; invoke the callback
+ if node is not None:
+ self._on_def(node, node.id, self.block_stack)
# Handle refs on the block scope level, or capture cell level
# references.
@@ -642,20 +711,23 @@ class ScopedVisitor(ast.NodeVisitor):
self.ref_stack[-1].add(node.id)
self.generic_visit(node)
+ return node
- def visit_Global(self, node: ast.Global) -> None:
+ def visit_Global(self, node: ast.Global) -> ast.Global:
node.names = [
self._if_local_then_mangle(name, ignore_scope=True)
for name in node.names
]
for name in node.names:
self.block_stack[-1].global_names.add(name)
- self._add_ref(name, deleted=False)
+ self._add_ref(node, name, deleted=False)
+ return node
- def visit_Import(self, node: ast.Import) -> None:
+ def visit_Import(self, node: ast.Import) -> ast.Import:
for alias_node in node.names:
variable_name = self._get_alias_name(alias_node)
self._define(
+ None,
variable_name,
VariableData(
kind="import",
@@ -666,8 +738,9 @@ class ScopedVisitor(ast.NodeVisitor):
),
),
)
+ return node
- def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.ImportFrom:
module = node.module if node.module is not None else ""
# we don't recurse into the alias nodes, since we define the
# aliases here
@@ -675,6 +748,7 @@ class ScopedVisitor(ast.NodeVisitor):
variable_name = self._get_alias_name(alias_node)
original_name = alias_node.name
self._define(
+ None,
variable_name,
VariableData(
kind="import",
@@ -686,6 +760,7 @@ class ScopedVisitor(ast.NodeVisitor):
),
),
)
+ return node
if sys.version_info >= (3, 10):
# Match statements were introduced in Python 3.10
@@ -695,21 +770,26 @@ class ScopedVisitor(ast.NodeVisitor):
# we don't know the value of the match subject), even though only a
# subset of the names will be bound at runtime. For this reason, in
# marimo, match statements should really only be used in local scopes.
- def visit_MatchAs(self, node: ast.MatchAs) -> None:
+ def visit_MatchAs(self, node: ast.MatchAs) -> ast.MatchAs:
if node.name is not None:
node.name = self._if_local_then_mangle(node.name)
self._define(
+ node,
node.name,
VariableData(kind="variable"),
)
if node.pattern is not None:
# pattern may contain additional MatchAs statements in it
self.visit(node.pattern)
+ return node
- def visit_MatchMapping(self, node: ast.MatchMapping) -> None:
+ def visit_MatchMapping(
+ self, node: ast.MatchMapping
+ ) -> ast.MatchMapping:
if node.rest is not None:
node.rest = self._if_local_then_mangle(node.rest)
self._define(
+ node,
node.rest,
VariableData(kind="variable"),
)
@@ -717,20 +797,24 @@ class ScopedVisitor(ast.NodeVisitor):
self.visit(key)
for pattern in node.patterns:
self.visit(pattern)
+ return node
- def visit_MatchStar(self, node: ast.MatchStar) -> None:
+ def visit_MatchStar(self, node: ast.MatchStar) -> ast.MatchStar:
if node.name is not None:
node.name = self._if_local_then_mangle(node.name)
self._define(
+ node,
node.name,
VariableData(kind="variable"),
)
+ return node
if sys.version_info >= (3, 12):
- def visit_TypeVar(self, node: ast.TypeVar) -> None:
+ def visit_TypeVar(self, node: ast.TypeVar) -> ast.TypeVar:
# node.name is a str, not an ast.Name node
self._define(
+ node,
node.name,
VariableData(
kind="variable", required_refs=self.ref_stack[-1]
@@ -741,21 +825,28 @@ class ScopedVisitor(ast.NodeVisitor):
self.visit(name)
elif node.bound is not None:
self.visit(node.bound)
+ return node
- def visit_ParamSpec(self, node: ast.ParamSpec) -> None:
+ def visit_ParamSpec(self, node: ast.ParamSpec) -> ast.ParamSpec:
# node.name is a str, not an ast.Name node
self._define(
+ node,
node.name,
VariableData(
kind="variable", required_refs=self.ref_stack[-1]
),
)
+ return node
- def visit_TypeVarTuple(self, node: ast.TypeVarTuple) -> None:
+ def visit_TypeVarTuple(
+ self, node: ast.TypeVarTuple
+ ) -> ast.TypeVarTuple:
# node.name is a str, not an ast.Name node
self._define(
+ node,
node.name,
VariableData(
kind="variable", required_refs=self.ref_stack[-1]
),
)
+ return node
diff --git a/marimo/_cli/convert/commands.py b/marimo/_cli/convert/commands.py
index 7e9b08368a..9b412d4f00 100644
--- a/marimo/_cli/convert/commands.py
+++ b/marimo/_cli/convert/commands.py
@@ -5,10 +5,10 @@ from pathlib import Path
import click
-from marimo._cli.convert.ipynb import convert_from_ipynb
from marimo._cli.convert.markdown import convert_from_md
from marimo._cli.convert.utils import load_external_file
from marimo._cli.print import echo
+from marimo._convert.ipynb import convert_from_ipynb
@click.argument("filename", required=True)
diff --git a/marimo/_cli/convert/ipynb.py b/marimo/_cli/convert/ipynb.py
index bc9702d5cf..eab50fbc05 100644
--- a/marimo/_cli/convert/ipynb.py
+++ b/marimo/_cli/convert/ipynb.py
@@ -1,75 +1,10 @@
# 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, language="python"):
- 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:
- notebook = json.loads(raw_notebook)
- sources = []
- has_markdown = False
- for cell in notebook["cells"]:
- source = (
- cell["source"]
- if isinstance(cell["source"], str)
- else "".join(cell["source"])
- )
- if cell["cell_type"] == "markdown":
- has_markdown = True
- source = markdown_to_marimo(source)
- sources.append(source)
-
- if has_markdown:
- sources.append("import marimo as mo")
-
- return generate_from_sources(fixup_multiple_definitions(sources))
+from marimo._convert.ipynb import convert_from_ipynb
def convert_from_ipynb_file(file_path: str) -> str:
diff --git a/marimo/_cli/convert/markdown.py b/marimo/_cli/convert/markdown.py
index 194920ba72..29741e96df 100644
--- a/marimo/_cli/convert/markdown.py
+++ b/marimo/_cli/convert/markdown.py
@@ -26,7 +26,7 @@ from marimo._ast import codegen
from marimo._ast.app import App, InternalApp, _AppConfig
from marimo._ast.cell import Cell, CellConfig
from marimo._ast.compiler import compile_cell
-from marimo._cli.convert.utils import markdown_to_marimo
+from marimo._convert.utils import markdown_to_marimo
MARIMO_MD = "marimo-md"
MARIMO_CODE = "marimo-code"
diff --git a/marimo/_cli/convert/utils.py b/marimo/_cli/convert/utils.py
index 4e8bfff168..9ca802f597 100644
--- a/marimo/_cli/convert/utils.py
+++ b/marimo/_cli/convert/utils.py
@@ -2,11 +2,7 @@
from __future__ import annotations
import urllib.request
-from typing import Optional
-from marimo._ast import codegen
-from marimo._ast.app import _AppConfig
-from marimo._ast.cell import CellConfig
from marimo._cli.file_path import get_github_src_url, is_github_src
@@ -23,28 +19,3 @@ def load_external_file(file_path: str, ext: str) -> str:
notebook = f.read()
return notebook
-
-
-def markdown_to_marimo(source: str) -> str:
- source = source.replace('"""', '\\"\\"\\"')
- return "\n".join(
- [
- "mo.md(",
- # r-string: a backslash is just a backslash!
- codegen.indent_text('r"""'),
- codegen.indent_text(source),
- codegen.indent_text('"""'),
- ")",
- ]
- )
-
-
-def generate_from_sources(
- sources: list[str], config: Optional[_AppConfig] = None
-) -> str:
- return codegen.generate_filecontents(
- sources,
- ["__" for _ in sources],
- [CellConfig() for _ in range(len(sources))],
- config=config,
- )
diff --git a/marimo/_convert/ipynb.py b/marimo/_convert/ipynb.py
new file mode 100644
index 0000000000..48da78fc02
--- /dev/null
+++ b/marimo/_convert/ipynb.py
@@ -0,0 +1,653 @@
+# Copyright 2024 marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+import json
+import sys
+from collections import defaultdict
+from typing import Any, Callable, Dict, List
+
+from marimo._ast.compiler import compile_cell
+from marimo._ast.transformers import NameTransformer
+from marimo._ast.visitor import Block, NamedNode, ScopedVisitor
+from marimo._convert.utils import generate_from_sources, markdown_to_marimo
+from marimo._runtime.dataflow import DirectedGraph
+from marimo._utils.variables import is_local
+
+# Define a type for our transform functions
+Transform = Callable[[List[str]], List[str]]
+
+
+def transform_fixup_multiple_definitions(sources: List[str]) -> List[str]:
+ """
+ Fixup multiple definitions of the same name in different cells,
+ by making the name private (underscore) to each cell.
+
+ This only takes effect if the declaration and reference are in
+ the same cell.
+ """
+ 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: Dict[str, str] = {}
+ for name in multiply_defined_names:
+ if not graph.get_referring_cells(name, language="python"):
+ name_transformations[name] = (
+ "_" + name if not name.startswith("_") else name
+ )
+
+ def transform(source: str) -> str:
+ try:
+ tree = ast.parse(source)
+ visitor = NameTransformer(name_transformations)
+ transformed_tree = visitor.visit(tree)
+ # Don't unparse if no changes were made
+ # otherwise we lose comments and formatting
+ if visitor.made_changes:
+ return ast.unparse(transformed_tree)
+ return source
+ except SyntaxError:
+ return source
+
+ return [transform(source) for source in sources]
+
+
+def transform_add_marimo_import(sources: List[str]) -> List[str]:
+ """
+ Add an import statement for marimo if any cell uses
+ the `mo.md` or `mo.sql` functions.
+ """
+
+ def contains_mo(cell: str) -> bool:
+ return cell.startswith("mo.md(") or "mo.sql(" in cell
+
+ if any(contains_mo(cell) for cell in sources):
+ return sources + ["import marimo as mo"]
+
+ return sources
+
+
+def transform_magic_commands(sources: List[str]) -> List[str]:
+ """
+ Transform Jupyter magic commands to their marimo equivalents
+ or comment them out.
+ """
+
+ def magic_sql(source: str, command: str) -> str:
+ """
+ Transform SQL magic into marimo SQL functions.
+
+ %%sql
+ SELECT * FROM table
+
+ to
+
+ _df = mo.sql('''
+ SELECT * FROM table
+ ''')
+ """
+ del command
+ source = source.strip()
+ return f'_df = mo.sql("""\n{source}\n""")'
+
+ def magic_remove(source: str, command: str) -> str:
+ """
+ Remove the magic but keep the source code.
+ """
+ double = command.startswith("%%")
+ if not double:
+ return "\n".join(
+ [
+ "# magic command not supported in marimo; please file an issue to add support", # noqa: E501
+ f"# {command + ' ' + source}",
+ ]
+ )
+
+ result = [
+ "# magic command not supported in marimo; please file an issue to add support", # noqa: E501
+ f"# {command}",
+ ]
+ if source:
+ result.append(source)
+ return "\n".join(result)
+
+ def magic_already_supported(source: str, command: str) -> str:
+ """
+ Remove the magic but keep the source code.
+ """
+ double = command.startswith("%%")
+ if not double:
+ return f"# {(command + ' ' + source)!r} command supported automatically in marimo" # noqa: E501
+
+ result = [
+ f"# {command!r} command supported automatically in marimo",
+ ]
+ if source:
+ result.append(source)
+ return "\n".join(result)
+
+ def magic_mkdir(source: str, command: str) -> str:
+ """
+ Transform mkdir magic into marimo mkdir functions.
+
+ %mkdir path/to/directory
+
+ to
+
+ import os
+ os.makedirs('path/to/directory', exist_ok=True)
+ """
+ del command
+ return f"import os\nos.makedirs({source!r}, exist_ok"
+
+ def magic_cd(source: str, command: str) -> str:
+ """
+ Transform cd magic into marimo cd functions.
+
+ %cd path/to/directory
+
+ to
+
+ import os
+ os.chdir('path/to/directory')
+ """
+ del command
+ return f"import os\nos.chdir({source!r})"
+
+ def magic_html(source: str, command: str) -> str:
+ """
+ Transform html magic into marimo html functions.
+
+ %html <h1>Heading</h1>
+
+ to
+
+ mo.Html('<h1>Heading</h1>')
+ """
+ del command
+ return f"mo.Html({source!r})"
+
+ def magic_ls(source: str, command: str) -> str:
+ """
+ Transform ls magic into marimo ls functions.
+
+ %ls
+
+ to
+
+ import os
+ os.listdir()
+ """
+ del command, source
+ return "import os\nos.listdir()"
+
+ def magic_bash(source: str, command: str) -> str:
+ """
+ Transform bash magic into marimo bash functions.
+
+ %bash echo "Hello, world!"
+
+ to
+
+ mo.bash('echo "Hello, world!"')
+ """
+ del command
+ return f"import subprocess\nsubprocess.run({source!r}, shell=True)"
+
+ def magic_env(source: str, command: str) -> str:
+ """
+ Transform env magic into marimo env functions
+
+ %env VAR_NAME=VALUE
+
+ to
+
+ import os
+ os.environ['VAR_NAME'] = 'VALUE'
+ """
+
+ del command
+ _key, value = source.split("=", 1)
+ return f"import os\nos.environ[{_key!r}] = {value!r}"
+
+ def comment_out_code(source: str) -> str:
+ if source.strip():
+ return "\n".join(f"# {line}" for line in source.split("\n"))
+ return source
+
+ magics: Dict[str, Callable[[str, str], str]] = {
+ "sql": magic_sql,
+ "mkdir": magic_mkdir,
+ "cd": magic_cd,
+ "html": magic_html,
+ "bash": magic_bash,
+ "!": magic_bash,
+ "ls": magic_ls,
+ "load_ext": magic_already_supported,
+ "env": magic_env,
+ # Already supported in marimo, can just comment out the magic
+ "pip": magic_already_supported,
+ "matplotlib": magic_already_supported,
+ # Remove the magic, but keep the code as is
+ "timeit": magic_remove,
+ "time": magic_remove,
+ # Everything else is not supported and will be commented out
+ }
+
+ def transform(cell: str) -> str:
+ stripped = cell.strip()
+
+ # Multi-line magic
+ if stripped.startswith("%%"):
+ magic, rest = stripped.split("\n", 1)
+ magic_cmd = magic.strip().split(" ")[0].lstrip("%")
+ if magic_cmd in magics:
+ return magics[magic_cmd](rest, magic)
+ return magic_remove(comment_out_code(rest), magic)
+
+ # Single-line magic
+ elif stripped.startswith("%"):
+ magic, rest = stripped.split(" ", 1)
+ magic_cmd = magic.strip().lstrip("%")
+ if magic_cmd in magics:
+ return magics[magic_cmd](rest, magic)
+ return magic_remove(comment_out_code(rest), magic)
+
+ return cell
+
+ return [transform(cell) for cell in sources]
+
+
+def transform_exclamation_mark(sources: List[str]) -> List[str]:
+ """
+ Handle exclamation mark commands.
+ """
+
+ def transform(cell: str) -> str:
+ if "!pip" in cell:
+ cell = cell.replace(
+ "!pip",
+ "# (use marimo's built-in package management features instead) !pip", # noqa: E501
+ )
+ return cell
+
+ return [transform(cell) for cell in sources]
+
+
+class Renamer:
+ def __init__(self, cell_remappings: dict[int, dict[str, str]]) -> None:
+ self.cell_remappings = cell_remappings
+ self.made_changes = False
+
+ def _maybe_rename(self, cell: int, name: str, is_reference: bool) -> str:
+ latest_mapping: dict[str, str] = {}
+ until = cell if is_reference else cell + 1
+ for idx in range(until):
+ if (
+ idx in self.cell_remappings
+ and name in self.cell_remappings[idx]
+ ):
+ latest_mapping = self.cell_remappings[idx]
+ if name in latest_mapping:
+ return latest_mapping[name]
+ else:
+ return name
+
+ def rename_named_node(
+ self, cell: int, node: NamedNode, is_reference: bool
+ ) -> None:
+ name: str | None = None
+ new_name: str | None = None
+
+ if isinstance(node, ast.Name):
+ name = node.id
+ new_name = self._maybe_rename(cell, name, is_reference)
+ node.id = new_name
+ elif isinstance(
+ node,
+ (
+ ast.ClassDef,
+ ast.FunctionDef,
+ ast.AsyncFunctionDef,
+ ),
+ ):
+ name = node.name
+ new_name = self._maybe_rename(cell, name, is_reference)
+ node.name = new_name
+ if sys.version_info >= (3, 10):
+ if isinstance(node, (ast.MatchAs, ast.MatchStar)):
+ name = node.name
+ if name is not None:
+ new_name = self._maybe_rename(cell, name, is_reference)
+ node.name = new_name
+ elif isinstance(node, ast.MatchMapping):
+ name = node.rest
+ if name is not None:
+ new_name = self._maybe_rename(cell, name, is_reference)
+ node.rest = new_name
+ if sys.version_info >= (3, 12):
+ if isinstance(
+ node, (ast.TypeVar, ast.ParamSpec, ast.TypeVarTuple)
+ ):
+ name = node.name
+ new_name = self._maybe_rename(cell, name, is_reference)
+ node.name = new_name
+
+ if not self.made_changes:
+ self.made_changes = name != new_name
+
+
+def _transform_aug_assign(sources: List[str]) -> List[str]:
+ if sys.version_info < (3, 9):
+ # ast.unparse unavailable
+ return sources
+
+ new_sources = sources.copy()
+ for i, source in enumerate(sources):
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
+ continue
+
+ made_changes = False
+
+ class AugAssignTransformer(ast.NodeTransformer):
+ def visit_AugAssign(self, node: ast.AugAssign) -> ast.Assign:
+ nonlocal made_changes
+ made_changes = True
+ return ast.Assign(
+ targets=[node.target],
+ value=ast.BinOp(
+ left=node.target, op=node.op, right=node.value
+ ),
+ )
+
+ transformed = ast.fix_missing_locations(
+ AugAssignTransformer().visit(tree)
+ )
+ if made_changes:
+ new_sources[i] = ast.unparse(transformed)
+
+ return new_sources
+
+
+def transform_duplicate_definitions(sources: List[str]) -> List[str]:
+ """
+ Rename variables with duplicate definitions across multiple cells,
+ even when the variables are declared in one cell and used in another.
+
+ We assume the notebook was meant to be run top-to-bottom,
+ so references to the name will be renamed to the last definition.
+
+ If a new definition is derived from a previous definition,
+ then at the top of the cell, we add a new line that assigns
+ the new definition to the previous definition.
+
+ ```
+ # Cell 1
+ a = 1
+
+ # Cell 2
+ print(a)
+
+ # Cell 3
+ a = 2
+
+ # Cell 4
+ a = 3
+ print(a)
+ ```
+
+ Then we transform it to:
+
+ ```
+ # Cell 1
+ a = 1
+
+ # Cell 2
+ print(a)
+
+ # Cell 3
+ a_1 = a
+ a_1 = a_1 + 2
+
+ # Cell 4
+ a_2 = 3
+ print(a_2)
+ ```
+ """
+ if sys.version_info < (3, 9):
+ # ast.unparse not available in Python 3.8
+ return sources
+
+ # Find all definitions in the AST
+ def find_definitions(node: ast.AST) -> List[str]:
+ visitor = ScopedVisitor("", ignore_local=True)
+ visitor.visit(node)
+ # Remove local variables
+ defs = list(visitor.defs)
+ return [def_ for def_ in defs if not is_local(def_)]
+
+ # Collect all definitions for each cell
+ def get_definitions(sources: List[str]) -> Dict[str, List[int]]:
+ definitions: Dict[str, List[int]] = defaultdict(list)
+ for i, source in enumerate(sources):
+ try:
+ tree = ast.parse(source)
+ for name in find_definitions(tree):
+ definitions[name].append(i)
+ except SyntaxError:
+ continue
+ return definitions
+
+ # Collect all definitions that are duplicates
+ def get_duplicates(
+ definitions: Dict[str, List[int]],
+ ) -> Dict[str, List[int]]:
+ return {
+ name: cells
+ for name, cells in definitions.items()
+ if len(cells) > 1
+ }
+
+ # Create mappings for renaming duplicates
+ def create_name_mappings(
+ duplicates: Dict[str, List[int]], definitions: set[str]
+ ) -> Dict[int, Dict[str, str]]:
+ new_definitions: set[str] = set()
+ name_mappings: Dict[int, Dict[str, str]] = defaultdict(dict)
+ for name, cells in duplicates.items():
+ for i, cell in enumerate(cells[1:], start=1):
+ counter = i
+ new_name = f"{name}_{counter}"
+ while new_name in definitions or new_name in new_definitions:
+ # handles the user defining variables like df_1 in their
+ # original notebook
+ counter += 1
+ new_name = f"{name}_{counter}"
+ counter += 1
+ name_mappings[cell][name] = new_name
+ new_definitions.add(new_name)
+ return name_mappings
+
+ definitions = get_definitions(sources)
+ duplicates = get_duplicates(definitions)
+
+ if not duplicates:
+ return sources
+
+ sources = _transform_aug_assign(sources)
+
+ new_sources: List[str] = sources.copy()
+ name_mappings = create_name_mappings(duplicates, set(definitions.keys()))
+
+ for cell_idx, source in enumerate(sources):
+ renamer = Renamer(name_mappings)
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
+ continue
+
+ def on_def(
+ node: NamedNode,
+ name: str,
+ block_stack: list[Block],
+ cell_idx: int = cell_idx,
+ renamer: Renamer = renamer,
+ ) -> None:
+ block_idx = 0 if name in block_stack[-1].global_names else -1
+ if block_idx == 0:
+ # all top-level definitions are renamed
+ renamer.rename_named_node(cell_idx, node, is_reference=False)
+ elif block_stack[0].is_defined(name) and not any(
+ block.is_defined(name) for block in block_stack[1:]
+ ):
+ # all ast.LOADs of top-level definitions are defined
+ renamer.rename_named_node(cell_idx, node, is_reference=False)
+
+ def on_ref(
+ node: NamedNode,
+ cell_idx: int = cell_idx,
+ renamer: Renamer = renamer,
+ ) -> None:
+ renamer.rename_named_node(cell_idx, node, is_reference=True)
+
+ visitor = ScopedVisitor(
+ ignore_local=True, on_def=on_def, on_ref=on_ref
+ )
+ new_tree = visitor.visit(tree)
+
+ # Don't unparse if no changes were made
+ if not renamer.made_changes:
+ new_sources[cell_idx] = source
+ continue
+
+ new_source_lines: list[str] = []
+
+ # TODO
+ # Add assignments for dependencies
+ # for definition, dep in visitor.dependencies.items():
+ # new_source_lines.append(f"{definition} = {dep}")
+
+ # Add the modified source
+ new_source_lines.append(ast.unparse(new_tree))
+ new_sources[cell_idx] = "\n".join(new_source_lines)
+
+ return new_sources
+
+
+def transform_cell_metadata(
+ sources: List[str], metadata: List[Dict[str, Any]]
+) -> List[str]:
+ """
+ Handle cell metadata, such as tags or cell IDs.
+ """
+ transformed_sources: List[str] = []
+ for source, meta in zip(sources, metadata):
+ if "tags" in meta:
+ tags = meta["tags"]
+ if not tags:
+ transformed_sources.append(source)
+ continue
+ source = f"# Cell tags: {', '.join(tags)}\n{source}"
+ transformed_sources.append(source)
+ return transformed_sources
+
+
+def transform_remove_duplicate_imports(sources: List[str]) -> List[str]:
+ """
+ Remove duplicate imports appearing in any cell.
+ """
+ imports: set[str] = set()
+ new_sources: List[str] = []
+ for source in sources:
+ new_lines: List[str] = []
+ for line in source.split("\n"):
+ stripped_line = line.strip()
+ if stripped_line.startswith("import ") or stripped_line.startswith(
+ "from "
+ ):
+ if stripped_line not in imports:
+ imports.add(stripped_line)
+ new_lines.append(line)
+ else:
+ new_lines.append(line)
+
+ new_source = "\n".join(new_lines)
+ new_sources.append(new_source.strip())
+
+ return new_sources
+
+
+def transform_remove_empty_cells(sources: List[str]) -> List[str]:
+ """
+ Remove empty cells.
+ """
+ sources = [source for source in sources if source.strip()]
+ # Ensure there is at least one cell
+ if not sources:
+ return [""]
+ return sources
+
+
+def transform_strip_whitespace(sources: List[str]) -> List[str]:
+ """
+ Strip whitespace from the beginning and end of each cell.
+ """
+ return [source.strip() for source in sources]
+
+
+def _transform_sources(
+ sources: list[str], metadata: list[dict[str, Any]]
+) -> list[str]:
+ transforms: List[Transform] = [
+ transform_strip_whitespace,
+ transform_magic_commands,
+ transform_remove_duplicate_imports,
+ transform_fixup_multiple_definitions,
+ transform_duplicate_definitions,
+ lambda s: transform_cell_metadata(s, metadata),
+ transform_add_marimo_import, # may change cell count
+ transform_remove_empty_cells, # may change cell count
+ ]
+
+ # Run all the transforms
+ for transform in transforms:
+ sources = transform(sources)
+ return sources
+
+
+def convert_from_ipynb(raw_notebook: str) -> str:
+ notebook = json.loads(raw_notebook)
+ sources: List[str] = []
+ metadata: List[Dict[str, Any]] = []
+
+ for cell in notebook["cells"]:
+ source = (
+ "".join(cell["source"])
+ if isinstance(cell["source"], list)
+ else cell["source"]
+ )
+ if cell["cell_type"] == "markdown":
+ source = markdown_to_marimo(source)
+ sources.append(source)
+ metadata.append(cell.get("metadata", {}))
+
+ return generate_from_sources(_transform_sources(sources, metadata))
diff --git a/marimo/_convert/utils.py b/marimo/_convert/utils.py
new file mode 100644
index 0000000000..ee3c3f9965
--- /dev/null
+++ b/marimo/_convert/utils.py
@@ -0,0 +1,37 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Optional
+
+from marimo._ast import codegen
+from marimo._ast.app import _AppConfig
+from marimo._ast.cell import CellConfig
+
+
+def markdown_to_marimo(source: str) -> str:
+ source = source.replace('"""', '\\"\\"\\"')
+ return "\n".join(
+ [
+ "mo.md(",
+ # r-string: a backslash is just a backslash!
+ codegen.indent_text('r"""'),
+ codegen.indent_text(source),
+ codegen.indent_text('"""'),
+ ")",
+ ]
+ )
+
+
+def generate_from_sources(
+ sources: list[str], config: Optional[_AppConfig] = None
+) -> str:
+ """
+ Given a list of Python source code,
+ generate the marimo file contents.
+ """
+ return codegen.generate_filecontents(
+ sources,
+ ["__" for _ in sources],
+ [CellConfig() for _ in range(len(sources))],
+ config=config,
+ )
diff --git a/tests/_ast/test_transformers.py b/tests/_ast/test_transformers.py
new file mode 100644
index 0000000000..b00f098b86
--- /dev/null
+++ b/tests/_ast/test_transformers.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+import ast
+import sys
+
+import pytest
+
+from marimo._ast.transformers import NameTransformer
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_name_transformer() -> None:
+ # Test code
+ code = """
+def old_function():
+ old_variable = 42
+ return old_variable
+
+class OldClass:
+ def __init__(self):
+ self.old_attribute = "hello"
+
+old_global = "world"
+ """
+
+ # Create an AST from the code
+ tree = ast.parse(code)
+
+ # Define name substitutions
+ name_substitutions = {
+ "old_function": "new_function",
+ "old_variable": "new_variable",
+ "OldClass": "NewClass",
+ "old_attribute": "new_attribute",
+ "old_global": "new_global",
+ }
+
+ # Apply the NameTransformer
+ transformer = NameTransformer(name_substitutions)
+ new_tree = transformer.visit(tree)
+
+ # Convert the new AST back to code
+ new_code = ast.unparse(new_tree)
+
+ # Expected transformed code
+ expected_code = """
+def new_function():
+ old_variable = 42
+ return old_variable
+
+class NewClass:
+
+ def __init__(self):
+ self.old_attribute = 'hello'
+new_global = 'world'
+"""
+
+ # Remove leading/trailing whitespace and normalize line endings
+ new_code = new_code.strip()
+ expected_code = expected_code.strip()
+
+ # Assert that the transformation was successful
+ assert new_code == expected_code
+ assert transformer.made_changes
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_name_transformer_no_changes() -> None:
+ code = "x = 1"
+ tree = ast.parse(code)
+ transformer = NameTransformer({"y": "z"})
+ new_tree = transformer.visit(tree)
+ new_code = ast.unparse(new_tree)
+
+ assert new_code.strip() == code.strip()
+ assert not transformer.made_changes
diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.py
index 069faf8f45..1835c65c38 100644
--- a/tests/_ast/test_visitor.py
+++ b/tests/_ast/test_visitor.py
@@ -251,6 +251,49 @@ def test_nested_comprehensions() -> None:
assert not v.variable_data
+def test_comprehension_generator() -> None:
+ code = "\n".join(
+ [
+ "[x for x in x]",
+ ]
+ )
+ v = visitor.ScopedVisitor()
+ mod = ast.parse(code)
+ v.visit(mod)
+ assert v.defs == set()
+ assert v.refs == set(["x"])
+ assert not v.variable_data
+
+
+def test_nested_comprehension_generator() -> None:
+ code = "\n".join(
+ [
+ "[x for x in x for x in x]",
+ ]
+ )
+ v = visitor.ScopedVisitor()
+ mod = ast.parse(code)
+ v.visit(mod)
+ assert v.defs == set()
+ assert v.refs == set(["x"])
+ assert not v.variable_data
+
+
+def test_nested_comprehension_generator_with_named_expr() -> None:
+ code = "\n".join(
+ [
+ "[(x := x) for x in x for x in x]",
+ ]
+ )
+ v = visitor.ScopedVisitor()
+ mod = ast.parse(code)
+ v.visit(mod)
+ # named expr kicks x out, evicting the ref
+ assert v.defs == set(["x"])
+ assert v.refs == set()
+ assert v.variable_data == {"x": [VariableData(kind="variable")]}
+
+
def test_walrus_leaks_to_global_in_comprehension() -> None:
code = "\n".join(
[
diff --git a/tests/_cli/test_ipynb_to_marimo.py b/tests/_cli/test_ipynb_to_marimo.py
index c6857a1267..5f5bb21927 100644
--- a/tests/_cli/test_ipynb_to_marimo.py
+++ b/tests/_cli/test_ipynb_to_marimo.py
@@ -116,8 +116,8 @@ def test_multiple_defs() -> None:
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[3] == "y_1 = 1"
+ assert codes[4] == "y_1"
assert (
codes[5]
== textwrap.dedent(
diff --git a/tests/_convert/test_convert_utils.py b/tests/_convert/test_convert_utils.py
new file mode 100644
index 0000000000..fbbad06089
--- /dev/null
+++ b/tests/_convert/test_convert_utils.py
@@ -0,0 +1,52 @@
+from __future__ import annotations
+
+from textwrap import dedent
+
+from marimo._convert import utils
+
+
+def test_markdown_to_marimo():
+ markdown = "# Hello, World!\nThis is a test."
+ expected = 'mo.md(\n r"""\n # Hello, World!\n This is a test.\n """\n)' # noqa: E501
+ assert utils.markdown_to_marimo(markdown) == expected
+
+ markdown = 'Here are some quotes: """'
+ expected = (
+ 'mo.md(\n r"""\n Here are some quotes: \\"\\"\\"\n """\n)' # noqa: E501
+ )
+ assert utils.markdown_to_marimo(markdown) == expected
+
+ markdown = r"This has a backslash: \\"
+ expected = 'mo.md(\n r"""\n This has a backslash: \\\\\n """\n)' # noqa: E501
+ assert utils.markdown_to_marimo(markdown) == expected
+
+
+def test_generate_from_sources():
+ # Test with basic sources
+ sources = ["print('Hello')", "x = 5"]
+ result = utils.generate_from_sources(sources)
+
+ assert result == dedent(
+ """
+import marimo
+
+__generated_with = "0.8.20"
+app = marimo.App()
+
+
+def __():
+ print('Hello')
+ return
+
+
+def __():
+ x = 5
+ return (x,)
+
+
+if __name__ == "__main__":
+ app.run()
+ """.lstrip()
+ )
diff --git a/tests/_convert/test_ipynb.py b/tests/_convert/test_ipynb.py
new file mode 100644
index 0000000000..8a3a0ffad6
--- /dev/null
+++ b/tests/_convert/test_ipynb.py
@@ -0,0 +1,951 @@
+from __future__ import annotations
+
+import ast
+import sys
+from textwrap import dedent
+
+import pytest
+
+from marimo._convert.ipynb import (
+ _transform_sources,
+ transform_add_marimo_import,
+ transform_cell_metadata,
+ transform_duplicate_definitions,
+ transform_exclamation_mark,
+ transform_fixup_multiple_definitions,
+ transform_magic_commands,
+ transform_remove_duplicate_imports,
+)
+
+
+def dd(sources: list[str]) -> list[str]:
+ return [dedent(s) for s in sources]
+
+
+def assert_sources_equal(transformed: list[str], expected: list[str]) -> None:
+ expected = dd(expected)
+ assert len(transformed) == len(expected)
+ try:
+ transformed = [ast.unparse(ast.parse(t)) for t in transformed]
+ except SyntaxError:
+ transformed = [t for t in transformed]
+ try:
+ expected = [ast.unparse(ast.parse(e)) for e in expected]
+ except SyntaxError:
+ expected = [e for e in expected]
+ assert transformed == expected
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_fixup_multiple_definitions():
+ # Makes everything private to avoid conflicts.
+ # Comments are removed, unfortunately.
+ sources = [
+ "x = 1\nprint(x) # print",
+ "x = 2\nprint(x) # print",
+ ]
+ result = transform_fixup_multiple_definitions(sources)
+ assert result == [
+ "_x = 1\nprint(_x)",
+ "_x = 2\nprint(_x)",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_fixup_multiple_definitions_when_not_encapsulated():
+ # Since the definitions are not encapsulated in a single cell, they should
+ # not be transformed.
+ sources = [
+ "x = 1",
+ "print(x) # print",
+ "x = 2",
+ "print(x) # print",
+ ]
+ result = transform_fixup_multiple_definitions(sources)
+ assert result == sources
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_add_marimo_import():
+ sources = [
+ "mo.md('# Hello')",
+ "print('World')",
+ "mo.sql('SELECT * FROM table')",
+ ]
+ result = transform_add_marimo_import(sources)
+ assert "import marimo as mo" in result
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_magic_commands():
+ sources = [
+ "%%sql\nSELECT * FROM table",
+ "%%sql\nSELECT * \nFROM table",
+ "%cd /path/to/dir",
+ "%matplotlib inline",
+ ]
+ result = transform_magic_commands(sources)
+ assert result == [
+ '_df = mo.sql("""\nSELECT * FROM table\n""")',
+ '_df = mo.sql("""\nSELECT * \nFROM table\n""")',
+ "import os\nos.chdir('/path/to/dir')",
+ "# '%matplotlib inline' command supported automatically in marimo",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_exclamation_mark():
+ sources = [
+ "!pip install package",
+ "!ls -l",
+ ]
+ result = transform_exclamation_mark(sources)
+ assert result == [
+ "# (use marimo's built-in package management features instead) !pip install package", # noqa: E501
+ "!ls -l",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions():
+ sources = [
+ "a = 1",
+ "print(a)",
+ "a = 2",
+ "print(a)",
+ "print(a)",
+ "a = 3",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert result == [
+ "a = 1",
+ "print(a)",
+ "a_1 = 2",
+ "print(a_1)",
+ "print(a_1)",
+ "a_2 = 3",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_cell_metadata():
+ sources = [
+ "print('Hello')",
+ "print('World')",
+ ]
+ metadata = [
+ {"tags": ["tag1", "tag2"]},
+ {},
+ ]
+ result = transform_cell_metadata(sources, metadata)
+ assert result == [
+ "# Cell tags: tag1, tag2\nprint('Hello')",
+ "print('World')",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_remove_duplicate_imports():
+ sources = [
+ "import numpy as np\nimport pandas as pd\nimport numpy as np",
+ "from sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score", # noqa: E501
+ "import matplotlib.pyplot as plt\nimport numpy as np",
+ ]
+ result = transform_remove_duplicate_imports(sources)
+ assert result == [
+ "import numpy as np\nimport pandas as pd",
+ "from sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score", # noqa: E501
+ "import matplotlib.pyplot as plt",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_remove_duplicate_imports_single_line():
+ sources = [
+ "import polars as pl",
+ "import polars as pl",
+ ]
+ result = transform_remove_duplicate_imports(sources)
+ assert result == [
+ "import polars as pl",
+ "",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_fixup_multiple_definitions_complex():
+ sources = [
+ "x = 1\ny = 2\nprint(x, y)",
+ "x = 3\nz = 4\nprint(x, z)",
+ "y = 5\nprint(y)",
+ ]
+ result = transform_fixup_multiple_definitions(sources)
+ assert result == [
+ "_x = 1\n_y = 2\nprint(_x, _y)",
+ "_x = 3\nz = 4\nprint(_x, z)",
+ "_y = 5\nprint(_y)",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_fixup_multiple_definitions_with_functions():
+ sources = [
+ "def func():\n x = 1\n return x\nfunc()",
+ "def func():\n y = 1\n return y\nfunc()",
+ "x = 2\nprint(x)",
+ "def another_func():\n x = 3\n return x",
+ ]
+ result = transform_fixup_multiple_definitions(sources)
+ assert result == [
+ "def _func():\n x = 1\n return x\n_func()",
+ "def _func():\n y = 1\n return y\n_func()",
+ "x = 2\nprint(x)",
+ "def another_func():\n x = 3\n return x",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_add_marimo_import_edge_cases():
+ sources = [
+ "# mo.md('# Hello')",
+ "print('mo.sql is not a real call')",
+ "mo = 'not the real mo'",
+ ]
+ result = transform_add_marimo_import(sources)
+ assert "import marimo as mo" not in result
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_magic_commands_complex():
+ sources = [
+ "%%sql\nSELECT *\nFROM table\nWHERE condition",
+ "%%time\nfor i in range(1000000):\n pass",
+ "%load_ext autoreload\n%autoreload 2",
+ "%env MY_VAR=value",
+ ]
+ result = transform_magic_commands(sources)
+ assert (
+ result
+ == [
+ '_df = mo.sql("""\nSELECT *\nFROM table\nWHERE condition\n""")',
+ (
+ "# magic command not supported in marimo; please file an issue to add support\n" # noqa: E501
+ "# %%time\nfor i in range(1000000):\n"
+ " pass"
+ ),
+ (
+ "# '%load_ext autoreload\\n%autoreload 2' command supported automatically in marimo" # noqa: E501
+ ),
+ "import os\nos.environ['MY_VAR'] = 'value'",
+ ]
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_exclamation_mark_complex():
+ sources = [
+ "!pip install package1 package2",
+ "! ls -l | grep '.py'",
+ "result = !echo 'Hello, World!'",
+ "!python script.py arg1 arg2",
+ ]
+ result = transform_exclamation_mark(sources)
+ assert result == [
+ "# (use marimo's built-in package management features instead) !pip install package1 package2", # noqa: E501
+ # These are currently unhandled.
+ "! ls -l | grep '.py'",
+ "result = !echo 'Hello, World!'",
+ "!python script.py arg1 arg2",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_complex():
+ sources = [
+ "x = 1 # comment unaffected",
+ "a = 1\nb = 2\nprint(a, b)",
+ "a = 3\nc = 4\nprint(a, c)",
+ "b = 5\nd = 6\nprint(b, d)",
+ "a = 7\nb = 8\nc = 9\nprint(a, b, c)",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert result == [
+ "x = 1 # comment unaffected",
+ "a = 1\nb = 2\nprint(a, b)",
+ "a_1 = 3\nc = 4\nprint(a_1, c)",
+ "b_1 = 5\nd = 6\nprint(b_1, d)",
+ "a_2 = 7\nb_2 = 8\nc_1 = 9\nprint(a_2, b_2, c_1)",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_cell_metadata_complex():
+ sources = [
+ "print('Cell 1')",
+ "print('Cell 2')",
+ "print('Cell 3')",
+ ]
+ metadata = [
+ {"tags": ["important", "data-processing"]},
+ {"tags": []},
+ {"tags": ["visualization"], "collapsed": True},
+ ]
+ result = transform_cell_metadata(sources, metadata)
+ assert result == [
+ "# Cell tags: important, data-processing\nprint('Cell 1')",
+ "print('Cell 2')",
+ "# Cell tags: visualization\nprint('Cell 3')",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_remove_duplicate_imports_complex():
+ sources = [
+ "import numpy as np\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plt", # noqa: E501
+ "from sklearn.model_selection import train_test_split, cross_val_score\nimport numpy as np", # noqa: E501
+ "from pandas import Series\nfrom matplotlib import pyplot as plt\nimport pandas as pd", # noqa: E501
+ ]
+ result = transform_remove_duplicate_imports(sources)
+ assert result == [
+ "import numpy as np\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plt", # noqa: E501
+ "from sklearn.model_selection import train_test_split, cross_val_score", # noqa: E501
+ "from pandas import Series\nfrom matplotlib import pyplot as plt\nimport pandas as pd", # noqa: E501
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_fixup_multiple_definitions_with_classes():
+ sources = [
+ "class MyClass:\n x = 1\n def method(self):\n return self.x", # noqa: E501
+ "x = 2\nprint(x)",
+ "class MyClass:\n x = 3\n def method(self):\n return self.x", # noqa: E501
+ ]
+ result = transform_fixup_multiple_definitions(sources)
+ assert result == [
+ "class _MyClass:\n x = 1\n\n def method(self):\n return self.x", # noqa: E501
+ "x = 2\nprint(x)",
+ "class _MyClass:\n x = 3\n\n def method(self):\n return self.x", # noqa: E501
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_magic_commands_unsupported():
+ sources = [
+ "%custom_magic arg1 arg2",
+ "%%custom_cell_magic\nsome\ncontent",
+ ]
+ result = transform_magic_commands(sources)
+ assert result == [
+ "# magic command not supported in marimo; please file an issue to add support\n# %custom_magic # arg1 arg2", # noqa: E501
+ "# magic command not supported in marimo; please file an issue to add support\n# %%custom_cell_magic\n# some\n# content", # noqa: E501
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_exclamation_mark_with_variables():
+ sources = [
+ "package = 'numpy'\n!pip install {package}",
+ "command = 'echo \"Hello, World!\"'\n!{command}",
+ ]
+ result = transform_exclamation_mark(sources)
+ assert result == [
+ "package = 'numpy'\n# (use marimo's built-in package management features instead) !pip install {package}", # noqa: E501
+ "command = 'echo \"Hello, World!\"'\n!{command}",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_with_comprehensions():
+ sources = [
+ "[x for x in range(10)]",
+ "x = 5\nprint(x)",
+ "{x: x**2 for x in range(5)}",
+ "x = 10\nprint(x)",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert result == [
+ "[x for x in range(10)]",
+ "x = 5\nprint(x)",
+ "{x: x**2 for x in range(5)}",
+ "x_1 = 10\nprint(x_1)",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_with_reference_to_previous():
+ sources = [
+ "x = 1",
+ "x = x + 1\nprint(x)",
+ "print(x)",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert result == [
+ "x = 1",
+ "x_1 = x + 1\nprint(x_1)",
+ "print(x_1)",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_cell_metadata_with_complex_metadata():
+ sources = [
+ "print('Complex metadata')",
+ ]
+ metadata = [
+ {
+ "tags": ["tag1", "tag2"],
+ "collapsed": True,
+ "scrolled": False,
+ "custom": {"key": "value"},
+ }
+ ]
+ result = transform_cell_metadata(sources, metadata)
+ assert result == [
+ "# Cell tags: tag1, tag2\nprint('Complex metadata')",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_remove_duplicate_imports_with_aliases():
+ sources = [
+ "import numpy as np\nimport pandas as pd",
+ "import numpy as numpy\nfrom pandas import DataFrame as DF",
+ "import numpy\nfrom pandas import Series",
+ ]
+ result = transform_remove_duplicate_imports(sources)
+ assert result == [
+ "import numpy as np\nimport pandas as pd",
+ "import numpy as numpy\nfrom pandas import DataFrame as DF",
+ "import numpy\nfrom pandas import Series",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_remove_duplicate_imports_single():
+ sources = [
+ "import polars as pl",
+ "import polars as pl",
+ "import polars as pl\ndf = pl.DataFrame({'a': [1, 2, 3]})",
+ ]
+ result = transform_remove_duplicate_imports(sources)
+ assert result == [
+ "import polars as pl",
+ "",
+ "df = pl.DataFrame({'a': [1, 2, 3]})",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_with_re_def():
+ sources = [
+ "x = 1",
+ "x = x + 1\nprint(x)",
+ "x = x + 2\nprint(x)",
+ "x = x + 3\nprint(x)",
+ "x = 10\nprint(x)",
+ "print(x)",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert result == [
+ "x = 1",
+ "x_1 = x + 1\nprint(x_1)",
+ "x_2 = x_1 + 2\nprint(x_2)",
+ "x_3 = x_2 + 3\nprint(x_3)",
+ "x_4 = 10\nprint(x_4)",
+ "print(x_4)",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_with_multiple_variables():
+ sources = [
+ "x, y = 1, 2",
+ "x = x + y\ny = y + x\nprint(x, y)",
+ "z = x + y\nx = z\nprint(x, y, z)",
+ "x, y, z = y, z, x\nprint(x, y, z)",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ dd(
+ [
+ "x, y = 1, 2",
+ "x_1 = x + y\ny_1 = y + x_1\nprint(x_1, y_1)",
+ "z = x_1 + y_1\nx_2 = z\nprint(x_2, y_1, z)",
+ "x_3, y_2, z_1 = (y_1, z, x_2)\nprint(x_3, y_2, z_1)",
+ ]
+ ),
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_with_function_and_global():
+ sources = dd(
+ [
+ "x = 10",
+ """
+ def func():
+ global x
+ x_1 = x + 1
+ return x
+ """,
+ """
+ x = func()
+ print(x)
+ """,
+ """
+ def another_func():
+ x = 20
+ return x
+ """,
+ """
+ x = another_func()
+ print(x)
+ """,
+ ]
+ )
+ expected = dd(
+ [
+ "x = 10",
+ """
+ def func():
+ global x
+ x_1 = x + 1
+ return x
+ """,
+ """
+ x_1 = func()
+ print(x_1)
+ """,
+ """
+ def another_func():
+ x = 20
+ return x
+ """,
+ """
+ x_2 = another_func()
+ print(x_2)
+ """,
+ ]
+ )
+
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(result, expected)
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_with_comprehensions_and_lambdas():
+ sources = [
+ "x = [i for i in range(5)]",
+ "x = list(map(lambda x: x**2, x))\nprint(x)",
+ "x = {x: x**3 for x in x}\nprint(x)",
+ "x = lambda x: x**4\nprint([x(i) for i in range(5)])",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ dd(
+ [
+ "x = [i for i in range(5)]",
+ "x_1 = list(map(lambda x: x**2, x))\nprint(x_1)",
+ "x_2 = {x: x**3 for x in x_1}\nprint(x_2)",
+ "x_3 = lambda x: x**4\nprint([x_3(i) for i in range(5)])",
+ ]
+ ),
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_with_simple_lambda():
+ sources = [
+ "x = 0",
+ "x = lambda x: x**2",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ dd(
+ [
+ "x = 0",
+ "x_1 = lambda x: x**2",
+ ]
+ ),
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_simple_redefinition() -> None:
+ sources = [
+ "x = 0",
+ "x",
+ "x = 1",
+ "x",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert result == [
+ "x = 0",
+ "x",
+ "x_1 = 1",
+ "x_1",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_with_simple_function():
+ sources = [
+ "x = 0",
+ "x = 1",
+ "def f(x): return x",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert result == [
+ "x = 0",
+ "x_1 = 1",
+ "def f(x): return x",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_attrs():
+ sources = [
+ "x = 0",
+ "x",
+ "x = x.apply()",
+ "x",
+ ]
+ result = transform_duplicate_definitions(sources)
+ assert result == [
+ "x = 0",
+ "x",
+ "x_1 = x.apply()",
+ "x_1",
+ ]
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definition_shadowed_definition():
+ sources = dd(
+ [
+ "x = 0",
+ "x",
+ """
+ x = 1
+ def f():
+ x = 1;
+ """,
+ ]
+ )
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ [
+ "x = 0",
+ "x",
+ """
+ x_1 = 1
+ def f():
+ x = 1;
+ """,
+ ],
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definition_kwarg():
+ sources = dd(
+ [
+ "x = 0",
+ "x",
+ """
+ x = 1
+ def f(x=x):
+ return x
+ """,
+ ]
+ )
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ [
+ "x = 0",
+ "x",
+ """
+ x_1 = 1
+ def f(x=x_1):
+ return x
+ """,
+ ],
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definition_nested():
+ sources = dd(
+ [
+ "x = 0",
+ "x",
+ """
+ x = 1
+ def f(x=x):
+ x = 2
+ def g(x=x):
+ return x
+ return g()
+ """,
+ ]
+ )
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ [
+ "x = 0",
+ "x",
+ """
+ x_1 = 1
+ def f(x=x_1):
+ x = 2
+ def g(x=x):
+ return x
+ return g()
+ """,
+ ],
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_function_definitions():
+ sources = dd(
+ [
+ "def f(): pass",
+ "f()",
+ "def f(): pass",
+ "f()",
+ ]
+ )
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ [
+ "def f(): pass",
+ "f()",
+ "def f_1(): pass",
+ "f_1()",
+ ],
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_classes():
+ sources = dd(
+ [
+ "class A(): ...",
+ "A()",
+ "class A(): ...",
+ "A()",
+ ]
+ )
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ [
+ "class A(): ...",
+ "A()",
+ "class A_1(): ...",
+ "A_1()",
+ ],
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_numbered_no_conflict():
+ sources = dd(
+ [
+ "df = 1",
+ "df_1 = 1",
+ "df",
+ ]
+ )
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ [
+ "df = 1",
+ "df_1 = 1",
+ "df",
+ ],
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_numbered():
+ # handle the user defining variables like df_1
+ sources = dd(
+ [
+ "df = 1",
+ "df_1 = 1",
+ "df = 2",
+ "df",
+ "df = 3",
+ "df",
+ ]
+ )
+ result = transform_duplicate_definitions(sources)
+ assert_sources_equal(
+ result,
+ [
+ "df = 1",
+ "df_1 = 1",
+ "df_2 = 2",
+ "df_2",
+ "df_3 = 3",
+ "df_3",
+ ],
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_and_aug_assign() -> None:
+ sources = dd(
+ [
+ "x = 1",
+ "x",
+ "x += 1",
+ "x",
+ ]
+ )
+ result = _transform_sources(sources, [{} for _ in sources])
+ assert_sources_equal(
+ result,
+ [
+ "x = 1",
+ "x",
+ "x_1 = x + 1",
+ "x_1",
+ ],
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_read_before_write() -> None:
+ sources = dd(
+ [
+ "x = 1",
+ "x",
+ "x; x = 2; x",
+ "x",
+ ]
+ )
+ result = _transform_sources(sources, [{} for _ in sources])
+ assert_sources_equal(
+ result,
+ [
+ "x = 1",
+ "x",
+ "x; x_1 = 2; x_1",
+ "x_1",
+ ],
+ )
+
+
+ sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+)
+def test_transform_duplicate_definitions_syntax_error() -> None:
+ sources = dd(
+ [
+ "x ( b 2 d & !",
+ "x",
+ ]
+ )
+ result = _transform_sources(sources, [{} for _ in sources])
+ assert_sources_equal(
+ result,
+ [
+ "x ( b 2 d & !",
+ "x",
+ ],
+ )