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: type inference with jedi (#11201)

Dylan Madisettiefab69b149b8
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index ea6ee2126e..060f15f67a 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -37,6 +37,7 @@ import { capabilitiesAtom } from "@/core/config/capabilities";
import { mergeConfig, useUserConfig } from "@/core/config/config";
import {
PackageManagerNames,
+ TYPE_INFERENCE_MODES,
type UserConfig,
UserConfigSchema,
} from "@/core/config/config-schema";
@@ -403,6 +404,40 @@ export const UserConfigForm: React.FC = () => {
</div>
)}
/>
+ {!isWasmRuntime && (
+ <OverriddenFormField
+ control={form.control}
+ name="formatting.infer_types"
+ render={({ field, override }) => (
+ <div className="flex flex-col space-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel>Infer types on save</FormLabel>
+ <FormControl>
+ <NativeSelect
+ data-testid="infer-types-select"
+ onChange={(e) => field.onChange(e.target.value)}
+ value={override.value}
+ disabled={field.disabled || override.isOverridden}
+ className="inline-flex mr-2"
+ >
+ {TYPE_INFERENCE_MODES.map((option) => (
+ <option value={option} key={option}>
+ {option}
+ </option>
+ ))}
+ </NativeSelect>
+ </FormControl>
+ <FormMessage />
+ <IsOverridden override={override} />
+ </FormItem>
+ <FormDescription>
+ Add inferred type annotations to cell signatures when
+ saving.
+ </FormDescription>
+ </div>
+ )}
+ />
+ )}
</SettingGroup>
<SettingGroup title="Autocomplete">
<OverriddenFormField
diff --git a/frontend/src/components/editor/__tests__/data-attributes.test.tsx b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
index 5bb8803df5..1c0c26309f 100644
--- a/frontend/src/components/editor/__tests__/data-attributes.test.tsx
+++ b/frontend/src/components/editor/__tests__/data-attributes.test.tsx
@@ -57,7 +57,7 @@ describe("Cell data attributes", () => {
signature_hint_on_typing: false,
copilot: false,
},
- formatting: { line_length: 88 },
+ formatting: { line_length: 88, infer_types: "off" },
package_management: { manager: "pip" },
runtime: {
auto_instantiate: false,
@@ -75,7 +75,11 @@ describe("Cell data attributes", () => {
browser: "default",
follow_symlink: false,
},
- save: { autosave: "off", autosave_delay: 1000, format_on_save: false },
+ save: {
+ autosave: "off",
+ autosave_delay: 1000,
+ format_on_save: false,
+ },
ai: {},
} as UserConfig;
diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.ts
index 0ba002824c..f667f6bd63 100644
--- a/frontend/src/core/config/__tests__/config-schema.test.ts
+++ b/frontend/src/core/config/__tests__/config-schema.test.ts
@@ -79,6 +79,7 @@ test("default UserConfig - empty", () => {
"experimental": {},
"file_browser": {},
"formatting": {
+ "infer_types": "off",
"line_length": 79,
},
"keymap": {
@@ -155,6 +156,7 @@ test("default UserConfig - one level", () => {
"experimental": {},
"file_browser": {},
"formatting": {
+ "infer_types": "off",
"line_length": 79,
},
"keymap": {
@@ -273,7 +275,7 @@ test("resolvedMarimoConfigAtom overrides correctly and does not mutate the origi
autosave_delay: 1000,
format_on_save: false,
},
- formatting: { line_length: 79 },
+ formatting: { line_length: 79, infer_types: "off" },
};
const overrides = {
@@ -299,7 +301,7 @@ test("resolvedMarimoConfigAtom overrides correctly and does not mutate the origi
autosave_delay: 1000,
format_on_save: false,
},
- formatting: { line_length: 79 },
+ formatting: { line_length: 79, infer_types: "off" },
display: { theme: "dark" },
});
@@ -314,7 +316,7 @@ test("resolvedMarimoConfigAtom overrides correctly and does not mutate the origi
autosave_delay: 1000,
format_on_save: false,
},
- formatting: { line_length: 79 },
+ formatting: { line_length: 79, infer_types: "off" },
});
});
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index 2c17043a35..3d447912c7 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -44,6 +44,8 @@ export const DEFAULT_AI_MODEL = "openai/gpt-4o";
*/
const AUTO_DOWNLOAD_FORMATS = ["html", "markdown", "ipynb"] as const;
+export const TYPE_INFERENCE_MODES = ["off", "jedi"] as const;
+
export type CopilotMode = NonNullable<schemas["AiConfig"]["mode"]>;
export const COPILOT_MODES: CopilotMode[] = [
"manual",
@@ -112,6 +114,7 @@ export const UserConfigSchema = z
.nonnegative()
.prefault(79)
.transform((n) => Math.min(n, 1000)),
+ infer_types: z.enum(TYPE_INFERENCE_MODES).prefault("off"),
})
.prefault({}),
keymap: z
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 4f3ccd81ec..3e7e023c8b 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -21,6 +21,7 @@ from marimo._ast.names import (
)
from marimo._ast.parse import ast_parse
from marimo._ast.toplevel import TopLevelExtraction, TopLevelStatus
+from marimo._ast.type_inference import infer_annotations
from marimo._ast.variables import BUILTINS
from marimo._ast.visitor import Name, VariableData
from marimo._convert.converters import MarimoConvert
@@ -36,6 +37,8 @@ from marimo._version import __version__
if TYPE_CHECKING:
from pathlib import Path
+ from marimo._ast.type_inference import TypeInferenceMode
+
from typing import TypeAlias
Cls: TypeAlias = type
@@ -80,7 +83,9 @@ def indent_text(text: str) -> str:
def _format_arg(arg: Any) -> str:
if isinstance(arg, str):
- return f'"{arg}"'.replace("\\", "\\\\")
+ literal = repr(arg)
+ # Match Ruff's quote style unless the value contains double quotes.
+ return f'"{literal[1:-1]}"' if '"' not in arg else literal
elif isinstance(arg, list):
return f"[{', '.join([_format_arg(item) for item in arg])}]"
else:
@@ -522,7 +527,12 @@ def generate_app_constructor(config: _AppConfig | None) -> str:
return format_tuple_elements("app = marimo.App(...)", kwargs)
-def generate_filecontents_from_ir(ir: NotebookSerializationV1) -> str:
+def generate_filecontents_from_ir(
+ ir: NotebookSerializationV1,
+ *,
+ infer_types: TypeInferenceMode = "off",
+ line_length: int = 79,
+) -> str:
# Markdown frontmatter may contain non-config metadata (e.g., author,
# description). Suppress warnings for unrecognized keys from markdown.
silent = (
@@ -540,12 +550,18 @@ def generate_filecontents_from_ir(ir: NotebookSerializationV1) -> str:
else cell.name
for cell in ir.cells
]
+ filename = (
+ ir.filename if ir.filename and ir.filename != "<marimo>" else None
+ )
return generate_filecontents(
codes=[cell.code for cell in ir.cells],
names=names,
cell_configs=[CellConfig.from_dict(cell.options) for cell in ir.cells],
config=_AppConfig.from_untrusted_dict(ir.app.options, silent=silent),
header_comments=header_comments,
+ filename=filename,
+ infer_types=infer_types,
+ line_length=line_length,
)
@@ -585,8 +601,12 @@ def generate_filecontents(
cell_configs: list[CellConfig],
config: _AppConfig | None = None,
header_comments: str | None = None,
+ *,
+ filename: str | None = None,
+ infer_types: TypeInferenceMode = "off",
+ line_length: int = 79,
) -> str:
- """Translates a sequences of codes (cells) to a Python file"""
+ """Generate a Python notebook from cell source and configuration."""
# Normalize internal cell names. Empty names would emit `def ():`
# (invalid Python) and fall back to the unparsable-cell path;
@@ -600,6 +620,16 @@ def generate_filecontents(
if setup_cell:
toplevel_defs = set(setup_cell.defs)
extraction = TopLevelExtraction(codes, names, cell_configs, toplevel_defs)
+ if infer_types != "off":
+ extraction.add_default_annotations(
+ infer_annotations(
+ extraction,
+ setup_cell,
+ filename=filename,
+ mode=infer_types,
+ line_length=line_length,
+ )
+ )
cell_blocks = [
safe_serialize_cell(extraction, status) for status in extraction
]
diff --git a/marimo/_ast/toplevel.py b/marimo/_ast/toplevel.py
index 0db471d59e..f80e558f7a 100644
--- a/marimo/_ast/toplevel.py
+++ b/marimo/_ast/toplevel.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import token as token_types
+from dataclasses import replace
from enum import Enum
from io import BytesIO
from tokenize import tokenize
@@ -16,7 +17,7 @@ from marimo._ast.names import (
TOPLEVEL_CELL_PREFIX,
)
from marimo._ast.variables import BUILTINS
-from marimo._ast.visitor import Name, VariableData
+from marimo._ast.visitor import AnnotationData, Name, VariableData
from marimo._runtime.dataflow import topological_sort
from marimo._runtime.dataflow.topology import GraphTopology
from marimo._types.ids import CellId_t
@@ -388,6 +389,18 @@ class TopLevelExtraction:
self._variables = variables
return variables
+ def add_default_annotations(
+ self, annotations: dict[Name, AnnotationData]
+ ) -> None:
+ """Add inferred annotations to variables without explicit annotations."""
+ variables = self.variables
+ for name, annotation in annotations.items():
+ data = variables.get(name)
+ if data is None:
+ variables[name] = VariableData(annotation_data=annotation)
+ elif data.annotation_data is None:
+ variables[name] = replace(data, annotation_data=annotation)
+
@classmethod
def from_graph(
cls,
diff --git a/marimo/_ast/type_inference.py b/marimo/_ast/type_inference.py
new file mode 100644
index 0000000000..f985435658
--- /dev/null
+++ b/marimo/_ast/type_inference.py
@@ -0,0 +1,631 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Infer parameter annotations for generated cell signatures."""
+
+from __future__ import annotations
+
+import ast
+import warnings
+from collections import defaultdict
+from dataclasses import dataclass
+from heapq import heapify, heappop, heappush
+from pathlib import Path
+from typing import TYPE_CHECKING, Literal, Protocol, cast
+
+from marimo import _loggers
+from marimo._ast.variables import BUILTINS
+from marimo._ast.visitor import AnnotationData, Name, ScopedVisitor
+from marimo._utils.strings import standardize_annotation_quotes
+
+if TYPE_CHECKING:
+ from marimo._ast.cell import CellImpl
+ from marimo._ast.toplevel import TopLevelExtraction, TopLevelStatus
+
+LOGGER = _loggers.marimo_logger()
+
+TypeInferenceMode = Literal["off", "jedi"]
+
+# A fixed-length tuple longer than this is written as `tuple[T, ...]`.
+MAX_TUPLE_ELEMENTS = 3
+
+# Omit annotations containing a union wider than this.
+MAX_UNION_MEMBERS = 3
+
+# Omit annotations containing an unconstrained type.
+_BROAD_TYPES = frozenset({"object", "Any"})
+
+DEFAULT_LINE_LENGTH = 79
+
+# Jedi reports notebook-defined classes under this module name.
+PROBE_MODULE_NAME = "__marimo_probe__"
+
+_BUILTINS = "builtins"
+
+_TYPING_TO_BUILTIN = {
+ "List": "list",
+ "Dict": "dict",
+ "Tuple": "tuple",
+ "Set": "set",
+ "FrozenSet": "frozenset",
+ "Type": "type",
+}
+
+
+@dataclass(frozen=True)
+class Inferred:
+ """One value a backend inferred for a definition."""
+
+ # Dotted path of the value's class, such as `pandas.core.frame.DataFrame`.
+ full_name: str
+ # `instance`, `class`, `function`, or `module`.
+ kind: str
+ # The backend's spelling of the type with generic parameters, if any.
+ hint: str | None = None
+
+
+class Backend(Protocol):
+ def infer_definitions(
+ self, source: str, names: set[Name], search_path: Path | None
+ ) -> dict[Name, list[Inferred]]:
+ """Infer every module-level definition of each name in `source`.
+
+ Omit a name if any of its definitions cannot be inferred.
+ """
+ ...
+
+ def resolve(
+ self, source: str, expressions: list[str], search_path: Path | None
+ ) -> list[Inferred | None]:
+ """Resolve expressions statically after the module source."""
+ ...
+
+
+def infer_annotations(
+ extraction: TopLevelExtraction,
+ setup_cell: CellImpl | None,
+ *,
+ filename: str | None,
+ mode: TypeInferenceMode,
+ line_length: int = DEFAULT_LINE_LENGTH,
+ backend: Backend | None = None,
+) -> dict[Name, AnnotationData]:
+ """Infer annotations for variables that cells read as parameters."""
+ if mode == "off":
+ return {}
+ names = candidate_names(extraction)
+ if not names:
+ return {}
+ if backend is None:
+ backend = JediBackend()
+
+ source = probe_module(extraction, setup_cell)
+ search_path = Path(filename).parent if filename else None
+ inferred = backend.infer_definitions(source, names, search_path)
+ if not inferred:
+ return {}
+
+ spellings = _ClassAnnotationResolver(
+ extraction, setup_cell, backend, source, search_path
+ )
+ # `unshadowed` only covers cell definitions, so also exclude setup
+ # definitions, which can rebind builtins.
+ setup_defs = set(setup_cell.defs) if setup_cell is not None else set()
+ scope = _Scope(
+ allowed_refs=extraction.allowed_refs,
+ builtins=extraction.unshadowed - setup_defs,
+ )
+ annotations: dict[Name, AnnotationData] = {}
+ for name in sorted(inferred):
+ node = _declared_type(inferred[name], scope, spellings)
+ if node is None:
+ continue
+ annotation = _annotation(node)
+ if len(f" {name}: {annotation.repr},") > line_length:
+ continue
+ annotations[name] = annotation
+
+ # Python evaluates signatures in file order before cells run, so each
+ # signature needs access to its types.
+ available = scope.builtins | setup_defs
+ for status in extraction:
+ if status.is_toplevel:
+ available.update(status.defs)
+ elif status.is_cell:
+ for name in (status.refs - status.defs) & annotations.keys():
+ if annotations[name].refs - available:
+ del annotations[name]
+ return annotations
+
+
+@dataclass(frozen=True)
+class _Scope:
+ """Names an annotation in the generated file can use."""
+
+ # Every name in scope at module level.
+ allowed_refs: set[Name]
+ # Builtin classes that nothing in the notebook rebinds.
+ builtins: set[Name]
+
+
+def candidate_names(extraction: TopLevelExtraction) -> set[Name]:
+ """Find public, unannotated variables read by other cells."""
+ variables = extraction.variables
+ names: set[Name] = set()
+ for status in extraction:
+ if status.is_unparsable:
+ continue
+ for name in status.defs:
+ data = variables.get(name)
+ # Compilation excludes private names from variable data.
+ if data is None:
+ continue
+ if data.annotation_data is not None or data.language == "sql":
+ continue
+ if name in extraction.allowed_refs:
+ continue
+ if name not in extraction.used_refs:
+ continue
+ names.add(name)
+ return names
+
+
+def module_aliases(setup_cell: CellImpl | None) -> dict[Name, str]:
+ """Collect module aliases from setup-cell imports."""
+ if setup_cell is None:
+ return {}
+ aliases: dict[Name, str] = {}
+ for name, entries in setup_cell.variable_data.items():
+ import_data = entries[0].import_data
+ # A from-import can bind a module or an object.
+ if import_data is not None and import_data.imported_symbol is None:
+ aliases[name] = import_data.module
+ return aliases
+
+
+def probe_module(
+ extraction: TopLevelExtraction, setup_cell: CellImpl | None
+) -> str:
+ """Combine setup and cells in dependency order into one module."""
+ blocks: list[str] = []
+ if setup_cell is not None and setup_cell.code.strip():
+ blocks.append(setup_cell.code)
+ for status in _dependency_order(extraction):
+ assert status._cell is not None
+ # The compiler replaces non-breaking spaces in cell source.
+ tree = ast.parse(status._cell.code)
+ ScopedVisitor("cell_" + status.cell_id).visit(tree)
+ blocks.append(ast.unparse(tree))
+ body = "\n".join(blocks)
+ if body and not body.endswith("\n"):
+ body += "\n"
+ return body
+
+
+def _dependency_order(extraction: TopLevelExtraction) -> list[TopLevelStatus]:
+ """Order cells by dependency, using file order to break ties."""
+ statuses = [status for status in extraction if not status.is_unparsable]
+ position = {id(status): idx for idx, status in enumerate(statuses)}
+
+ definer: dict[Name, TopLevelStatus] = {}
+ for status in statuses:
+ for name in status.defs:
+ definer.setdefault(name, status)
+
+ children: dict[int, list[TopLevelStatus]] = defaultdict(list)
+ in_degree = {id(status): 0 for status in statuses}
+ for status in statuses:
+ parents = {
+ id(definer[ref]): definer[ref]
+ for ref in status.refs
+ if ref in definer and definer[ref] is not status
+ }
+ in_degree[id(status)] = len(parents)
+ for parent in parents.values():
+ children[id(parent)].append(status)
+
+ heap = [
+ (position[id(status)], status)
+ for status in statuses
+ if in_degree[id(status)] == 0
+ ]
+ heapify(heap)
+ ordered: list[TopLevelStatus] = []
+ while heap:
+ _, status = heappop(heap)
+ ordered.append(status)
+ for child in children[id(status)]:
+ in_degree[id(child)] -= 1
+ if in_degree[id(child)] == 0:
+ heappush(heap, (position[id(child)], child))
+
+ if len(ordered) < len(statuses):
+ # Preserve file order for cycles and their dependents.
+ emitted = {id(status) for status in ordered}
+ ordered.extend(s for s in statuses if id(s) not in emitted)
+ return ordered
+
+
+def definition_sites(
+ source: str, names: set[Name]
+) -> dict[Name, list[tuple[int, int]]]:
+ """Locate module-level bindings, excluding names with unsupported bindings."""
+ sites: dict[Name, list[tuple[int, int]]] = defaultdict(list)
+ unsupported: set[Name] = set()
+
+ def visit(node: ast.AST) -> None:
+ if isinstance(
+ node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
+ ):
+ unsupported.add(node.name)
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
+ unsupported.update(
+ alias.asname or alias.name.split(".")[0]
+ for alias in node.names
+ )
+ elif isinstance(node, (ast.MatchAs, ast.MatchStar, ast.ExceptHandler)):
+ if node.name is not None:
+ unsupported.add(node.name)
+ elif isinstance(node, ast.MatchMapping) and node.rest is not None:
+ unsupported.add(node.rest)
+ elif isinstance(
+ node, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
+ ):
+ # Comprehension walruses bind in the enclosing scope.
+ unsupported.update(
+ child.target.id
+ for child in ast.walk(node)
+ if isinstance(child, ast.NamedExpr)
+ and isinstance(child.target, ast.Name)
+ )
+ if isinstance(node, _SCOPES):
+ return
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
+ if node.id in names:
+ sites[node.id].append((node.lineno, node.col_offset))
+ for child in ast.iter_child_nodes(node):
+ visit(child)
+
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
+ return {}
+ visit(tree)
+ return {
+ name: positions
+ for name, positions in sites.items()
+ if name not in unsupported
+ }
+
+
+_SCOPES = (
+ ast.FunctionDef,
+ ast.AsyncFunctionDef,
+ ast.ClassDef,
+ ast.Lambda,
+ ast.ListComp,
+ ast.SetComp,
+ ast.DictComp,
+ ast.GeneratorExp,
+)
+
+
+class JediBackend:
+ """Infer types with Jedi against the running interpreter."""
+
+ def infer_definitions(
+ self, source: str, names: set[Name], search_path: Path | None
+ ) -> dict[Name, list[Inferred]]:
+ sites = definition_sites(source, names)
+ if not sites:
+ return {}
+ script = self._script(source, search_path)
+ if script is None:
+ return {}
+ inferred: dict[Name, list[Inferred]] = {}
+ for name, positions in sites.items():
+ values: list[Inferred] = []
+ for line, column in positions:
+ found = self._infer(script, line, column)
+ if not found:
+ break
+ values.extend(found)
+ else:
+ inferred[name] = values
+ return inferred
+
+ def resolve(
+ self, source: str, expressions: list[str], search_path: Path | None
+ ) -> list[Inferred | None]:
+ if not expressions:
+ return []
+ first_line = source.count("\n") + 1
+ script = self._script(
+ source + "\n".join(expressions) + "\n", search_path
+ )
+ if script is None:
+ return [None] * len(expressions)
+ resolved: list[Inferred | None] = []
+ for offset, expression in enumerate(expressions):
+ found = self._infer(script, first_line + offset, len(expression))
+ resolved.append(found[0] if found else None)
+ return resolved
+
+ @staticmethod
+ def _script(source: str, search_path: Path | None) -> object | None:
+ # Defer importing Jedi until inference is enabled.
+ import jedi # type: ignore
+
+ script: object
+ try:
+ if search_path is None:
+ script = jedi.Script(source)
+ else:
+ script = jedi.Script(
+ source,
+ path=str(search_path / f"{PROBE_MODULE_NAME}.py"),
+ project=jedi.Project(str(search_path)),
+ )
+ return script
+ except Exception as e:
+ LOGGER.debug("jedi could not load the notebook: %s", e)
+ return None
+
+ @staticmethod
+ def _infer(script: object, line: int, column: int) -> list[Inferred]:
+ values: list[Inferred] = []
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ try:
+ found = cast("list[object]", script.infer(line, column)) # type: ignore[attr-defined]
+ except Exception as e:
+ LOGGER.debug(
+ "jedi inference failed at %s:%s: %s", line, column, e
+ )
+ return []
+ for definition in found:
+ full_name = getattr(definition, "full_name", None)
+ if not full_name:
+ continue
+ # A failed hint still leaves the class in `full_name`.
+ try:
+ hint = cast("str | None", definition.get_type_hint()) # type: ignore[attr-defined]
+ except Exception:
+ hint = None
+ values.append(
+ Inferred(
+ full_name=full_name,
+ kind=cast(str, getattr(definition, "type", "")),
+ hint=hint,
+ )
+ )
+ return values
+
+
+class _ClassAnnotationResolver:
+ """Resolve classes to annotations available in the notebook."""
+
+ def __init__(
+ self,
+ extraction: TopLevelExtraction,
+ setup_cell: CellImpl | None,
+ backend: Backend,
+ source: str,
+ search_path: Path | None,
+ ) -> None:
+ self._allowed = extraction.allowed_refs
+ self._aliases = module_aliases(setup_cell)
+ self._backend = backend
+ self._source = source
+ self._search_path = search_path
+ self._cache: dict[str, ast.expr | None] = {}
+
+ def spell(self, full_name: str) -> ast.expr | None:
+ if full_name in self._cache:
+ return self._cache[full_name]
+ spelling = self._spell(full_name)
+ self._cache[full_name] = spelling
+ return spelling
+
+ def _spell(self, full_name: str) -> ast.expr | None:
+ module, _, class_name = full_name.rpartition(".")
+ candidates: list[str] = []
+ if class_name in self._allowed:
+ candidates.append(class_name)
+ for alias, alias_module in sorted(self._aliases.items()):
+ if module == alias_module or module.startswith(alias_module + "."):
+ candidates.append(f"{alias}.{class_name}")
+ if not candidates:
+ return None
+ resolved = self._backend.resolve(
+ self._source, candidates, self._search_path
+ )
+ for candidate, found in zip(candidates, resolved, strict=True):
+ if (
+ found is not None
+ and found.kind == "class"
+ and found.full_name == full_name
+ ):
+ return ast.parse(candidate, mode="eval").body
+ return None
+
+
+def _declared_type(
+ values: list[Inferred], scope: _Scope, spellings: _ClassAnnotationResolver
+) -> ast.expr | None:
+ """Build a variable's annotation from its inferred values."""
+ members: list[ast.expr] = []
+ for value in values:
+ if value.kind != "instance":
+ return None
+ if value.full_name.rpartition(".")[2].startswith("_"):
+ continue
+ member = _member_type(value, scope, spellings)
+ if member is None:
+ return None
+ members.append(member)
+ if not members:
+ return None
+ node = cast(ast.expr, _SimplifyTypeAnnotation().visit(_union(members)))
+ if _names_in(node) - scope.allowed_refs or _is_broad(node):
+ return None
+ return node
+
+
+def _is_broad(node: ast.expr) -> bool:
+ """True when the type names `object` or `Any`, or a union is too wide."""
+ if _names_in(node) & _BROAD_TYPES:
+ return True
+ return any(
+ isinstance(n, ast.BinOp)
+ and isinstance(n.op, ast.BitOr)
+ and len(_union_members(n)) > MAX_UNION_MEMBERS
+ for n in ast.walk(node)
+ )
+
+
+def _member_type(
+ value: Inferred, scope: _Scope, spellings: _ClassAnnotationResolver
+) -> ast.expr | None:
+ module, _, class_name = value.full_name.rpartition(".")
+ if module != _BUILTINS:
+ return spellings.spell(value.full_name)
+ if class_name == "NoneType":
+ return ast.Constant(value=None)
+ if class_name not in scope.builtins:
+ return None
+ bare = ast.Name(id=class_name, ctx=ast.Load())
+ hinted = lower_hint(value.hint) if value.hint else None
+ # An unavailable or shadowed nested type still permits the bare
+ # container annotation.
+ if (
+ hinted is None
+ or _names_in(hinted) - scope.allowed_refs
+ or _names_in(hinted) & (BUILTINS - scope.builtins)
+ ):
+ return bare
+ return hinted
+
+
+def lower_hint(hint: str) -> ast.expr | None:
+ """Rewrite a Jedi type hint with builtin generics and `|` unions."""
+ try:
+ node = ast.parse(hint, mode="eval").body
+ except SyntaxError:
+ return None
+ return cast(
+ ast.expr, _SimplifyTypeAnnotation().visit(_LowerTyping().visit(node))
+ )
+
+
+def _annotation(node: ast.expr) -> AnnotationData:
+ return AnnotationData(
+ standardize_annotation_quotes(ast.unparse(node)), _names_in(node)
+ )
+
+
+def _names_in(node: ast.expr) -> set[Name]:
+ return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
+
+
+def _union_members(node: ast.expr) -> list[ast.expr]:
+ """Flatten `A | B | C` into its members."""
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
+ return _union_members(node.left) + _union_members(node.right)
+ return [node]
+
+
+def _union(members: list[ast.expr]) -> ast.expr:
+ """Join distinct types with `|`, preserving their order."""
+ distinct: list[ast.expr] = []
+ for member in members:
+ if all(ast.dump(member) != ast.dump(seen) for seen in distinct):
+ distinct.append(member)
+ union = distinct[0]
+ for extra in distinct[1:]:
+ union = ast.BinOp(left=union, op=ast.BitOr(), right=extra)
+ return union
+
+
+class _LowerTyping(ast.NodeTransformer):
+ """Convert typing generics to builtin annotation syntax."""
+
+ def visit_Name(self, node: ast.Name) -> ast.expr:
+ if node.id in _TYPING_TO_BUILTIN:
+ return ast.Name(id=_TYPING_TO_BUILTIN[node.id], ctx=ast.Load())
+ if node.id == "NoneType":
+ return ast.Constant(value=None)
+ return node
+
+ def visit_Subscript(self, node: ast.Subscript) -> ast.expr:
+ self.generic_visit(node)
+ if not isinstance(node.value, ast.Name):
+ return node
+ members = (
+ node.slice.elts
+ if isinstance(node.slice, ast.Tuple)
+ else [node.slice]
+ )
+ if node.value.id == "Union":
+ return _union(members)
+ if node.value.id == "Optional":
+ return _union([*members, ast.Constant(value=None)])
+ return node
+
+
+class _SimplifyTypeAnnotation(ast.NodeTransformer):
+ """Widen literals and long tuples, and deduplicate unions."""
+
+ def visit_BinOp(self, node: ast.BinOp) -> ast.expr:
+ self.generic_visit(node)
+ if isinstance(node.op, ast.BitOr):
+ return _union(_union_members(node))
+ return node
+
+ def visit_Subscript(self, node: ast.Subscript) -> ast.expr:
+ self.generic_visit(node)
+ if not isinstance(node.value, ast.Name):
+ return node
+ members = (
+ node.slice.elts
+ if isinstance(node.slice, ast.Tuple)
+ else [node.slice]
+ )
+ if node.value.id == "Literal":
+ widened: list[ast.expr] = []
+ for member in members:
+ wide = _widen_literal_member(member)
+ if wide is None:
+ return node
+ widened.append(wide)
+ return _union(widened)
+ if node.value.id == "tuple" and len(members) > MAX_TUPLE_ELEMENTS:
+ if any(
+ isinstance(m, ast.Constant) and m.value is Ellipsis
+ for m in members
+ ):
+ return node
+ return ast.Subscript(
+ value=node.value,
+ slice=ast.Tuple(
+ elts=[_union(members), ast.Constant(value=Ellipsis)],
+ ctx=ast.Load(),
+ ),
+ ctx=ast.Load(),
+ )
+ return node
+
+
+def _widen_literal_member(member: ast.expr) -> ast.expr | None:
+ if isinstance(member, ast.UnaryOp) and isinstance(member.op, ast.USub):
+ member = member.operand
+ if isinstance(member, ast.Constant):
+ value = member.value
+ if value is None:
+ return ast.Constant(value=None)
+ # Check bool before int, since True is an int.
+ if isinstance(value, bool):
+ return ast.Name(id="bool", ctx=ast.Load())
+ return ast.Name(id=type(value).__name__, ctx=ast.Load())
+ # `Literal[Color.RED]` widens to the enum type `Color`.
+ if isinstance(member, ast.Attribute):
+ return member.value
+ return None
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index f6fb3fa3a5..ed786cb36d 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -1584,6 +1584,8 @@ def check(
ignore_scripts=ignore_scripts,
formatter=formatter,
lint_config=lint_config,
+ infer_types=None,
+ line_length=None,
)
# Get counts from linter (fix happens automatically during streaming)
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index c1e799cfc9..1346385dbd 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -232,6 +232,7 @@ class FormattingConfig(TypedDict):
"""
line_length: int
+ infer_types: NotRequired[Literal["off", "jedi"]]
@dataclass
diff --git a/marimo/_config/config_schema.py b/marimo/_config/config_schema.py
index fa26dc7fb7..b147b4b323 100644
--- a/marimo/_config/config_schema.py
+++ b/marimo/_config/config_schema.py
@@ -301,6 +301,10 @@ class FormattingConfig(Config, kw_only=True):
"""Configuration for code formatting."""
line_length: Annotated[int, Meta(description="max line length")] = 79
+ infer_types: Annotated[
+ Literal["off", "jedi"],
+ Meta(description="infer type annotations for cell parameters on save"),
+ ] = "off"
class ServerConfig(Config, kw_only=True):
diff --git a/marimo/_convert/converters.py b/marimo/_convert/converters.py
index 8c7c4ebeee..9feb71f31e 100644
--- a/marimo/_convert/converters.py
+++ b/marimo/_convert/converters.py
@@ -11,6 +11,7 @@ from marimo._schemas.serialization import (
)
if TYPE_CHECKING:
+ from marimo._ast.type_inference import TypeInferenceMode
from marimo._convert.markdown.flavor.base import (
MarkdownFlavor,
MarkdownFlavorName,
@@ -39,11 +40,15 @@ class MarimoConverterIntermediate:
return convert_from_ir_to_markdown(self.ir, filename, flavor=flavor)
- def to_py(self) -> str:
- """Convert to python format."""
+ def to_py(
+ self, *, infer_types: TypeInferenceMode = "off", line_length: int = 79
+ ) -> str:
+ """Convert the notebook to Python."""
from marimo._ast.codegen import generate_filecontents_from_ir
- return generate_filecontents_from_ir(self.ir)
+ return generate_filecontents_from_ir(
+ self.ir, infer_types=infer_types, line_length=line_length
+ )
def to_ir(self) -> NotebookSerialization:
"""Convert to notebook IR."""
diff --git a/marimo/_lint/__init__.py b/marimo/_lint/__init__.py
index 2e885c80b1..b5dd280284 100644
--- a/marimo/_lint/__init__.py
+++ b/marimo/_lint/__init__.py
@@ -12,6 +12,7 @@ from marimo._utils.files import async_expand_file_patterns
if TYPE_CHECKING:
from collections.abc import Callable
+ from marimo._ast.type_inference import TypeInferenceMode
from marimo._config.config import LintConfig
@@ -64,6 +65,8 @@ def run_check(
ignore_scripts: bool = False,
formatter: str = "full",
lint_config: LintConfig | None = None,
+ infer_types: TypeInferenceMode | None = "off",
+ line_length: int | None = 79,
) -> Linter:
"""Run linting checks on files matching patterns (CLI entry point).
@@ -78,6 +81,8 @@ def run_check(
ignore_scripts: Whether to ignore files not recognizable as marimo notebooks
formatter: Output format for diagnostics ("full" or "json")
lint_config: Optional lint rule selection config
+ infer_types: Inference backend, or None to use notebook configuration.
+ line_length: Parameter line width, or None to use notebook configuration.
Returns:
Linter with per-file status and diagnostics
@@ -92,6 +97,8 @@ def run_check(
ignore_scripts=ignore_scripts,
formatter=formatter,
lint_config=lint_config,
+ infer_types=infer_types,
+ line_length=line_length,
)
linter.run_streaming(files_to_check)
return linter
diff --git a/marimo/_lint/linter.py b/marimo/_lint/linter.py
index 4104cd6797..d2e86636e8 100644
--- a/marimo/_lint/linter.py
+++ b/marimo/_lint/linter.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING
from marimo._ast.load import get_notebook_status
from marimo._ast.parse import MarimoFileError
from marimo._cli.print import red
+from marimo._config.manager import get_default_config_manager
from marimo._convert.converters import MarimoConvert
from marimo._lint.diagnostic import Diagnostic, Severity
from marimo._lint.formatters import LintResultJSON
@@ -23,6 +24,7 @@ from marimo._utils.generated_with import (
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Callable, Iterator
+ from marimo._ast.type_inference import TypeInferenceMode
from marimo._config.config import LintConfig
from marimo._lint.rules.base import LintRule
@@ -73,6 +75,8 @@ class Linter:
ignore_scripts: bool = False,
formatter: str = "full",
lint_config: LintConfig | None = None,
+ infer_types: TypeInferenceMode | None = "off",
+ line_length: int | None = 79,
):
if rules is not None:
self.rule_engine = RuleEngine(rules, early_stopping)
@@ -85,6 +89,9 @@ class Linter:
self.unsafe_fixes = unsafe_fixes
self.ignore_scripts = ignore_scripts
self.formatter = formatter
+ # None inherits notebook configuration, while "off" overrides it.
+ self.infer_types = infer_types
+ self.line_length = line_length
self.files: list[FileStatus] = []
self._lint_config = lint_config
self._early_stopping = early_stopping
@@ -281,7 +288,11 @@ class Linter:
@staticmethod
def _generate_file_contents_from_notebook(
- notebook: NotebookSerialization, filename: str
+ notebook: NotebookSerialization,
+ filename: str,
+ *,
+ infer_types: TypeInferenceMode = "off",
+ line_length: int = 79,
) -> str:
"""Generate file contents from notebook serialization."""
converter = MarimoConvert.from_ir(notebook)
@@ -290,10 +301,17 @@ class Linter:
if filename.endswith((".md", ".qmd")):
return converter.to_markdown()
else:
- return converter.to_py()
+ return converter.to_py(
+ infer_types=infer_types, line_length=line_length
+ )
@staticmethod
- def _generate_file_contents(file_status: FileStatus) -> str:
+ def _generate_file_contents(
+ file_status: FileStatus,
+ *,
+ infer_types: TypeInferenceMode = "off",
+ line_length: int = 79,
+ ) -> str:
"""Generate file contents from notebook serialization."""
if file_status.notebook is None:
raise ValueError(
@@ -301,7 +319,10 @@ class Linter:
)
return Linter._generate_file_contents_from_notebook(
- file_status.notebook, file_status.file
+ file_status.notebook,
+ file_status.file,
+ infer_types=infer_types,
+ line_length=line_length,
)
def run_streaming(
@@ -375,9 +396,24 @@ class Linter:
modified_notebook, diagnostics
)
+ infer_types = self.infer_types
+ line_length = self.line_length
+ if infer_types is None or line_length is None:
+ config = get_default_config_manager(
+ current_path=file_status.file
+ ).get_config(hide_secrets=False)
+ formatting = config["formatting"]
+ if infer_types is None:
+ infer_types = formatting.get("infer_types", "off")
+ if line_length is None:
+ line_length = formatting["line_length"]
+
# Generate file contents from (possibly modified) notebook
generated_contents = Linter._generate_file_contents_from_notebook(
- modified_notebook, file_status.file
+ modified_notebook,
+ file_status.file,
+ infer_types=infer_types,
+ line_length=line_length,
)
# Only write if content changed (excluding __generated_with differences)
diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.py
index f3b408337d..524b6dab8a 100644
--- a/marimo/_session/notebook/file_manager.py
+++ b/marimo/_session/notebook/file_manager.py
@@ -35,6 +35,8 @@ LOGGER = _loggers.marimo_logger()
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
+ from marimo._ast.type_inference import TypeInferenceMode
+ from marimo._config.manager import MarimoConfigManager
from marimo._server.models.models import (
CopyNotebookRequest,
SaveNotebookRequest,
@@ -72,6 +74,8 @@ class AppFileManager:
# Configuration defaults
self._defaults = defaults or AppDefaults()
+ self.config_reader: MarimoConfigManager | None = None
+
# Load the app
self.app = self._load_app(self.path)
@@ -93,6 +97,22 @@ class AppFileManager:
# Foreground writes supersede queued autosaves.
self._autosave_generation = 0
+ @property
+ def infer_types(self) -> TypeInferenceMode:
+ """Read the configured inference backend."""
+ if self.config_reader is None:
+ return "off"
+ formatting = self.config_reader.get_config().get("formatting", {})
+ return formatting.get("infer_types", "off")
+
+ @property
+ def line_length(self) -> int:
+ """Read the configured annotation line length."""
+ if self.config_reader is None:
+ return 79
+ formatting = self.config_reader.get_config().get("formatting", {})
+ return int(formatting.get("line_length", 79))
+
@property
def filename(self) -> str | None:
"""Get the current filename as a Path object."""
@@ -226,6 +246,8 @@ class AppFileManager:
notebook=notebook,
persist=persist,
previous_path=previous_path,
+ infer_types=self.infer_types,
+ line_length=self.line_length,
)
# If this is a new unnamed notebook, update the filename
if self._is_unnamed():
@@ -561,7 +583,9 @@ class AppFileManager:
"""
from marimo._convert.converters import MarimoConvert
- return MarimoConvert.from_ir(self.app.to_ir()).to_py()
+ return MarimoConvert.from_ir(self.app.to_ir()).to_py(
+ infer_types=self.infer_types, line_length=self.line_length
+ )
def _is_unnamed(self) -> bool:
"""Check if notebook is unnamed.
diff --git a/marimo/_session/notebook/serializer.py b/marimo/_session/notebook/serializer.py
index f9d8ba4998..29845dde23 100644
--- a/marimo/_session/notebook/serializer.py
+++ b/marimo/_session/notebook/serializer.py
@@ -4,7 +4,7 @@
from __future__ import annotations
from pathlib import Path
-from typing import Protocol
+from typing import TYPE_CHECKING, Protocol
from marimo._ast.parse import MarimoFileError, is_non_marimo_python_script
from marimo._schemas.serialization import (
@@ -12,15 +12,26 @@ from marimo._schemas.serialization import (
NotebookSerializationV1,
)
+if TYPE_CHECKING:
+ from marimo._ast.type_inference import TypeInferenceMode
+
class NotebookSerializer(Protocol):
"""Protocol for notebook format handlers."""
- def serialize(self, notebook: NotebookSerializationV1) -> str:
+ def serialize(
+ self,
+ notebook: NotebookSerializationV1,
+ *,
+ infer_types: TypeInferenceMode = "off",
+ line_length: int = 79,
+ ) -> str:
"""Convert notebook IR to the target format.
Args:
notebook: Notebook in intermediate representation
+ infer_types: Inference backend for formats with cell signatures.
+ line_length: Maximum parameter line width for inferred annotations.
Returns:
Serialized notebook content as string
@@ -56,14 +67,22 @@ class NotebookSerializer(Protocol):
class PythonNotebookSerializer(NotebookSerializer):
"""Handler for Python (.py) notebook files."""
- def serialize(self, notebook: NotebookSerializationV1) -> str:
+ def serialize(
+ self,
+ notebook: NotebookSerializationV1,
+ *,
+ infer_types: TypeInferenceMode = "off",
+ line_length: int = 79,
+ ) -> str:
"""Serialize notebook to Python format.
Handles header preservation when converting from other formats.
"""
from marimo._ast.codegen import generate_filecontents_from_ir
- return generate_filecontents_from_ir(notebook)
+ return generate_filecontents_from_ir(
+ notebook, infer_types=infer_types, line_length=line_length
+ )
def deserialize(
self, content: str, filepath: str | None = None
@@ -86,8 +105,16 @@ class PythonNotebookSerializer(NotebookSerializer):
class MarkdownNotebookSerializer(NotebookSerializer):
"""Handler for Markdown (.md) notebook files."""
- def serialize(self, notebook: NotebookSerializationV1) -> str:
+ def serialize(
+ self,
+ notebook: NotebookSerializationV1,
+ *,
+ infer_types: TypeInferenceMode = "off",
+ line_length: int = 79,
+ ) -> str:
"""Serialize notebook to Markdown format."""
+ # Markdown has no cell signatures to annotate.
+ del infer_types, line_length
from marimo._convert.markdown import convert_from_ir_to_markdown
return convert_from_ir_to_markdown(notebook)
diff --git a/marimo/_session/notebook/writer.py b/marimo/_session/notebook/writer.py
index 112f568b3e..aa1d86b44e 100644
--- a/marimo/_session/notebook/writer.py
+++ b/marimo/_session/notebook/writer.py
@@ -32,6 +32,7 @@ if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
from pathlib import Path
+ from marimo._ast.type_inference import TypeInferenceMode
from marimo._messaging.notebook.document import NotebookCell
LOGGER = _loggers.marimo_logger()
@@ -83,6 +84,8 @@ class NotebookWriter:
notebook: NotebookSerializationV1,
persist: bool,
previous_path: Path | None = None,
+ infer_types: TypeInferenceMode = "off",
+ line_length: int = 79,
) -> str:
"""Serialize `notebook` for `path` and, if `persist`, write it.
@@ -131,7 +134,9 @@ class NotebookWriter:
valid=notebook.valid,
filename=str(path),
)
- contents = handler.serialize(notebook)
+ contents = handler.serialize(
+ notebook, infer_types=infer_types, line_length=line_length
+ )
if persist:
if self.content_matches_last_save(contents):
diff --git a/marimo/_session/session.py b/marimo/_session/session.py
index 5e099c16fd..e951fb246f 100644
--- a/marimo/_session/session.py
+++ b/marimo/_session/session.py
@@ -246,6 +246,8 @@ class SessionImpl(Session):
self.initialization_id = initialization_id
self._stable_id = mint(StableSessionId, "sess")
self.app_file_manager = app_file_manager
+ # Read configuration on each save to pick up later edits.
+ self.app_file_manager.config_reader = config_manager
self.room = Room()
self.connection_generation = 0
self._kernel_manager = kernel_manager
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 3055ca6684..b022c93c84 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -2664,6 +2664,10 @@ components:
description: "Configuration for code formatting.\n\n **Keys.**\n\n - `line_length`:\
\ max line length"
properties:
+ infer_types:
+ enum:
+ - jedi
+ - 'off'
line_length:
type: integer
required:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index f0c639cdec..cf40b5ec05 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -5368,6 +5368,8 @@ export interface components {
* - `line_length`: max line length
*/
FormattingConfig: {
+ /** @enum {unknown} */
+ infer_types?: "jedi" | "off";
line_length: number;
};
/**
diff --git a/pyproject.toml b/pyproject.toml
index 70c772917c..c299a265a3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -213,6 +213,7 @@ test-optional = [
# For testing starrocks
"starrocks>=1.3.0",
"pandas>=1.5.3",
+ "pandas-stubs>=1.5.3.230321",
"hvplot~=0.11.3",
"geopandas>=1.1.0",
# Ibis 12 needs DuckDB 1.x; remove after a compatible Ibis release.
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index dcc57d84f2..3625a1b6b2 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -793,6 +793,28 @@ app._unparsable_cell(
result = codegen.generate_app_constructor(config)
assert result == 'app = marimo.App(auto_download=["html"])'
+ @staticmethod
+ @pytest.mark.parametrize(
+ "title",
+ ['He said "hi"', "it's", "both \"double\" and 'single'", "two\nlines"],
+ )
+ def test_generate_app_constructor_quotes_strings(title: str) -> None:
+ result = codegen.generate_app_constructor(_AppConfig(app_title=title))
+ (call,) = ast.parse(result).body
+ assert isinstance(call, ast.Assign)
+ assert isinstance(call.value, ast.Call)
+ (keyword,) = call.value.keywords
+ assert keyword.arg == "app_title"
+ assert ast.literal_eval(keyword.value) == title
+
+ @staticmethod
+ def test_generate_app_constructor_prefers_double_quotes() -> None:
+ config = _AppConfig(app_title="plain", css_file=r"a\b.css")
+ result = codegen.generate_app_constructor(config)
+ assert result == (
+ 'app = marimo.App(app_title="plain", css_file="a\\\\b.css")'
+ )
+
@staticmethod
def test_generate_file_contents_overwrite_default_cell_names() -> None:
contents = wrap_generate_filecontents(
diff --git a/tests/_ast/test_type_inference.py b/tests/_ast/test_type_inference.py
new file mode 100644
index 0000000000..091bf06d77
--- /dev/null
+++ b/tests/_ast/test_type_inference.py
@@ -0,0 +1,853 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+import importlib.util
+import runpy
+from typing import TYPE_CHECKING
+
+import pytest
+
+from marimo._ast import codegen
+from marimo._ast.cell import CellConfig
+from marimo._ast.codegen import pop_setup_cell
+from marimo._ast.names import SETUP_CELL_NAME
+from marimo._ast.toplevel import TopLevelExtraction
+from marimo._ast.type_inference import (
+ Inferred,
+ JediBackend,
+ candidate_names,
+ definition_sites,
+ infer_annotations,
+ lower_hint,
+ module_aliases,
+ probe_module,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from marimo._ast.cell import CellImpl
+
+
+def make_extraction(
+ codes: list[str], setup: str | None = None
+) -> tuple[TopLevelExtraction, CellImpl | None]:
+ names = ["_" for _ in codes]
+ configs = [CellConfig() for _ in codes]
+ if setup is not None:
+ codes = [setup, *codes]
+ names = [SETUP_CELL_NAME, *names]
+ configs = [CellConfig(), *configs]
+ setup_cell = pop_setup_cell(codes, names, configs)
+ toplevel_defs = set(setup_cell.defs) if setup_cell else set()
+ return TopLevelExtraction(codes, names, configs, toplevel_defs), setup_cell
+
+
+def instance(full_name: str, hint: str | None = None) -> Inferred:
+ return Inferred(full_name, "instance", hint)
+
+
+class FakeBackend:
+ """Return configured inferences and resolve known class aliases."""
+
+ def __init__(
+ self,
+ inferred: dict[str, list[Inferred]],
+ classes: dict[str, str] | None = None,
+ ) -> None:
+ self.inferred = inferred
+ self.classes = classes or {}
+ self.sources: list[str] = []
+ self.resolved: list[str] = []
+ self.search_paths: list[Path | None] = []
+
+ def infer_definitions(
+ self, source: str, names: set[str], search_path: Path | None
+ ) -> dict[str, list[Inferred]]:
+ self.sources.append(source)
+ self.search_paths.append(search_path)
+ return {n: v for n, v in self.inferred.items() if n in names}
+
+ def resolve(
+ self, source: str, expressions: list[str], search_path: Path | None
+ ) -> list[Inferred | None]:
+ del source, search_path
+ self.resolved.extend(expressions)
+ return [
+ Inferred(self.classes[e], "class") if e in self.classes else None
+ for e in expressions
+ ]
+
+
+def generate(
+ codes: list[str],
+ setup: str | None = None,
+ *,
+ backend: FakeBackend | None = None,
+ infer_types: str = "jedi",
+ monkeypatch: pytest.MonkeyPatch | None = None,
+) -> str:
+ names = ["_" for _ in codes]
+ configs = [CellConfig() for _ in codes]
+ if setup is not None:
+ codes = [setup, *codes]
+ names = [SETUP_CELL_NAME, *names]
+ configs = [CellConfig(), *configs]
+ if backend is not None:
+ assert monkeypatch is not None
+ monkeypatch.setattr(
+ "marimo._ast.type_inference.JediBackend", lambda: backend
+ )
+ return codegen.generate_filecontents(
+ codes,
+ names,
+ configs,
+ infer_types=infer_types, # type: ignore[arg-type]
+ )
+
+
+class TestCandidateNames:
+ def test_only_public_unannotated_names_read_by_other_cells(self) -> None:
+ extraction, _ = make_extraction(
+ [
+ "x = 1",
+ "y: int = 2",
+ "unused = 3",
+ "_private = 4",
+ "print(x, y, K, _private)",
+ ],
+ setup="K = 1",
+ )
+ assert candidate_names(extraction) == {"x"}
+
+ @pytest.mark.requires("duckdb", "sqlglot")
+ def test_sql_definitions_are_skipped(self) -> None:
+ extraction, _ = make_extraction(
+ [
+ 'mo.sql("CREATE TABLE t AS SELECT 1 AS a")',
+ 'df = mo.sql("SELECT * FROM t")',
+ "print(df)",
+ ],
+ )
+ # A read of `t` rules out exclusion as an unused variable.
+ assert "t" in extraction.used_refs
+ names = candidate_names(extraction)
+ assert "t" not in names
+ assert "df" in names
+
+
+class TestModuleAliases:
+ def test_only_module_bindings(self) -> None:
+ _, setup_cell = make_extraction(
+ ["print(np, pd, Path, math)"],
+ setup=(
+ "import numpy as np\n"
+ "import pandas as pd\n"
+ "from pathlib import Path\n"
+ "import math"
+ ),
+ )
+ assert module_aliases(setup_cell) == {
+ "math": "math",
+ "np": "numpy",
+ "pd": "pandas",
+ }
+
+ def test_no_setup_cell(self) -> None:
+ assert module_aliases(None) == {}
+
+
+class TestProbeModule:
+ def test_definitions_precede_uses(self) -> None:
+ extraction, setup_cell = make_extraction(
+ ["y = x + 1", "x = 1", "print(x, y)"],
+ setup="import math",
+ )
+ lines = probe_module(extraction, setup_cell).splitlines()
+ assert lines[0] == "import math"
+ assert lines.index("x = 1") < lines.index("y = x + 1")
+
+ def test_cycles_fall_back_to_file_order(self) -> None:
+ extraction, _ = make_extraction(["a = b", "b = a", "print(a, b)"])
+ lines = probe_module(extraction, None).splitlines()
+ assert lines[:3] == ["a = b", "b = a", "print(a, b)"]
+
+
+class TestDefinitionSites:
+ def test_module_level_bindings_of_every_kind(self) -> None:
+ source = (
+ "x = 1\n"
+ "if x:\n"
+ " x = 2\n"
+ "for item in [1]:\n"
+ " pass\n"
+ "with open('f') as handle:\n"
+ " pass\n"
+ "first, second = 1, 2\n"
+ "print(walrus := 3)\n"
+ "def f():\n"
+ " x = 'not module level'\n"
+ "squares = [x for x in range(3)]\n"
+ )
+ names = {"x", "item", "handle", "first", "second", "walrus", "squares"}
+ sites = definition_sites(source, names)
+ assert sites["x"] == [(1, 0), (3, 4)]
+ assert sites["item"] == [(4, 4)]
+ assert sites["handle"] == [(6, 18)]
+ assert sites["first"] == [(8, 0)]
+ assert sites["second"] == [(8, 7)]
+ assert sites["walrus"] == [(9, 6)]
+ # Comprehensions bind `x` in their own scope.
+ assert sites["squares"] == [(12, 0)]
+
+ def test_functions_classes_and_imports_have_no_site(self) -> None:
+ source = "import os\ndef f():\n pass\nclass C:\n pass\n"
+ assert definition_sites(source, {"os", "f", "C"}) == {}
+
+ def test_unparsable_source_has_no_sites(self) -> None:
+ assert definition_sites("x = (", {"x"}) == {}
+
+
+class TestLowerHint:
+ @pytest.mark.parametrize(
+ ("hint", "expected"),
+ [
+ ("int", "int"),
+ ("List[str]", "list[str]"),
+ ("Dict[str, List[int]]", "dict[str, list[int]]"),
+ ("Set[int]", "set[int]"),
+ ("FrozenSet[int]", "frozenset[int]"),
+ ("Type[int]", "type[int]"),
+ ("List[Union[int, str]]", "list[int | str]"),
+ ("Optional[int]", "int | None"),
+ ("Union[int, int]", "int"),
+ ("NoneType", "None"),
+ ("Tuple[int, str]", "tuple[int, str]"),
+ ("Tuple[int, str, int, str]", "tuple[int | str, ...]"),
+ ("Tuple[int, ...]", "tuple[int, ...]"),
+ (
+ "Dict[str, Tuple[int, str, int, str]]",
+ "dict[str, tuple[int | str, ...]]",
+ ),
+ ("Literal[1]", "int"),
+ ("Literal[True]", "bool"),
+ ('Literal[1, "a"]', "int | str"),
+ ],
+ )
+ def test_typing_spellings_become_builtins(
+ self, hint: str, expected: str
+ ) -> None:
+ node = lower_hint(hint)
+ assert node is not None
+ assert ast.unparse(node) == expected
+
+ def test_not_an_expression(self) -> None:
+ assert lower_hint("len(__obj: Sized) -> int") is None
+ assert lower_hint("<class 'Foo'>") is None
+
+
+class TestInferAnnotations:
+ def test_inferred_types_land_in_signatures(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "x": [instance("builtins.int", "int")],
+ "words": [instance("builtins.list", "List[str]")],
+ "flag": [instance("builtins.bool", None)],
+ "nothing": [instance("builtins.NoneType", "None")],
+ }
+ )
+ source = generate(
+ [
+ "x = 1",
+ "words = ['a']",
+ "flag = True",
+ "nothing = None",
+ "print(x, words, flag, nothing)",
+ ],
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert (
+ "def _(flag: bool, nothing: None, words: list[str], x: int):"
+ in source
+ )
+
+ def test_explicit_annotation_wins(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {"x": [instance("builtins.int", "int")]},
+ )
+ source = generate(
+ ["x: float = 1", "y = 2", "print(x, y)"],
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(x: float, y):" in source
+
+ def test_several_definitions_form_a_union(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "maybe": [
+ instance("builtins.NoneType", "None"),
+ instance("builtins.int", "int"),
+ ],
+ "same": [
+ instance("builtins.int", "int"),
+ instance("builtins.int", "int"),
+ ],
+ }
+ )
+ source = generate(
+ [
+ "maybe = None\nif maybe:\n maybe = 1",
+ "same = 1\nsame = 2",
+ "print(maybe, same)",
+ ],
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(maybe: None | int, same: int):" in source
+
+ def test_hint_failure_falls_back_to_the_bare_class(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "empty": [instance("builtins.list", None)],
+ "frames": [instance("builtins.list", "List[DataFrame]")],
+ }
+ )
+ source = generate(
+ ["empty = []", "frames = [make()]", "print(empty, frames)"],
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(empty: list, frames: list):" in source
+
+ @pytest.mark.parametrize("kind", ["function", "class", "module"])
+ def test_non_instances_stay_bare(
+ self, kind: str, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend({"thing": [Inferred("builtins.len", kind)]})
+ source = generate(
+ ["thing = len", "print(thing)"],
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(thing):" in source
+
+ def test_shadowed_builtin_is_not_written(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend({"n": [instance("builtins.int", "int")]})
+ source = generate(
+ ["n = 1", "print(n)"],
+ setup="int = 'shadowed'",
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(n):" in source
+
+ def test_library_class_is_spelled_through_a_verified_alias(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "df": [instance("pandas.core.frame.DataFrame", "DataFrame")],
+ "arr": [instance("numpy.ndarray", "ndarray[Any, Any]")],
+ "n": [instance("builtins.int", "int")],
+ },
+ classes={
+ "pd.DataFrame": "pandas.core.frame.DataFrame",
+ "np.ndarray": "numpy.ndarray",
+ },
+ )
+ source = generate(
+ [
+ "df = pd.DataFrame()",
+ "arr = np.zeros(3)",
+ "n = 3",
+ "print(df, arr, n)",
+ ],
+ setup="import numpy as np\nimport pandas as pd",
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(arr: np.ndarray, df: pd.DataFrame, n: int):" in source
+ assert backend.resolved == ["np.ndarray", "pd.DataFrame"]
+
+ def test_unverified_spellings_are_omitted_not_quoted(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "df": [instance("pandas.core.frame.DataFrame", "DataFrame")],
+ # No setup alias reaches this nested class.
+ "stock": [
+ instance("marimo._plugins.ui._impl.input.slider", "slider")
+ ],
+ "n": [instance("builtins.int", "int")],
+ },
+ classes={},
+ )
+ source = generate(
+ [
+ "df = pd.DataFrame()",
+ "stock = mo.ui.slider(1, 10)",
+ "n = 3",
+ "print(df, stock, n)",
+ ],
+ setup="import marimo as mo\nimport pandas as pd",
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(df, n: int, stock):" in source
+ assert '"' not in source.split("def _(df, n: int, stock):")[0][-200:]
+ assert backend.resolved == ["pd.DataFrame", "mo.slider"]
+
+ def test_setup_import_of_the_class_itself_is_written_bare(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {"p": [instance("pathlib.Path", "Path")]},
+ classes={"Path": "pathlib.Path"},
+ )
+ source = generate(
+ ['p = Path(".")', "print(p)"],
+ setup="from pathlib import Path",
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(p: Path):" in source
+
+ def test_notebook_class_is_written_bare(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "origin": [instance("__marimo_probe__.Point", "Point")],
+ "points": [instance("builtins.list", "List[Point]")],
+ },
+ classes={"Point": "__marimo_probe__.Point"},
+ )
+ source = generate(
+ [
+ "class Point:\n pass",
+ "origin = Point()",
+ "points = [Point()]",
+ "print(origin, points)",
+ ],
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(origin: Point, points: list[Point]):" in source
+
+ @pytest.mark.parametrize(
+ ("types", "signature"),
+ [
+ (["library._Private"], "def _(value):"),
+ (["library.__Private"], "def _(value):"),
+ (["library._internal.Public"], "def _(value: library.Public):"),
+ (
+ ["library._Private", "library._internal.Public"],
+ "def _(value: library.Public):",
+ ),
+ ],
+ )
+ def test_private_class_names_are_discarded(
+ self,
+ types: list[str],
+ signature: str,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ backend = FakeBackend(
+ {"value": [instance(name) for name in types]},
+ classes={
+ "library._Private": "library._Private",
+ "library.__Private": "library.__Private",
+ "library.Public": "library._internal.Public",
+ },
+ )
+ source = generate(
+ ["value = library.make()", "print(value)"],
+ setup="import library",
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert signature in source
+
+ def test_union_with_an_unspellable_member_is_dropped(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "value": [
+ instance("builtins.int", "int"),
+ instance("pandas.core.frame.DataFrame", "DataFrame"),
+ ]
+ }
+ )
+ source = generate(
+ ["value = 1\nif value:\n value = make()", "print(value)"],
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(value):" in source
+
+ def test_off_never_builds_a_backend(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ def explode() -> None:
+ raise AssertionError("the backend must not run")
+
+ monkeypatch.setattr("marimo._ast.type_inference.JediBackend", explode)
+ assert "def _(x):" in generate(
+ ["x = 1", "print(x)"], infer_types="off"
+ )
+
+ def test_nothing_to_probe_skips_the_backend(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ def explode() -> None:
+ raise AssertionError("the backend must not run")
+
+ monkeypatch.setattr("marimo._ast.type_inference.JediBackend", explode)
+ extraction, setup_cell = make_extraction(["x: int = 1", "print(x)"])
+ assert (
+ infer_annotations(
+ extraction, setup_cell, filename=None, mode="jedi"
+ )
+ == {}
+ )
+
+ def test_notebook_directory_is_the_search_path(
+ self, tmp_path: Path
+ ) -> None:
+ backend = FakeBackend({})
+ extraction, setup_cell = make_extraction(["x = 1", "print(x)"])
+ infer_annotations(
+ extraction,
+ setup_cell,
+ filename=str(tmp_path / "nb.py"),
+ mode="jedi",
+ backend=backend,
+ )
+ assert backend.search_paths == [tmp_path]
+
+
+class TestJediBackend:
+ def test_infers_every_definition_and_drops_uninferable_names(
+ self,
+ ) -> None:
+ source = (
+ "count = 3\n"
+ "maybe = None\n"
+ "if count:\n"
+ " maybe = 1\n"
+ "mystery = unknown_call()\n"
+ "def restock(n):\n"
+ " return n\n"
+ "fn = restock\n"
+ )
+ inferred = JediBackend().infer_definitions(
+ source, {"count", "maybe", "mystery", "fn", "restock"}, None
+ )
+ assert inferred["count"] == [instance("builtins.int", "int")]
+ assert [v.full_name for v in inferred["maybe"]] == [
+ "builtins.NoneType",
+ "builtins.int",
+ ]
+ assert inferred["fn"][0].kind == "function"
+ assert "mystery" not in inferred
+ assert "restock" not in inferred
+
+ def test_resolves_expressions_to_classes(self) -> None:
+ source = "from pathlib import Path\nimport collections\n"
+ resolved = JediBackend().resolve(
+ source,
+ ["Path", "collections.OrderedDict", "collections.nope"],
+ None,
+ )
+ assert resolved[0] is not None
+ assert resolved[0].kind == "class"
+ assert resolved[0].full_name.endswith(".Path")
+ assert resolved[1] is not None
+ assert resolved[1].kind == "class"
+ assert resolved[1].full_name == "collections.OrderedDict"
+ assert resolved[2] is None
+
+
+def test_infer_annotations_with_real_jedi() -> None:
+ source = generate(
+ [
+ "class Point:\n pass",
+ "x = 1",
+ "words = ['a', 'b']",
+ "prices = {'a': 1.0}",
+ "ratio = 1.5",
+ "mixed = (1, 2, 4, 4, 'long type', 1, 1)",
+ "flag = True",
+ 'p = Path(".")',
+ "origin = Point()",
+ "maybe = None\nif x:\n maybe = 'a'",
+ "helper = len",
+ "print(x, words, prices, ratio, mixed, flag, p, origin, maybe)",
+ "print(helper)",
+ ],
+ setup="from pathlib import Path",
+ )
+ for expected in [
+ "flag: bool",
+ "maybe: None | str",
+ "mixed: tuple[int | str, ...]",
+ "origin: Point",
+ "p: Path",
+ "prices: dict[str, float]",
+ "ratio: float",
+ "words: list[str]",
+ "x: int",
+ ]:
+ assert expected in source
+ assert "def _(helper):" in source
+
+
+ "definition",
+ [
+ "value = Point()",
+ "value = [Point()]",
+ "value = {'a': [Point()]}",
+ "value = None\nif True:\n value = Point()",
+ ],
+)
+def test_late_class_is_omitted_from_every_signature(
+ definition: str, tmp_path: Path
+) -> None:
+ source = generate(
+ [
+ definition,
+ "print(value)",
+ "class Point:\n pass",
+ "print(value)",
+ ]
+ )
+ path = tmp_path / "late_class.py"
+ path.write_text(source)
+ runpy.run_path(str(path))
+ assert source.count("def _(value):") == 2
+
+
+def test_class_only_needs_to_precede_consuming_signatures(
+ tmp_path: Path,
+) -> None:
+ source = generate(
+ [
+ "value = Point()\nprint(value)",
+ "class Point:\n pass",
+ "print(value)",
+ ]
+ )
+ path = tmp_path / "early_class.py"
+ path.write_text(source)
+ runpy.run_path(str(path))
+ assert "def _(value: Point):" in source
+
+
+ ("setup", "definition", "annotation"),
+ [
+ ("int = 0", "value = [1, 'a']", "list"),
+ ("list = 0", "value = {'a': [1]}", "dict"),
+ ("str = 0", "value = (1, ['a'])", "tuple"),
+ ],
+)
+def test_shadowed_nested_builtins_fall_back_to_bare_container(
+ setup: str, definition: str, annotation: str, tmp_path: Path
+) -> None:
+ source = generate([definition, "print(value)"], setup=setup)
+ path = tmp_path / "shadowed_builtin.py"
+ path.write_text(source)
+ runpy.run_path(str(path))
+ assert f"def _(value: {annotation}):" in source
+
+
+def test_private_names_keep_their_cell_scope(tmp_path: Path) -> None:
+ source = generate(
+ [
+ "_n = 1\ndef _f():\n return _n\nx = _f()",
+ "_n = 'a'\ny = _n",
+ "print(x, y)",
+ ]
+ )
+ path = tmp_path / "private_names.py"
+ path.write_text(source)
+ _, values = runpy.run_path(str(path))["app"].run()
+ assert values["x"] == 1
+ assert values["y"] == "a"
+ assert "def _(x: int, y: str):" in source
+
+
+ "rebind",
+ [
+ "import math as value",
+ "from math import sqrt as value",
+ "def value():\n pass",
+ "async def value():\n pass",
+ "class value:\n pass",
+ "match 'a':\n case value:\n pass",
+ "match ['a']:\n case [*value]:\n pass",
+ "match {'a': 1}:\n case {**value}:\n pass",
+ "[(value := 'a') for _ in range(1)]",
+ ],
+)
+def test_partially_inferred_bindings_are_omitted(
+ rebind: str, tmp_path: Path
+) -> None:
+ source = generate(["value = 1\n" + rebind, "print(value)"])
+ path = tmp_path / "rebindings.py"
+ path.write_text(source)
+ _, values = runpy.run_path(str(path))["app"].run()
+ assert not isinstance(values["value"], int)
+ assert "def _(value):" in source
+
+
+ importlib.util.find_spec("numpy") is None
+ or importlib.util.find_spec("pandas") is None,
+ reason="numpy and pandas are required",
+)
+def test_library_classes_with_real_jedi() -> None:
+ source = generate(
+ [
+ "df = pd.DataFrame({'a': [1]})",
+ "col = df['a']",
+ "prices = np.linspace(1.5, 2.5, 3)",
+ "print(df, col, prices)",
+ ],
+ setup="import numpy as np\nimport pandas as pd",
+ )
+ assert "df: pd.DataFrame" in source
+ assert "col: pd.Series" in source
+ # marimo keeps Jedi's incorrect tuple inference for `np.linspace`,
+ # and this expectation detects backend changes.
+ assert "prices: tuple" in source
+
+
+class TestBroadTypes:
+ def test_object_and_any_are_dropped(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "blob": [instance("builtins.object", "object")],
+ "maybe": [
+ instance("builtins.int", "int"),
+ instance("builtins.object", "object"),
+ ],
+ "items": [instance("builtins.list", "List[Any]")],
+ }
+ )
+ source = generate(
+ [
+ "blob = object()",
+ "maybe = 1\nif maybe:\n maybe = object()",
+ "items = [object()]",
+ "print(blob, maybe, items)",
+ ],
+ setup="from typing import Any",
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(blob, items, maybe):" in source
+
+ def test_union_wider_than_three_members_is_dropped(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "three": [
+ instance("builtins.int", "int"),
+ instance("builtins.NoneType", "None"),
+ instance("builtins.str", "str"),
+ ],
+ "four": [
+ instance("builtins.int", "int"),
+ instance("builtins.NoneType", "None"),
+ instance("builtins.str", "str"),
+ instance("builtins.bytes", "bytes"),
+ ],
+ # The collapsed tuple has four types in its element union.
+ "record": [
+ instance("builtins.tuple", "Tuple[int, str, float, bytes]")
+ ],
+ }
+ )
+ source = generate(
+ [
+ "three = 1\nthree = None\nthree = 'a'",
+ "four = 1\nfour = None\nfour = 'a'\nfour = b'a'",
+ "record = (1, 'a', 2.0, b'a')",
+ "print(three, four, record)",
+ ],
+ backend=backend,
+ monkeypatch=monkeypatch,
+ )
+ assert "def _(four, record, three: int | None | str):" in source
+
+
+class TestLineLength:
+ def test_annotation_that_does_not_fit_its_line_is_dropped(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ # ` x: list[str],` is 17 characters.
+ "x": [instance("builtins.list", "List[str]")],
+ # ` y: dict[str, list[int]],` is 28 characters.
+ "y": [instance("builtins.dict", "Dict[str, List[int]]")],
+ }
+ )
+ monkeypatch.setattr(
+ "marimo._ast.type_inference.JediBackend", lambda: backend
+ )
+ source = codegen.generate_filecontents(
+ ["x = ['a']", "y = {'a': [1]}", "print(x, y)"],
+ ["_", "_", "_"],
+ [CellConfig(), CellConfig(), CellConfig()],
+ infer_types="jedi",
+ line_length=20,
+ )
+ assert "def _(x: list[str], y):" in source
+
+ def test_budget_counts_the_parameter_name(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = FakeBackend(
+ {
+ "a": [instance("builtins.int", "int")],
+ "a_much_longer_name": [instance("builtins.int", "int")],
+ }
+ )
+ monkeypatch.setattr(
+ "marimo._ast.type_inference.JediBackend", lambda: backend
+ )
+ source = codegen.generate_filecontents(
+ [
+ "a = 1",
+ "a_much_longer_name = 2",
+ "print(a, a_much_longer_name)",
+ ],
+ ["_", "_", "_"],
+ [CellConfig(), CellConfig(), CellConfig()],
+ infer_types="jedi",
+ # ` a: int,` is 11 characters, and the long name needs 28.
+ line_length=12,
+ )
+ assert "def _(a: int, a_much_longer_name):" in source
diff --git a/tests/_cli/test_cli_check.py b/tests/_cli/test_cli_check.py
index 21d208c2f7..3990c063b4 100644
--- a/tests/_cli/test_cli_check.py
+++ b/tests/_cli/test_cli_check.py
@@ -13,6 +13,84 @@ from click.testing import CliRunner
from marimo._ast.cell import CellConfig
from marimo._ast.codegen import generate_filecontents
from marimo._cli.cli import check
+from marimo._config.manager import UserConfigStore, get_default_config_manager
+from marimo._server.models.models import SaveNotebookRequest
+from marimo._session.notebook import load_notebook
+
+
[email protected]("inline", [False, True])
+def test_fix_uses_each_notebooks_formatting_config(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, inline: bool
+) -> None:
+ monkeypatch.setattr(UserConfigStore, "read", lambda _self: {})
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "pyproject.toml").write_text(
+ '[tool.marimo.formatting]\ninfer_types = "off"\n'
+ )
+ files = []
+ signatures = [
+ ("jedi", 20, "def _(x: int, y):"),
+ ("jedi", 79, "def _(x: int, y: dict[str, list[int]]):"),
+ ("off", 79, "def _(x, y):"),
+ ]
+ for index, (mode, line_length, _) in enumerate(signatures):
+ project = tmp_path / str(index)
+ project.mkdir()
+ formatting = (
+ "[tool.marimo.formatting]\n"
+ f'infer_types = "{mode}"\nline_length = {line_length}\n'
+ )
+ project_config = formatting
+ header = None
+ if inline:
+ project_config = (
+ "[tool.marimo.formatting]\n"
+ f'infer_types = "{"off" if mode == "jedi" else "jedi"}"\n'
+ f"line_length = {79 if line_length == 20 else 20}\n"
+ )
+ header = (
+ "# /// script\n# dependencies = []\n"
+ + "".join(f"# {line}\n" for line in formatting.splitlines())
+ + "# ///\n"
+ )
+ (project / "pyproject.toml").write_text(project_config)
+ notebook = project / "notebook.py"
+ notebook.write_text(
+ generate_filecontents(
+ ["x = 1\ny = {'a': [1]}", "print(x, y)"],
+ ["_", "_"],
+ [CellConfig(), CellConfig()],
+ header_comments=header,
+ )
+ )
+ files.append(str(notebook))
+
+ runner = CliRunner()
+ result = runner.invoke(check, ["--fix", *files])
+ assert result.exit_code == 0, result.output
+ saved = [Path(file).read_text() for file in files]
+ for file, contents, (_, _, signature) in zip(
+ files, saved, signatures, strict=True
+ ):
+ assert signature in contents
+ manager = load_notebook(file)
+ manager.config_reader = get_default_config_manager(current_path=file)
+ cells = manager.app.cell_manager
+ manager.save(
+ SaveNotebookRequest(
+ cell_ids=list(cells.cell_ids()),
+ codes=list(cells.codes()),
+ names=list(cells.names()),
+ configs=list(cells.configs()),
+ filename=file,
+ )
+ )
+ assert Path(file).read_text() == contents
+
+ result = runner.invoke(check, ["--fix", *files])
+ assert result.exit_code == 0, result.output
+ assert "Updated" not in result.output
+ assert [Path(file).read_text() for file in files] == saved
@pytest.mark.parametrize(
diff --git a/tests/_config/test_config_snapshots.py b/tests/_config/test_config_snapshots.py
index cff389e830..ed15d38349 100644
--- a/tests/_config/test_config_snapshots.py
+++ b/tests/_config/test_config_snapshots.py
@@ -154,7 +154,7 @@ def test_default_configuration_snapshot(config_tree: Path) -> None:
"enable_pyflakes": False,
}
},
- "formatting": {"line_length": 79},
+ "formatting": {"line_length": 79, "infer_types": "off"},
"completion": {
"activate_on_typing": True,
"signature_hint_on_typing": False,
@@ -312,7 +312,7 @@ def test_layered_configuration_snapshot(
"vimrc": "<root>/home/project/editor.vim",
"preset": "default",
},
- "formatting": {"line_length": 130},
+ "formatting": {"infer_types": "off", "line_length": 130},
},
"resolved_unmasked": {
"language_servers": {
@@ -390,7 +390,7 @@ def test_layered_configuration_snapshot(
"vimrc": "<root>/home/project/editor.vim",
"preset": "default",
},
- "formatting": {"line_length": 130},
+ "formatting": {"infer_types": "off", "line_length": 130},
},
"user_masked": {
"package_management": {"manager": "pip"},
@@ -424,7 +424,7 @@ def test_layered_configuration_snapshot(
}
},
"signing": {"private_key_path": "********"},
- "formatting": {"line_length": 70},
+ "formatting": {"infer_types": "off", "line_length": 70},
"completion": {
"activate_on_typing": True,
"signature_hint_on_typing": False,
@@ -655,6 +655,7 @@ reference_highlighting = true
theme = "dark"
[formatting]
+infer_types = "off"
line_length = 79
[keymap]
diff --git a/tests/_lint/test_run_check.py b/tests/_lint/test_run_check.py
index 89c9a5164a..ab6f179b3b 100644
--- a/tests/_lint/test_run_check.py
+++ b/tests/_lint/test_run_check.py
@@ -4,10 +4,56 @@
import asyncio
from pathlib import Path
+import pytest
+
+from marimo._ast.cell import CellConfig
+from marimo._ast.codegen import generate_filecontents
+from marimo._ast.type_inference import TypeInferenceMode
+from marimo._config.manager import UserConfigStore
from marimo._lint import FileStatus, Linter, run_check
from marimo._lint.diagnostic import Diagnostic, Severity
+ ("configured", "override", "line_length", "expected"),
+ [
+ ("jedi", "off", None, "def _(value):"),
+ ("off", "jedi", 79, "def _(value: dict[str, list[int]]):"),
+ ("off", "jedi", None, "def _(value):"),
+ ("jedi", None, 79, "def _(value: dict[str, list[int]]):"),
+ ],
+)
+def test_formatting_overrides(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ configured: TypeInferenceMode,
+ override: TypeInferenceMode | None,
+ line_length: int | None,
+ expected: str,
+) -> None:
+ monkeypatch.setattr(UserConfigStore, "read", lambda _self: {})
+ (tmp_path / "pyproject.toml").write_text(
+ "[tool.marimo.formatting]\n"
+ f'infer_types = "{configured}"\nline_length = 20\n'
+ )
+ path = tmp_path / "notebook.py"
+ path.write_text(
+ generate_filecontents(
+ ["value = {'a': [1]}", "print(value)"],
+ ["_", "_"],
+ [CellConfig(), CellConfig()],
+ )
+ )
+ result = run_check(
+ (str(path),), fix=True, infer_types=override, line_length=line_length
+ )
+ assert not result.errored
+ assert expected in path.read_text()
+ result = run_check((str(path),), fix=True)
+ assert not result.errored
+ assert "def _(value):" in path.read_text()
+
+
class TestRunCheck:
"""Test the run_check function and CLI integration."""
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
index 00182b1546..8273821aa6 100644
--- a/tests/_server/templates/snapshots/export1.txt
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -100,7 +100,7 @@
"mode": "read",
"version": "0.0.0",
"serverToken": "token",
- "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
+ "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"infer_types": "off", "line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"layout": null,
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
index 8051b76242..20a6bb4f22 100644
--- a/tests/_server/templates/snapshots/export2.txt
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -100,7 +100,7 @@
"mode": "read",
"version": "0.0.0",
"serverToken": "token",
- "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
+ "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"infer_types": "off", "line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"layout": null,
diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txt
index 3ec440062f..8582a6a7fe 100644
--- a/tests/_server/templates/snapshots/export3.txt
+++ b/tests/_server/templates/snapshots/export3.txt
@@ -100,7 +100,7 @@
"mode": "read",
"version": "0.0.0",
"serverToken": "token",
- "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
+ "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"infer_types": "off", "line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"layout": null,
diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txt
index ad3a13b263..e3cac4fb67 100644
--- a/tests/_server/templates/snapshots/export4.txt
+++ b/tests/_server/templates/snapshots/export4.txt
@@ -100,7 +100,7 @@
"mode": "read",
"version": "0.0.0",
"serverToken": "token",
- "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
+ "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"infer_types": "off", "line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"css_file": "custom.css", "sql_output": "auto", "width": "compact"},
"layout": null,
diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txt
index 042ea91067..da29a09773 100644
--- a/tests/_server/templates/snapshots/export5.txt
+++ b/tests/_server/templates/snapshots/export5.txt
@@ -112,7 +112,7 @@
"mode": "read",
"version": "0.0.0",
"serverToken": "token",
- "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
+ "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"infer_types": "off", "line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"app_title": "My App", "html_head_file": "head.html", "sql_output": "auto", "width": "compact"},
"layout": null,
diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txt
index fece2d9937..682eef2274 100644
--- a/tests/_server/templates/snapshots/export6.txt
+++ b/tests/_server/templates/snapshots/export6.txt
@@ -101,7 +101,7 @@
"mode": "read",
"version": "0.0.0",
"serverToken": "token",
- "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "custom_css": ["custom1.css", "custom2.css"], "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
+ "config": {"ai": {"allow_provider_config": true, "custom_providers": {}, "enabled": true, "models": {"custom_models": [], "displayed_models": []}}, "completion": {"activate_on_typing": true, "auto_close_pairs": true, "copilot": false, "signature_hint_on_typing": false}, "diagnostics": {"sql_linter": true}, "display": {"cell_output": "below", "code_editor_font_size": 14, "code_lens": true, "custom_css": ["custom1.css", "custom2.css"], "dataframes": "rich", "default_table_max_columns": 50, "default_table_page_size": 10, "default_width": "medium", "reference_highlighting": true, "theme": "light"}, "formatting": {"infer_types": "off", "line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "language_servers": {"pylsp": {"enable_flake8": false, "enable_mypy": true, "enable_pydocstyle": false, "enable_pyflakes": false, "enable_pylint": false, "enable_ruff": true, "enabled": false}}, "mcp": {"mcpServers": {}, "presets": []}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": false, "auto_reload": "off", "default_csv_encoding": "utf-8", "default_sql_output": "auto", "on_cell_change": "autorun", "output_max_bytes": 8000000, "reactive_tests": true, "show_tracebacks": false, "std_stream_max_bytes": 1000000, "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}},
"configOverrides": {"formatting": {"line_length": 100}},
"appConfig": {"sql_output": "auto", "width": "compact"},
"layout": null,
diff --git a/tests/_session/notebook/test_app_file_manager.py b/tests/_session/notebook/test_app_file_manager.py
index ed72f6c06b..0ddb519ef9 100644
--- a/tests/_session/notebook/test_app_file_manager.py
+++ b/tests/_session/notebook/test_app_file_manager.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import os
+import runpy
import threading
from concurrent.futures import ThreadPoolExecutor, wait
from typing import TYPE_CHECKING
@@ -9,6 +10,8 @@ from unittest.mock import patch
import pytest
+from marimo._ast.type_inference import Inferred
+from marimo._server.models.models import SaveNotebookRequest
from marimo._session.notebook import (
AppFileManager,
load_notebook,
@@ -215,6 +218,143 @@ def test_manifest_and_cell_saves_preserve_each_other(
]
+_NOTEBOOK_WITH_PARAMETER = """
+import marimo
+
+app = marimo.App()
+
+
+def _():
+ x = 1
+ return (x,)
+
+
+def _(x):
+ print(x)
+ return
+"""
+
+
+class _ConfigReader:
+ """Provide formatting configuration for save tests."""
+
+ def __init__(self, infer_types: str) -> None:
+ self.infer_types = infer_types
+
+ def get_config(self, *, hide_secrets: bool = True) -> dict:
+ del hide_secrets
+ return {"formatting": {"infer_types": self.infer_types}}
+
+
+class _FakeBackend:
+ """Infer `x` as `int` and record the module search path."""
+
+ def __init__(self) -> None:
+ self.search_paths: list[Path | None] = []
+
+ def infer_definitions(
+ self, source: str, names: set[str], search_path: Path | None
+ ) -> dict[str, list[Inferred]]:
+ del source, names
+ self.search_paths.append(search_path)
+ return {"x": [Inferred("builtins.int", "instance", "int")]}
+
+ def resolve(
+ self, source: str, expressions: list[str], search_path: Path | None
+ ) -> list[Inferred | None]:
+ del source, search_path
+ return [None] * len(expressions)
+
+
+def _save_request(fm: AppFileManager, nb: Path) -> SaveNotebookRequest:
+ cell_manager = fm.app.cell_manager
+ return SaveNotebookRequest(
+ cell_ids=list(cell_manager.cell_ids()),
+ codes=list(cell_manager.codes()),
+ names=list(cell_manager.names()),
+ configs=list(cell_manager.configs()),
+ filename=str(nb),
+ )
+
+
+def test_infer_types_defaults_off_without_config(tmp_path: Path) -> None:
+ fm = load_notebook(_write_notebook(tmp_path / "nb.py"))
+ assert fm.config_reader is None
+ assert fm.infer_types == "off"
+
+
+def test_infer_types_follows_live_config(tmp_path: Path) -> None:
+ fm = load_notebook(_write_notebook(tmp_path / "nb.py"))
+ reader = _ConfigReader(infer_types="off")
+ fm.config_reader = reader # type: ignore[assignment]
+ assert fm.infer_types == "off"
+ reader.infer_types = "jedi"
+ assert fm.infer_types == "jedi"
+
+
+def test_save_writes_inferred_types_to_disk_when_enabled(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ nb = tmp_path / "nb.py"
+ nb.write_text(_NOTEBOOK_WITH_PARAMETER)
+ fm = load_notebook(nb)
+ fm.config_reader = _ConfigReader(infer_types="jedi") # type: ignore[assignment]
+ backend = _FakeBackend()
+ monkeypatch.setattr(
+ "marimo._ast.type_inference.JediBackend", lambda: backend
+ )
+
+ fm.save(_save_request(fm, nb))
+
+ assert "def _(x: int):" in nb.read_text()
+ assert backend.search_paths == [tmp_path]
+
+
+def test_save_normalizes_nonbreaking_spaces_with_inference(
+ tmp_path: Path,
+) -> None:
+ nb = tmp_path / "nb.py"
+ nb.write_text(_NOTEBOOK_WITH_PARAMETER)
+ fm = load_notebook(nb)
+ fm.config_reader = _ConfigReader(infer_types="jedi") # type: ignore[assignment]
+ request = _save_request(fm, nb)
+ request.codes[0] = "x\u00a0=\u00a02"
+
+ fm.save(request)
+
+ assert "def _(x: int):" in nb.read_text()
+ _, values = runpy.run_path(str(nb))["app"].run()
+ assert values["x"] == 2
+
+
+def test_to_code_skips_type_inference_when_disabled(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ nb = tmp_path / "nb.py"
+ nb.write_text(_NOTEBOOK_WITH_PARAMETER)
+ fm = load_notebook(nb)
+ fm.config_reader = _ConfigReader(infer_types="off") # type: ignore[assignment]
+
+ def explode() -> None:
+ raise AssertionError("the type inference backend must not run")
+
+ monkeypatch.setattr("marimo._ast.type_inference.JediBackend", explode)
+ assert "def _(x):" in fm.to_code()
+
+
+def test_line_length_follows_config_and_defaults_to_79(tmp_path: Path) -> None:
+ fm = load_notebook(_write_notebook(tmp_path / "nb.py"))
+ assert fm.line_length == 79
+ reader = _ConfigReader(infer_types="jedi")
+ reader.get_config = lambda **_: { # type: ignore[method-assign]
+ "formatting": {"infer_types": "jedi", "line_length": 100}
+ }
+ fm.config_reader = reader # type: ignore[assignment]
+ assert fm.line_length == 100
+
+
def test_on_persisted_reports_the_cells_and_config_written(
tmp_path: Path,
) -> None: