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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: preserve literal strings in type annotations (#6451)
Dylan Madisettif28480089cc2
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex 1fa721eb6c..a03ca4b6d2 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -22,6 +22,7 @@ from marimo._ast.sql_visitor import ()from marimo._ast.variables import is_localfrom marimo._dependencies.dependencies import DependencyManager+from marimo._utils.strings import standardize_annotation_quotesLOGGER = _loggers.marimo_logger()@@ -813,11 +814,8 @@ class ScopedVisitor(ast.NodeVisitor):annotation = ast.unparse(node.annotation)# It's also possible for multiline types/ stringsannotation = 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]}"'+ # Standardize quotes to use double quotes consistently+ annotation = standardize_annotation_quotes(annotation)self.variable_data[name][0].annotation_data = AnnotationData(annotation, annotation_refsdiff --git a/marimo/_utils/strings.py b/marimo/_utils/strings.pynew file mode 100644index 0000000000..3cb48e5b8b--- /dev/null+++ b/marimo/_utils/strings.py@@ -0,0 +1,66 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++import re+++def standardize_annotation_quotes(annotation: str) -> str:+ """Standardize quotes in type annotations to use double quotes.++ This handles complex cases like Literal['foo', 'bar'] -> Literal["foo", "bar"]+ while preserving mixed quote scenarios where double quotes are already present.++ Args:+ annotation: The type annotation string to standardize++ Returns:+ The annotation string with standardized double quotes++ Examples:+ >>> standardize_annotation_quotes("Literal['foo', 'bar']")+ 'Literal["foo", "bar"]'+ >>> standardize_annotation_quotes("Literal['say \"hello\"']")+ 'Literal[\'say "hello"\']' # Preserved due to internal double quotes+ >>> standardize_annotation_quotes("int")+ 'int' # No quotes to standardize+ """++ # Regex pattern to match string literals within the annotation:+ #+ # '([^'\\]*(?:\\.[^'\\]*)*)' - Matches single-quoted strings:+ # - ' - Opening single quote+ # - ([^'\\]* - Capture group: any chars except ' and \+ # - (?:\\.[^'\\]*)* - Non-capturing group: escaped char followed by non-quote/backslash chars, repeated+ # - )' - Closing single quote and end capture group+ #+ # | - OR operator+ #+ # "([^"\\]*(?:\\.[^"\\]*)*)" - Matches double-quoted strings:+ # - " - Opening double quote+ # - ([^"\\]* - Capture group: any chars except " and \+ # - (?:\\.[^"\\]*)* - Non-capturing group: escaped char followed by non-quote/backslash chars, repeated+ # - )" - Closing double quote and end capture group+ #+ # This pattern correctly handles escaped quotes within strings like 'it\'s' or "say \"hello\""+ string_pattern = (+ r"'([^'\\]*(?:\\.[^'\\]*)*)'|\"([^\"\\]*(?:\\.[^\"\\]*)*)\""+ )++ def replace_quotes(match: re.Match[str]) -> str:+ if match.group(1) is not None: # Single quoted string matched+ content = match.group(1)+ # Check if the content contains unescaped double quotes+ # If so, keep as single quotes to avoid escaping issues+ if '"' in content and '\\"' not in content:+ return match.group(0) # Keep original single-quoted string+ else:+ # Convert to double quotes, handling escaped characters properly+ content = content.replace("\\'", "'") # Unescape single quotes+ content = content.replace(+ '"', '\\"'+ ) # Escape any double quotes+ return f'"{content}"'+ else: # Double quoted string matched (group 2)+ return match.group(0) # Keep as is - already using double quotes++ return re.sub(string_pattern, replace_quotes, annotation)diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex 9a8a5e603e..9e858d0a43 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -370,6 +370,70 @@ class TestGeneration:)assert fndef == expected+ def test_literal_quote_standardization(self) -> None:+ """Test that Literal type annotations are standardized to double quotes.++ Regression test for https://github.com/marimo-team/marimo/issues/6446+ """+ # Test that single quotes in Literal are standardized to double quotes+ referring = "x: Literal['foo', 'bar'] = 'foo'"+ ref_vars = compile_cell(referring).init_variable_data++ code = "z = x"+ cell = compile_cell(code)+ fndef = codegen.to_functiondef(+ cell, "foo", allowed_refs={"Literal"}, variable_data=ref_vars+ )+ expected = "\n".join(+ [+ "@app.cell",+ 'def foo(x: Literal["foo", "bar"]):',+ " z = x",+ " return (z,)",+ ]+ )+ assert fndef == expected++ def test_quote_standardization_edge_cases(self) -> None:+ """Test edge cases for quote standardization in type annotations."""+ # Test mixed quotes where double quotes are preserved+ referring = 'x: Literal["foo", \'bar\'] = "foo"'+ ref_vars = compile_cell(referring).init_variable_data++ code = "z = x"+ cell = compile_cell(code)+ fndef = codegen.to_functiondef(+ cell, "foo", allowed_refs={"Literal"}, variable_data=ref_vars+ )+ expected = "\n".join(+ [+ "@app.cell",+ 'def foo(x: Literal["foo", "bar"]):',+ " z = x",+ " return (z,)",+ ]+ )+ assert fndef == expected++ # Test nested quotes that should remain single due to containing double quotes+ referring = "x: Literal['say \"hello\"'] = 'say \"hello\"'"+ ref_vars = compile_cell(referring).init_variable_data++ code = "z = x"+ cell = compile_cell(code)+ fndef = codegen.to_functiondef(+ cell, "foo", allowed_refs={"Literal"}, variable_data=ref_vars+ )+ expected = "\n".join(+ [+ "@app.cell",+ "def foo(x: Literal['say \"hello\"']):",+ " z = x",+ " return (z,)",+ ]+ )+ assert fndef == expected+@staticmethoddef test_generate_app_constructor_with_auto_download() -> None:config = _AppConfig(