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.

mep/8: Add @app.class_definition (#4353)

Dylan Madisettid2f45cfae636
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 955b7316f8..312b57635d 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -68,10 +68,10 @@ if TYPE_CHECKING:
from marimo._plugins.core.web_component import JSONType
from marimo._runtime.context.types import ExecutionContext
-
P = ParamSpec("P")
R = TypeVar("R")
Fn: TypeAlias = Callable[P, R]
+Cls: TypeAlias = type
LOGGER = _loggers.marimo_logger()
@@ -372,7 +372,7 @@ class App:
hide_code: bool = False,
**kwargs: Any,
) -> Fn[P, R] | Callable[[Fn[P, R]], Fn[P, R]]:
- """A decorator to wrap a callable function into a cell in the app.
+ """A decorator to wrap a callable function into a marimo cell.
This decorator can be called with or without parentheses. Each of the
following is valid:
@@ -414,6 +414,61 @@ class App:
),
)
+ @overload
+ def class_definition(self, cls: Cls) -> Cls: ...
+
+ @overload
+ def class_definition(self, **kwargs: Any) -> Callable[[Cls], Cls]: ...
+
+ def class_definition(
+ self,
+ cls: Cls | None = None,
+ *,
+ column: Optional[int] = None,
+ disabled: bool = False,
+ hide_code: bool = False,
+ **kwargs: Any,
+ ) -> Cls | Callable[[Cls], Cls]:
+ """A decorator to wrap a class into a marimo cell.
+
+ This decorator can be called with or without parentheses. Each of the
+ following is valid:
+
+ ```
+ @app.class_definition
+ class MyClass: ...
+
+
+ @app.class_definition()
+ class TestClass: ...
+
+
+ @app.class_definition(disabled=True)
+ @dataclasses.dataclass
+ class MyStruct: ...
+ ```
+
+ Args:
+ cls: The decorated class.
+ column: The column number to place this cell in.
+ disabled: Whether to disable the cell.
+ hide_code: Whether to hide the cell's code.
+ **kwargs: For forward-compatibility with future arguments.
+ """
+ del kwargs
+
+ return cast(
+ Union[Cls, Callable[[Cls], Cls]],
+ self._cell_manager.cell_decorator(
+ cls,
+ column,
+ disabled,
+ hide_code,
+ app=InternalApp(self),
+ top_level=True,
+ ),
+ )
+
@property
def setup(self) -> _SetupContext:
"""Provides a context manager to initialize the setup cell.
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 95f6e27d1f..a5aba77010 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -8,12 +8,15 @@ import os
from collections.abc import Awaitable, Mapping
from typing import TYPE_CHECKING, Any, Literal, Optional
+from marimo import _loggers
from marimo._ast.sql_visitor import SQLVisitor
from marimo._ast.visitor import ImportData, Language, Name, VariableData
from marimo._runtime.exceptions import MarimoRuntimeException
from marimo._types.ids import CellId_t
from marimo._utils.deep_merge import deep_merge
+LOGGER = _loggers.marimo_logger()
+
if TYPE_CHECKING:
from collections.abc import Iterable
from types import CodeType
@@ -304,7 +307,8 @@ class CellImpl:
if not (
len(tree.body) == 1
and isinstance(
- tree.body[0], (ast.FunctionDef, ast.AsyncFunctionDef)
+ tree.body[0],
+ (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef),
)
):
return None
@@ -408,6 +412,8 @@ class Cell:
# Whether to expose this cell as a test cell.
_test_allowed: bool = False
+ _expected_signature: Optional[tuple[str, ...]] = None
+
@property
def name(self) -> str:
return self._name
@@ -603,9 +609,14 @@ class Cell:
raise e.__cause__ from None # type: ignore
def __call__(self, *args: Any, **kwargs: Any) -> Any:
- # TODO: Expand for toplevel modules when the time comes.
+ from marimo._ast.toplevel import TopLevelExtraction
+
+ assert self._app is not None
+ # Definitions on a module level are not part of the signature, and as
+ # such, should not be provided with the call.
+ extraction = TopLevelExtraction.from_app(self._app)
arg_names = sorted(
- self._cell.refs - set(globals()["__builtins__"].keys())
+ (self._cell.refs - extraction.allowed_refs) - self._cell.defs
)
argc = len(arg_names)
@@ -613,6 +624,11 @@ class Cell:
call_args.update(kwargs)
call_argc = len(call_args.keys()) + len(self._pytest_reserved)
+ if unexpected := call_args.keys() - arg_names:
+ raise TypeError(
+ f"{self.name}() got an unexpected argument(s) '{unexpected}'"
+ )
+
is_pytest = "PYTEST_CURRENT_TEST" in os.environ
# Capture pytest case, where arguments don't match the references.
if self._pytest_reserved - set(arg_names):
@@ -621,6 +637,18 @@ class Cell:
"resave the notebook in the marimo editor."
)
+ actual_count = len(args) + len(kwargs)
+
+ mismatch_context = ""
+ if self._expected_signature is not None:
+ if tuple(arg_names) != self._expected_signature:
+ mismatch_context = (
+ f"The signature of function ``{self._name}'': {self._expected_signature} "
+ f"does not match the expected signature: {tuple(arg_names)}. "
+ "A mismatch in arguments likely means you should "
+ "resave the notebook in the marimo editor."
+ )
+
# If all the arguments are provided, then run as if it were a normal
# function call. An incorrect number of arguments will raise a
# TypeError (the same as a normal function call).
@@ -628,8 +656,16 @@ class Cell:
# pytest is an exception here, since it enables testing directly on
# notebooks, and the graph will be executed if needed.
if argc == call_argc and (
- is_pytest or all(name in call_args for name in arg_names)
+ is_pytest
+ or (
+ all(name in call_args for name in arg_names)
+ and argc == actual_count
+ )
):
+ # Function invoked successfully, but let the user know there is a
+ # mismatch in the signature.
+ if mismatch_context:
+ LOGGER.warning(mismatch_context)
# Note, run returns a tuple of (output, defs)-
# so stripped defs is required.
ret = self.run(**call_args)
@@ -645,20 +681,19 @@ class Cell:
return output
if is_pytest:
- call_str = (
- "A mismatch in arguments likely means you should "
- "resave the notebook in the marimo editor."
- )
+ call_str = mismatch_context
else:
await_str = "await " if self._is_coroutine else ""
+ mismatch_context += " Alternatively; " if mismatch_context else ""
call_str = (
- "Consider calling with `outputs, defs = "
- f"{await_str}{self.name}.run()`"
+ f"{mismatch_context}Consider calling with `outputs, defs = "
+ f"{await_str}{self.name}.run()`."
)
+ were = "were" if actual_count != 1 else "was"
raise TypeError(
f"{self.name}() takes {argc} positional arguments but "
- f"{call_argc} were given. {call_str}"
+ f"{actual_count} {were} given. {call_str}"
)
diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.py
index 1084f48466..4b3b21dfca 100644
--- a/marimo/_ast/cell_manager.py
+++ b/marimo/_ast/cell_manager.py
@@ -37,6 +37,8 @@ if TYPE_CHECKING:
P = ParamSpec("P")
R = TypeVar("R")
Fn: TypeAlias = Callable[P, R]
+Cls: TypeAlias = type
+Obj: TypeAlias = "Cls | Fn[P, R]"
class CellManager:
@@ -87,29 +89,31 @@ class CellManager:
# TODO: maybe remove this, it is leaky
def cell_decorator(
self,
- func: Fn[P, R] | None,
+ obj: Obj[P, R] | None,
column: Optional[int],
disabled: bool,
hide_code: bool,
app: InternalApp | None = None,
*,
top_level: bool = False,
- ) -> Cell | Fn[P, R] | Callable[[Fn[P, R]], Cell | Fn[P, R]]:
+ ) -> Cell | Obj[P, R] | Callable[[Obj[P, R]], Cell | Obj[P, R]]:
"""Create a cell decorator for marimo notebook cells."""
cell_config = CellConfig(
column=column, disabled=disabled, hide_code=hide_code
)
- def _register(func: Fn[P, R]) -> Cell | Fn[P, R]:
+ def _register(obj: Obj[P, R]) -> Cell | Obj[P, R]:
# Use PYTEST_VERSION here, opposed to PYTEST_CURRENT_TEST, in
# order to allow execution during test collection.
is_top_level_pytest = (
"PYTEST_VERSION" in os.environ
and "PYTEST_CURRENT_TEST" not in os.environ
)
- factory = toplevel_cell_factory if top_level else cell_factory
+ factory: Callable[..., Cell] = (
+ toplevel_cell_factory if top_level else cell_factory
+ )
cell = factory(
- func,
+ obj,
cell_id=self.create_cell_id(),
anonymous_file=app._app._anonymous_file if app else False,
test_rewrite=is_top_level_pytest
@@ -120,24 +124,24 @@ class CellManager:
# Top level functions are exposed as the function itself.
if top_level:
- return func
+ return obj
# Manually set the signature for pytest.
if is_top_level_pytest:
# NB. in place metadata update.
- process_for_pytest(func, cell)
+ process_for_pytest(obj, cell)
return cell
- if func is None:
+ if obj is None:
# If the decorator was used with parentheses, func will be None,
# and we return a decorator that takes the decorated function as an
# argument
- def decorator(func: Fn[P, R]) -> Cell | Fn[P, R]:
- return _register(func)
+ def decorator(obj: Obj[P, R]) -> Cell | Obj[P, R]:
+ return _register(obj)
return decorator
else:
- return _register(func)
+ return _register(obj)
def cell_context(
self,
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index ae3ddc8841..5de559a96a 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -7,6 +7,7 @@ import importlib.util
import json
import os
import re
+import sys
import textwrap
from typing import Any, Literal, Optional, cast
@@ -20,6 +21,13 @@ from marimo._ast.visitor import Name
from marimo._config.manager import get_default_config_manager
from marimo._types.ids import CellId_t
+if sys.version_info < (3, 10):
+ from typing_extensions import TypeAlias
+else:
+ from typing import TypeAlias
+
+Cls: TypeAlias = type
+
INDENT = " "
MAX_LINE_LENGTH = 80
@@ -30,6 +38,8 @@ NOTICE = "\n".join(
]
)
+Decorators = Literal["cell", "function", "class_definition"]
+
def pop_setup_cell(
code: list[str],
@@ -107,7 +117,8 @@ def format_tuple_elements(
def to_decorator(
- config: Optional[CellConfig], fn: Literal["cell", "function"] = "cell"
+ config: Optional[CellConfig],
+ fn: Decorators = "cell",
) -> str:
if config is None:
return f"@app.{fn}"
@@ -177,6 +188,9 @@ def to_functiondef(
# other static analysis tools can capture unused variables across cells.
defs: tuple[str, ...] = tuple()
if cell.defs:
+ # There are possible name error cases where a cell defines, and also
+ # requires a variable. We remove defs from the signature such that
+ # this causes a lint error in pyright.
if used_refs is None:
defs = tuple(name for name in sorted(cell.defs))
else:
@@ -198,9 +212,17 @@ def to_top_functiondef(
# the cell, it must pass basic checks in the cell impl.
if allowed_refs is None:
allowed_refs = set(builtins.__dict__.keys())
- assert cell.toplevel_variable, "Cell is not a top-level function"
+ toplevel_var = cell.toplevel_variable
+
+ assert toplevel_var, "Cell is not a top-level function"
if cell.code:
- decorator = to_decorator(cell.config, fn="function")
+ assert toplevel_var.kind in ("function", "class"), (
+ "Unexpected cell kind, please report an issue to github.com/marimo-team/marimo"
+ )
+ if toplevel_var.kind == "class":
+ decorator = to_decorator(cell.config, fn="class_definition")
+ else:
+ decorator = to_decorator(cell.config, fn="function")
return "\n".join([decorator, cell.code.strip()])
return ""
@@ -410,13 +432,19 @@ def get_app(filename: Optional[str]) -> Optional[App]:
if has_only_comments:
return None
+ # TODO(dmadisetti): Consider replacing with a completely static load for
+ # edit.
spec = importlib.util.spec_from_file_location("marimo_app", filename)
if spec is None:
raise RuntimeError("Failed to load module spec")
marimo_app = importlib.util.module_from_spec(spec)
if spec.loader is None:
raise RuntimeError("Failed to load module spec's loader")
- spec.loader.exec_module(marimo_app) # This may throw a SyntaxError
+ try:
+ sys.modules["marimo_app"] = marimo_app
+ spec.loader.exec_module(marimo_app) # This may throw a SyntaxError
+ finally:
+ sys.modules.pop("marimo_app", None)
if not hasattr(marimo_app, "app"):
raise MarimoFileError(f"{filename} missing attribute `app`.")
if not isinstance(marimo_app.app, App):
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index c055e713c3..9c6a6b853f 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -7,6 +7,7 @@ import io
import linecache
import os
import re
+import sys
import textwrap
import token as token_types
from tokenize import TokenInfo, tokenize
@@ -26,7 +27,13 @@ from marimo._ast.visitor import ImportData, Name, ScopedVisitor
from marimo._types.ids import CellId_t
from marimo._utils.tmpdir import get_tmpdir
+if sys.version_info < (3, 10):
+ from typing_extensions import TypeAlias
+else:
+ from typing import TypeAlias
+
LOGGER = _loggers.marimo_logger()
+Cls: TypeAlias = type
if TYPE_CHECKING:
from collections.abc import Iterator
@@ -283,10 +290,13 @@ def compile_cell(
def get_source_position(
- f: Callable[..., Any], lineno: int, col_offset: int
+ f: Cls | Callable[..., Any], lineno: int, col_offset: int
) -> Optional[SourcePosition]:
# Fallback won't capture embedded scripts
- is_script = f.__globals__["__name__"] == "__main__"
+ if inspect.isclass(f):
+ is_script = f.__module__ == "__main__"
+ else:
+ is_script = f.__globals__["__name__"] == "__main__" # type: ignore
# TODO: spec is None for markdown notebooks, which is fine for now
if module := inspect.getmodule(f):
spec = module.__spec__
@@ -296,7 +306,7 @@ def get_source_position(
return None
return SourcePosition(
- filename=f.__code__.co_filename,
+ filename=inspect.getfile(f),
lineno=lineno,
col_offset=col_offset,
)
@@ -348,7 +358,7 @@ def context_cell_factory(
def toplevel_cell_factory(
- f: Callable[..., Any],
+ obj: Cls | Callable[..., Any],
cell_id: CellId_t,
anonymous_file: bool = False,
test_rewrite: bool = False,
@@ -358,7 +368,7 @@ def toplevel_cell_factory(
NB: Unlike cell_factory, this utilizes the function itself as the cell
definition. As such, signature and return type are important.
"""
- code, lnum = inspect.getsourcelines(f)
+ code, lnum = inspect.getsourcelines(obj)
function_code = textwrap.dedent("".join(code))
# We need to scrub through the initial decorator. Since we don't care about
@@ -379,7 +389,7 @@ def toplevel_cell_factory(
source_position = None
if not anonymous_file:
source_position = get_source_position(
- f,
+ obj,
lnum + decorator.end_lineno - 1, # Scrub the decorator
0,
)
@@ -390,10 +400,14 @@ def toplevel_cell_factory(
source_position=source_position,
test_rewrite=test_rewrite,
)
+ if isinstance(obj, Cls):
+ is_test = obj.__name__.startswith("Test")
+ else:
+ is_test = obj.__name__.startswith("test_")
return Cell(
- _name=f.__name__,
+ _name=obj.__name__,
_cell=cell,
- _test_allowed=cell._test or f.__name__.startswith("test_"),
+ _test_allowed=cell._test or is_test,
)
@@ -528,4 +542,5 @@ def cell_factory(
_name=f.__name__,
_cell=cell,
_test_allowed=cell._test or f.__name__.startswith("test_"),
+ _expected_signature=tuple(inspect.signature(f).parameters.keys()),
)
diff --git a/marimo/_ast/toplevel.py b/marimo/_ast/toplevel.py
index 85d7ffb215..a12e86bff7 100644
--- a/marimo/_ast/toplevel.py
+++ b/marimo/_ast/toplevel.py
@@ -103,11 +103,14 @@ class TopLevelStatus:
allowed_refs: set[Name],
unresolved: set[Name] | None = None,
potential_refs: set[Name] | None = None,
+ toplevel: set[Name] | None = None,
) -> None:
if potential_refs is None:
potential_refs = set()
if unresolved is None:
unresolved = set()
+ if toplevel is None:
+ toplevel = set()
if self._cell is None:
try:
@@ -137,8 +140,9 @@ class TopLevelStatus:
self.demote(HINT_HAS_COMMENT)
return
- allowed_refs = set(allowed_refs) | {self.name}
+ allowed_refs = set(allowed_refs) | {self.name, "_lambda"}
order_dependent_refs = var.unbounded_refs - allowed_refs
+
if order_dependent_refs and order_dependent_refs - unresolved:
self.dependencies = order_dependent_refs
if not order_dependent_refs - (unresolved | potential_refs):
@@ -147,7 +151,7 @@ class TopLevelStatus:
self.demote(HINT_HAS_REFS.format(self.dependencies))
return
- dependent_refs = var.required_refs - allowed_refs
+ dependent_refs = self._cell.refs - (allowed_refs | toplevel)
if not dependent_refs:
self.type = TopLevelType.TOPLEVEL
return
@@ -239,15 +243,16 @@ class TopLevelExtraction:
CellId_t(str(idx)), code, name, config, self.allowed_refs
)
self._statuses[status.type][status.name] = status
+
self.statuses.append(status)
if not status.is_unparsable:
defs.update(status.defs)
refs.update(status.refs)
- if status.is_toplevel:
- self.allowed_refs.add(status.name)
# Refresh names
- names = [status.name for status in self.statuses]
+ potential_refs = set(
+ [status.name for status in self.statuses if not status.is_toplevel]
+ )
self.unshadowed = set(builtins.__dict__.keys()) - defs
self.allowed_refs.update(self.unshadowed)
@@ -259,12 +264,19 @@ class TopLevelExtraction:
for status in self.statuses:
if status.is_unresolved or status.is_cell:
self._statuses[status.type].pop(status.name)
- status.update(self.allowed_refs, unresolved, set(names))
+ status.update(
+ self.allowed_refs,
+ unresolved,
+ potential_refs,
+ set(self.toplevel.keys()),
+ )
if status.is_toplevel:
self.allowed_refs.add(status.name)
elif status.is_unresolved:
unresolved.add(status.name)
self._statuses[status.type][status.name] = status
+ else:
+ self.allowed_refs.add(status.name)
self._resolve_dependencies()
# Don't change names of objects that are not toplevel.
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index c8ac47bee0..5ba929f4d1 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -392,17 +392,34 @@ class ScopedVisitor(ast.NodeVisitor):
scope and then return the body refs and unbounded refs."""
self.ref_stack.append(set())
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
- # Handle function refs that are evaluated in the outer scope
- # Remove the body, which keeps signature and non-scoped parts.
- mock = deepcopy(node)
- mock.body.clear()
- self.generic_visit(mock)
- # Collect the unbounded refs
- unbounded_refs = set(self.ref_stack[-1])
- else:
- # TODO: Update for class_definition toplevel decorator.
- unbounded_refs = set()
+
+ mock = deepcopy(node)
+ unbounded_refs = set()
+ if isinstance(mock, (ast.ClassDef)):
+ # The Class ast is surprising loose, and anything can be defined
+ # inside. Python runs the ClassDef body on definition and anything
+ # defined in the scope gets added to the class.
+ mock_module = ast.Module(body=mock.body, type_ignores=[])
+ mock_visitor = ScopedVisitor(self.id)
+ mock_visitor.visit(mock_module)
+ # The unbounded defs are carried from the recursive visitor
+ # excluding all references found in exclusively in scope.
+ ignore_refs = set()
+ for var in mock_visitor.variable_data:
+ for data in mock_visitor.variable_data[var]:
+ if data.kind in ("function", "class"):
+ unbounded_refs |= data.unbounded_refs
+ ignore_refs |= data.required_refs
+ else:
+ unbounded_refs |= data.required_refs
+ unbounded_refs |= mock_visitor.refs - ignore_refs
+
+ # Handle function/class refs that are evaluated in the outer scope
+ # Remove the body, which keeps signature and non-scoped parts.
+ mock.body.clear()
+ self.generic_visit(mock)
+ # Collect the unbounded refs
+ unbounded_refs |= set(self.ref_stack[-1])
# Process the function body
self.generic_visit(node)
@@ -422,11 +439,13 @@ class ScopedVisitor(ast.NodeVisitor):
# ClassDef and FunctionDef nodes don't have ast.Name nodes as children
def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
node.name = self._if_local_then_mangle(node.name)
- refs, _ = self._visit_and_get_refs(node)
+ refs, unbounded_refs = self._visit_and_get_refs(node)
self._define(
node,
node.name,
- VariableData(kind="class", required_refs=refs),
+ VariableData(
+ kind="class", required_refs=refs, unbounded_refs=unbounded_refs
+ ),
)
return node
diff --git a/tests/_ast/cell_data/named_cells.py b/tests/_ast/cell_data/named_cells.py
index 10c94a2c9d..19572581ed 100644
--- a/tests/_ast/cell_data/named_cells.py
+++ b/tests/_ast/cell_data/named_cells.py
@@ -3,6 +3,10 @@ import marimo
__generated_with = "0.2.8"
app = marimo.App()
+with app.setup:
+ # Purposefully named a, such that in ordering it would be first.
+ a = 1
+
@app.cell
def f():
@@ -44,5 +48,12 @@ def multiple():
(A, B)
return (A, B)
+
+def called_with_global(x):
+ Y = a + x
+ Y
+ return (Y,)
+
if __name__ == "__main__":
app.run()
diff --git a/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py b/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py
index c4ea10080a..72618a349b 100644
--- a/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py
+++ b/tests/_ast/codegen_data/test_generate_filecontents_toplevel.py
@@ -14,6 +14,7 @@ with app.setup:
import textwrap
import typing
from pathlib import Path
+ import dataclasses
import marimo as mo
@@ -89,5 +90,16 @@ def _():
return
+class ExampleClass:
+ ...
+
+
+class SubClass(ExampleClass):
+ ...
+
+
if __name__ == "__main__":
app.run()
diff --git a/tests/_ast/test_cell.py b/tests/_ast/test_cell.py
index 62c768a75d..7277c0470e 100644
--- a/tests/_ast/test_cell.py
+++ b/tests/_ast/test_cell.py
@@ -1,10 +1,14 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import logging
+import os
+import sys
from collections.abc import Awaitable
import pytest
+from marimo import _loggers
from marimo._ast.app import App
from marimo._ast.cell import CellConfig
@@ -216,6 +220,67 @@ class TestCellRun:
assert multiple() == (0, 1)
assert unhashable_defined() == {0, 1, 2}
+ @staticmethod
+ def test_direct_call_with_global() -> None:
+ old = os.environ.pop("PYTEST_CURRENT_TEST")
+ old_version = os.environ.pop("PYTEST_VERSION")
+ try:
+ if "cell_data.named_cells" in sys.modules:
+ del sys.modules["cell_data.named_cells"]
+ from cell_data.named_cells import called_with_global
+
+ # NB. depends on a variable `a` defined on module level.
+ assert called_with_global(1) == 2
+ assert called_with_global(x=1) == 2
+
+ # Raise errors
+ with pytest.raises(TypeError) as e:
+ called_with_global(1, 1)
+
+ with pytest.raises(TypeError) as e:
+ called_with_global(x=1, a=1)
+ assert "unexpected argument" in str(e.value)
+
+ with pytest.raises(TypeError) as e:
+ called_with_global(a=1)
+ assert "unexpected argument" in str(e.value)
+
+ finally:
+ os.environ["PYTEST_CURRENT_TEST"] = old
+ os.environ["PYTEST_VERSION"] = old_version
+
+ @staticmethod
+ def test_mismatch_args(app, caplog) -> None:
+ # poor practice, but possible cell.
+ @app.cell
+ def basic(lots, of_, incorrect, args): # noqa: ARG001
+ 1 # noqa: B018
+ return
+
+ assert basic.run() == (1, {})
+ assert len(caplog.records) == 0
+ with caplog.at_level(logging.WARNING):
+ _loggers.marimo_logger().propagate = True
+ assert basic() == 1
+ assert len(caplog.records) == 1
+ assert "signature" in caplog.text
+
+ @staticmethod
+ def test_direct_cyclic_call(app) -> None:
+ # poor practice, but possible cell.
+ @app.cell
+ def cyclic():
+ a = 1
+ if False:
+ a = b # noqa: F821
+ else:
+ b = a
+ b # noqa: B018
+ return
+
+ assert cyclic.run() == (1, {"a": 1, "b": 1})
+ assert cyclic() == 1
+
def help_smoke() -> None:
app = App()
diff --git a/tests/_ast/test_pytest_toplevel.py b/tests/_ast/test_pytest_toplevel.py
index 7e0a61354d..58bf78979f 100644
--- a/tests/_ast/test_pytest_toplevel.py
+++ b/tests/_ast/test_pytest_toplevel.py
@@ -33,5 +33,11 @@ def test_add_bad(a, b, c):
assert add(a, b) == c
+class TestClassWorks:
+ def test_sanity(self):
+ assert True
+
+
if __name__ == "__main__":
app.run()
diff --git a/tests/_ast/test_toplevel.py b/tests/_ast/test_toplevel.py
index f5a433ae4f..b489480b94 100644
--- a/tests/_ast/test_toplevel.py
+++ b/tests/_ast/test_toplevel.py
@@ -142,6 +142,48 @@ class TestTopLevelExtraction:
extraction = TopLevelExtraction.from_app(InternalApp(app))
assert [TopLevelType.TOPLEVEL] == [s.type for s in extraction]
+ @staticmethod
+ def test_decorator_reversed(app) -> None:
+ with app.setup:
+ from typing import Callable
+
+ @app.cell
+ def second(wrap):
+ @wrap
+ def c() -> float:
+ return 1 + 1
+
+ @app.cell
+ def first():
+ def wrap(fn: Callable[[], float]) -> float:
+ return lambda: fn() + 1
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [TopLevelType.CELL, TopLevelType.TOPLEVEL] == [
+ s.type for s in extraction
+ ], [s.hint for s in extraction]
+
+ @staticmethod
+ def test_decorator(app) -> None:
+ with app.setup:
+ from typing import Callable
+
+ @app.cell
+ def first():
+ def wrap(fn: Callable[[], float]) -> float:
+ return lambda: fn() + 1
+
+ @app.cell
+ def second(wrap):
+ @wrap
+ def c() -> float:
+ return 1 + 1
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [TopLevelType.TOPLEVEL, TopLevelType.TOPLEVEL] == [
+ s.type for s in extraction
+ ], [s.hint for s in extraction]
+
@staticmethod
def test_function_trailing_comment(app) -> None:
@app.cell
@@ -305,3 +347,109 @@ class TestTopLevelExtraction:
assert [TopLevelType.TOPLEVEL, TopLevelType.TOPLEVEL] == [
s.type for s in extraction
], [s.hint for s in extraction]
+
+
+class TestTopLevelClasses:
+ @staticmethod
+ def test_class_converted(app) -> None:
+ @app.cell
+ def cell():
+ class Example: ...
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [
+ TopLevelType.TOPLEVEL,
+ ] == [s.type for s in extraction], [s.hint for s in extraction]
+
+ @staticmethod
+ def test_subclassing_order(app) -> None:
+ @app.cell
+ def Example():
+ class Example: ...
+
+ @app.cell
+ def SubExample(Example):
+ class SubExample(Example): ...
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [
+ TopLevelType.TOPLEVEL,
+ TopLevelType.TOPLEVEL,
+ ] == [s.type for s in extraction], [s.hint for s in extraction]
+
+ @staticmethod
+ def test_subclassing_scoped_vars(app) -> None:
+ @app.cell
+ def Example():
+ class Example: ...
+
+ @app.cell
+ def SubExample(A, Example):
+ class SubExample(Example):
+ def __init__(self):
+ self.a = A()
+
+ @app.cell
+ def _():
+ def A() -> float:
+ return 1.0
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [
+ TopLevelType.TOPLEVEL,
+ TopLevelType.TOPLEVEL,
+ TopLevelType.TOPLEVEL,
+ ] == [s.type for s in extraction], [s.hint for s in extraction]
+
+ @staticmethod
+ def test_subclassing_order_vars(app) -> None:
+ @app.cell
+ def Example(A):
+ class Example:
+ a = A()
+
+ @app.cell
+ def _():
+ def A() -> float:
+ return 1.0
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [
+ TopLevelType.CELL,
+ TopLevelType.TOPLEVEL,
+ ] == [s.type for s in extraction], [s.hint for s in extraction]
+
+ @staticmethod
+ def test_subclassing_order_vars_recursion(app) -> None:
+ @app.cell
+ def Example(A):
+ class Example:
+ class SubExample:
+ a = A()
+
+ @app.cell
+ def _():
+ def A() -> float:
+ return 1.0
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [
+ TopLevelType.CELL,
+ TopLevelType.TOPLEVEL,
+ ] == [s.type for s in extraction], [s.hint for s in extraction]
+
+ @staticmethod
+ def test_subclassing_order_breaks(app) -> None:
+ @app.cell
+ def cell(Example):
+ class SubExample(Example): ...
+
+ @app.cell
+ def _():
+ class Example: ...
+
+ extraction = TopLevelExtraction.from_app(InternalApp(app))
+ assert [
+ TopLevelType.CELL,
+ TopLevelType.TOPLEVEL,
+ ] == [s.type for s in extraction], [s.hint for s in extraction]
diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.py
index 0c45f45a94..fb6900d498 100644
--- a/tests/_ast/test_visitor.py
+++ b/tests/_ast/test_visitor.py
@@ -154,7 +154,11 @@ def test_assign_same_name() -> None:
assert v.defs == set(["f"])
assert v.refs == set(["x"])
assert v.variable_data == {
- "f": [VariableData(kind="function", required_refs={"x"})]
+ "f": [
+ VariableData(
+ kind="function", required_refs={"x"}, unbounded_refs=set()
+ )
+ ]
}
expr = "class F(): x = x"
@@ -164,7 +168,11 @@ def test_assign_same_name() -> None:
assert v.defs == set(["F"])
assert v.refs == set(["x"])
assert v.variable_data == {
- "F": [VariableData(kind="class", required_refs={"x"})]
+ "F": [
+ VariableData(
+ kind="class", required_refs={"x"}, unbounded_refs={"x"}
+ )
+ ]
}
expr = "{x: x}"
diff --git a/tests/conftest.py b/tests/conftest.py
index e009cfdefb..a38e4b87e4 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -632,6 +632,12 @@ def app() -> Generator[App, None, None]:
# A pytest hook to fail when raw marimo cells are not collected.
+# Meta testing gets a little messy, and may leave you a little testy. This is
+# increasingly coupled with the following specific tests that test testing:
+# _ast/
+# ./test_pytest
+# ./test_pytest_toplevel
+# ./test_pytest_scoped
@pytest.hookimpl
def pytest_make_collect_report(collector):
report = runner.pytest_make_collect_report(collector)
@@ -669,13 +675,20 @@ def pytest_make_collect_report(collector):
if len(classes) == 0:
report.outcome = "failed"
report.longrepr = (
- f"Expected class in {collector.path}, found none."
+ f"Expected class in {collector.path}, found none "
+ " (tests/conftest.py)."
)
return report
for cls in classes:
- if not cls.startswith("MarimoTestBlock"):
+ if not (
+ cls.startswith("MarimoTestBlock") or cls == "TestClassWorks"
+ ):
report.outcome = "failed"
- report.longrepr = f"Unknown class '{cls}' in {collector.path}"
+ report.longrepr = (
+ f"Unknown class '{cls}' in {collector.path}"
+ " (tests/conftest.py)."
+ )
+
return report
# Check the functions match cells in the app.
@@ -688,5 +701,6 @@ def pytest_make_collect_report(collector):
report.outcome = "failed"
report.longrepr = (
f"Cannot collect test(s) {', '.join(invalid)} from {tests}"
+ " (tests/conftest.py)."
)
return report