Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: Exposes types if they are explicitly declared by the user (#4720)

Dylan Madisetti2d6811354928
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 4676b609f4..d32663fbf7 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -330,6 +330,10 @@ class CellImpl:
return list(variable_data)[0]
+ @property
+ def init_variable_data(self) -> dict[Name, VariableData]:
+ return {key: vs[0] for key, vs in self.variable_data.items()}
+
def set_runtime_state(
self, status: RuntimeStateType, stream: Stream | None = None
) -> None:
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 6f8a1e95fe..a66245e02f 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -16,7 +16,7 @@ from marimo._ast.compiler import compile_cell
from marimo._ast.names import DEFAULT_CELL_NAME, SETUP_CELL_NAME
from marimo._ast.toplevel import TopLevelExtraction, TopLevelStatus
from marimo._ast.variables import BUILTINS
-from marimo._ast.visitor import Name
+from marimo._ast.visitor import Name, VariableData
from marimo._types.ids import CellId_t
if TYPE_CHECKING:
@@ -39,6 +39,11 @@ NOTICE = "\n".join(
]
)
+BRACES: dict[Literal["(", "["], tuple[str, str]] = {
+ "(": ("(", ")"),
+ "[": ("[", "]"),
+}
+
Decorators = Literal["cell", "function", "class_definition"]
@@ -81,16 +86,18 @@ def format_tuple_elements(
elems: tuple[str, ...],
indent: bool = False,
allowed_naked: bool = False,
+ brace: Literal["(", "["] = "(",
) -> str:
"""
Replaces (...) with the elements in elems, formatted as a tuple.
Adjusts for multiple lines as needed.
"""
+ left, right = BRACES[brace]
maybe_indent = indent_text if indent else (lambda x: x)
if not elems:
if allowed_naked:
return maybe_indent(code.replace("(...)", "").rstrip())
- return maybe_indent(code.replace("(...)", "()"))
+ return maybe_indent(code.replace("(...)", left + right))
if allowed_naked and len(elems) == 1:
allowed_naked = False
@@ -100,7 +107,7 @@ def format_tuple_elements(
if allowed_naked:
attempt = code.replace("(...)", tuple_str).rstrip()
else:
- attempt = code.replace("(...)", f"({tuple_str})")
+ attempt = code.replace("(...)", f"{left}{tuple_str}{right}")
attempt = maybe_indent(attempt)
if len(attempt) < MAX_LINE_LENGTH:
@@ -111,7 +118,7 @@ def format_tuple_elements(
elems = (elems[0].strip(","),)
multiline_tuple = "\n".join(
- ["(", indent_text(",\n".join(elems)) + ",", ")"]
+ [left, indent_text(",\n".join(elems)) + ",", right]
)
return maybe_indent(code.replace("(...)", multiline_tuple))
@@ -166,12 +173,35 @@ def build_setup_section(setup_cell: Optional[CellImpl]) -> str:
)
+def to_annotated_string(
+ variable_data: dict[Name, VariableData],
+ names: tuple[Name, ...],
+ allowed_refs: set[Name],
+) -> dict[str, str]:
+ """Checks relevant variables for annotation data, and if found either
+ represents the type directly or as a string (as a safety measure)"""
+ response: dict[str, str] = {}
+ if not variable_data:
+ return response
+ for name in names:
+ if name in variable_data and variable_data[name]:
+ variable = variable_data[name]
+ annotation = variable.annotation_data
+ if annotation:
+ if annotation.refs - allowed_refs:
+ response[name] = f'"{annotation.repr}"'
+ else:
+ response[name] = annotation.repr
+ return response
+
+
def to_functiondef(
cell: CellImpl,
name: str,
allowed_refs: Optional[set[Name]] = None,
used_refs: Optional[set[Name]] = None,
fn: Literal["cell"] = "cell",
+ variable_data: Optional[dict[str, VariableData]] = None,
) -> str:
# allowed refs are a combination of top level imports and unshadowed
# builtins.
@@ -183,14 +213,16 @@ def to_functiondef(
allowed_refs = BUILTINS
refs = tuple(ref for ref in sorted(cell.refs) if ref not in allowed_refs)
- decorator = to_decorator(cell.config, fn=fn)
-
- prefix = "" if not cell.is_coroutine() else "async "
- signature = format_tuple_elements(f"{prefix}def {name}(...):", refs)
-
- definition_body = [decorator, signature]
- if body := indent_text(cell.code):
- definition_body.append(body)
+ # Check to see if any of the refs have an explicit type assigned to them.
+ annotation_lookups = to_annotated_string(
+ variable_data or {}, refs, allowed_refs
+ )
+ refs = tuple(
+ f"{ref}: {annotation_lookups[ref]}"
+ if ref in annotation_lookups
+ else ref
+ for ref in refs
+ )
# Used refs are a collection of all the references that cells make to some
# external call. We collect them such that we can determine if a variable
@@ -208,8 +240,21 @@ def to_functiondef(
name for name in sorted(cell.defs) if name in used_refs
)
+ decorator = to_decorator(cell.config, fn=fn)
+ prefix = "" if not cell.is_coroutine() else "async "
+ signature = format_tuple_elements(f"{prefix}def {name}(...):", refs)
+
+ definition_body = [decorator, signature]
+ if body := indent_text(cell.code):
+ definition_body.append(body)
+
returns = format_tuple_elements(
- "return (...)", defs, indent=True, allowed_naked=True
+ "return (...)",
+ defs,
+ indent=True,
+ allowed_naked=True,
+ # maybe consider "return Edges(...)"
+ # Such that the return type can simply be 'Edges'
)
definition_body.append(returns)
return "\n".join(definition_body)
@@ -286,6 +331,7 @@ def serialize_cell(
extraction.allowed_refs | cell.defs,
extraction.used_refs,
fn="cell",
+ variable_data=extraction.variables,
)
elif status.is_toplevel:
return to_top_functiondef(cell, extraction.allowed_refs)
diff --git a/marimo/_ast/toplevel.py b/marimo/_ast/toplevel.py
index fa457c2387..10781ace41 100644
--- a/marimo/_ast/toplevel.py
+++ b/marimo/_ast/toplevel.py
@@ -16,7 +16,7 @@ from marimo._ast.names import (
TOPLEVEL_CELL_PREFIX,
)
from marimo._ast.variables import BUILTINS
-from marimo._ast.visitor import Name
+from marimo._ast.visitor import Name, VariableData
from marimo._runtime.dataflow import DirectedGraph
from marimo._types.ids import CellId_t
@@ -244,7 +244,8 @@ class TopLevelExtraction:
defs: set[Name] = set()
refs: set[Name] = set()
self.allowed_refs: set[Name] = set(toplevel_defs)
- # Run through and get deff + refs, and a naive attempt at resolving cell
+ self._variables: Optional[dict[Name, VariableData]] = None
+ # Run through and get defs + refs, and a naive attempt at resolving cell
# status.
for idx, (code, name, config) in enumerate(
zip(codes, names, cell_configs)
@@ -349,6 +350,23 @@ class TopLevelExtraction:
_ = resolve(name)
assert not self.unresolved
+ @property
+ def variables(self) -> dict[Name, VariableData]:
+ # Grabs all initial variable data from cells for use in annotations.
+ if self._variables is not None:
+ return self._variables
+ variables = {}
+ for status in self.cells.values():
+ if status._cell:
+ variables.update(status._cell.init_variable_data)
+ for var, status in self.toplevel.items():
+ if status._cell:
+ toplevel_variable = status._cell.toplevel_variable
+ if toplevel_variable:
+ variables[var] = toplevel_variable
+ self._variables = variables
+ return variables
+
@classmethod
def from_graph(
cls,
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 5ba929f4d1..19e76a4911 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -45,6 +45,14 @@ class ImportData:
self.namespace = self.module.split(".")[0]
+@dataclass
+class AnnotationData:
+ # How the annotation is set
+ repr: str
+ # Which references are related to the annotation.
+ refs: set[Name] = field(default_factory=set)
+
+
@dataclass
class VariableData:
# "table", "view", "schema", and "catalog" are SQL variables, not Python.
@@ -74,6 +82,9 @@ class VariableData:
# A reference needed for function/ class definition
unbounded_refs: set[Name] = field(default_factory=set)
+ # References used for annotation (typing)
+ annotation_data: Optional[AnnotationData] = None
+
# For kind == import
import_data: Optional[ImportData] = None
@@ -658,11 +669,46 @@ class ScopedVisitor(ast.NodeVisitor):
def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign:
# Annotated assign
# e.g., x: int = 0
+ # ^ ^ ^
+ # tar ann val?
self.ref_stack.append(set())
if node.value is not None:
self.visit(node.value)
+
+ # Hold on to the annotation references in particular
+ self.ref_stack.append(set())
self.visit(node.annotation)
+ annotation_refs = self.ref_stack.pop()
+ self.ref_stack[-1].update(annotation_refs)
+ # But only if we are in global scope is it relevant.
+ # annotation data
+ record_annotation = False
+ name = ""
+ # Also possible for "var[subscript]:type"
+ # but we do not care about those.
+ if isinstance(node.target, ast.Name):
+ name = node.target.id
+ record_annotation = (
+ len(self.block_stack) == 1 and name not in self.variable_data
+ )
self.visit(node.target)
+
+ # Visit must have inserted the variable, attach the annotation data to
+ # it.
+ if record_annotation and name in self.variable_data:
+ annotation = ast.unparse(node.annotation)
+ # It's also possible for multiline types/ strings
+ annotation = annotation.replace("\n", "").strip()
+ # ast seems to give single quote strings regardless
+ # but ruff asks for double quotes (unless double quotes are
+ # contained).
+ if annotation.startswith("'") and '"' not in annotation[1:-1]:
+ annotation = f'"{annotation[1:-1]}"'
+
+ self.variable_data[name][0].annotation_data = AnnotationData(
+ annotation, annotation_refs
+ )
+
refs = self.ref_stack.pop()
self.ref_stack[-1].update(refs)
return node
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index 2b2a34c57a..aac8ec5c18 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -264,6 +264,111 @@ class TestGeneration:
"test_generate_filecontents_shadowed_builtin"
)
+ def test_with_second_type_noop(self) -> None:
+ referring = "x = 1; x: int = 0"
+ ref_vars = compile_cell(referring).init_variable_data
+
+ code = "z = x + 0"
+ cell = compile_cell(code)
+ fndef = codegen.to_functiondef(cell, "foo", variable_data=ref_vars)
+ expected = "\n".join(
+ [
+ "@app.cell",
+ "def foo(x):",
+ " z = x + 0",
+ " return (z,)",
+ ]
+ )
+ assert fndef == expected
+
+ def test_with_types(self) -> None:
+ referring = "x: int = 0"
+ ref_vars = compile_cell(referring).init_variable_data
+
+ code = "z = x + 0"
+ cell = compile_cell(code)
+ fndef = codegen.to_functiondef(cell, "foo", variable_data=ref_vars)
+ expected = "\n".join(
+ [
+ "@app.cell",
+ "def foo(x: int):",
+ " z = x + 0",
+ " return (z,)",
+ ]
+ )
+ assert fndef == expected
+
+ def test_with_toplevel_types(self) -> None:
+ referring = "x: T = 1"
+ ref_vars = compile_cell(referring).init_variable_data
+
+ code = "z: T = x + 0"
+ cell = compile_cell(code)
+ fndef = codegen.to_functiondef(
+ cell, "foo", allowed_refs={"T"}, variable_data=ref_vars
+ )
+ expected = "\n".join(
+ [
+ "@app.cell",
+ "def foo(x: T):",
+ " z: T = x + 0",
+ " return (z,)",
+ ]
+ )
+ assert fndef == expected
+
+ def test_with_string_types(self) -> None:
+ referring = 'x: "int" = 0'
+ ref_vars = compile_cell(referring).init_variable_data
+
+ code = "z = x + 0"
+ cell = compile_cell(code)
+ fndef = codegen.to_functiondef(cell, "foo", variable_data=ref_vars)
+ expected = "\n".join(
+ [
+ "@app.cell",
+ 'def foo(x: "int"):',
+ " z = x + 0",
+ " return (z,)",
+ ]
+ )
+ assert fndef == expected
+
+ def test_with_nested_string_types(self) -> None:
+ referring = '''x: "TT[\\"i\\"]" = 0; A:"""
+ a new line type"""'''
+ ref_vars = compile_cell(referring).init_variable_data
+
+ code = "z = x + 0"
+ cell = compile_cell(code)
+ fndef = codegen.to_functiondef(cell, "foo", variable_data=ref_vars)
+ expected = "\n".join(
+ [
+ "@app.cell",
+ "def foo(x: 'TT[\"i\"]'):",
+ " z = x + 0",
+ " return (z,)",
+ ]
+ )
+ assert fndef == expected
+
+ def test_with_unknown_types(self) -> None:
+ referring = "x: something = 0"
+ ref_vars = compile_cell(referring).init_variable_data
+
+ code = "z = x + 0"
+ cell = compile_cell(code)
+ fndef = codegen.to_functiondef(cell, "foo", variable_data=ref_vars)
+ expected = "\n".join(
+ [
+ "@app.cell",
+ 'def foo(x: "something"):',
+ " z = x + 0",
+ " return (z,)",
+ ]
+ )
+ assert fndef == expected
+
@staticmethod
def test_generate_app_constructor_with_auto_download() -> None:
config = _AppConfig(