A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
style: enforce single backticks in Python docstrings (markdown, not RST) (#9645)
Akshay Agrawal917b86334795
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex c4a4b48ab4..1179bcabd5 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -30,6 +30,14 @@ repos:- id: typospass_filenames: false+ - repo: local+ hooks:+ - id: no-double-backticks-in-docstrings+ name: no double backticks in docstrings+ entry: python scripts/check_docstring_backticks.py+ language: python+ types: [python]+- repo: https://github.com/astral-sh/ruff-pre-commitrev: v0.15.10hooks:diff --git a/AGENTS.md b/AGENTS.mdindex 5c5518350b..dbbf58430b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -52,3 +52,14 @@ cd frontend && pnpm test src/path/to/file.test.ts- You MUST disclose that you are an agent at the very top of your PR description: "**This pull request was authored by a coding agent.**"- You MUST mark your PRs as drafts- See [CONTRIBUTING.md](CONTRIBUTING.md) for other PR guidelines and CLA++## Conventions++### Python++Most style rules are enforced by ruff (`pyproject.toml`) and pre-commit; run+`make py-check`. Here are some that the linter may not catch, or for which+we may not have autofixes.++- Docstrings are rendered as Markdown, not reStructuredText. Use single+ backticks for inline code (`value`), never double backticks.diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 40db052bc0..cfe4d3a5c9 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -175,7 +175,7 @@ class _SetupContext:) -> _SetupContext:"""When called with parameters, update the setup cell config.- The setup cell was already registered when ``app.setup`` ran+ The setup cell was already registered when `app.setup` ran(the property getter); this call updates that cell's config inplace rather than re-registering."""@@ -1031,12 +1031,12 @@ class InternalApp:) -> InternalApp:"""Rewrite the cell list from textual fields, in place.- Mutates ``self._app._cell_manager`` rather than replacing it,- so any caller holding ``app.cell_manager`` or- ``app.cell_manager.document`` (notably ``Session.document``)+ Mutates `self._app._cell_manager` rather than replacing it,+ so any caller holding `app.cell_manager` or+ `app.cell_manager.document` (notably `Session.document`)continues to see live state without rebinding.- Cells that survive the rewrite keep their compiled ``Cell``;+ Cells that survive the rewrite keep their compiled `Cell`;callers from save flows pass the frontend's snapshot, whichrenames/reorders/reconfigures cells but doesn't recompile."""diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex 19f34b3b9c..695a3bafb5 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -521,22 +521,22 @@ class CellManager:return Nonedef _replace_state_from(self, other: CellManager) -> None:- """Overwrite this manager's content with ``other``'s, in place.+ """Overwrite this manager's content with `other`'s, in place.- Identity-preserving substitute for ``self = other``: the- underlying ``NotebookDocument`` instance and the- ``_compiled_cells`` dict instance are kept; only their contents+ Identity-preserving substitute for `self = other`: the+ underlying `NotebookDocument` instance and the+ `_compiled_cells` dict instance are kept; only their contentsare replaced. Any object holding a reference to this manager —- most notably the owning ``Session`` (which holds- ``cell_manager.document`` as ``session.document``) — continues+ most notably the owning `Session` (which holds+ `cell_manager.document` as `session.document`) — continuesto see live state without rebinding.- ``unparsable`` is copied. ``_cell_id_generator.seen_ids`` is+ `unparsable` is copied. `_cell_id_generator.seen_ids` isunioned (never narrowed) so we don't recycle an id seen- previously even if it's gone from ``other``.+ previously even if it's gone from `other`.Transitional helper: cell-list bulk-replace bypasses- ``NotebookDocument.apply``. Goes away once full-document+ `NotebookDocument.apply`. Goes away once full-documentrebuilds are expressed as diff Transactions."""self._document._replace_cells(list(other._document._cells))diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex d30413b44f..be76ea904d 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -270,7 +270,7 @@ class _OptionalValueOption(click.Option):"""A click Option that supports an optional value.Works around a regression in click 8.3.x where the documented- ``is_flag=False, flag_value=...`` pattern is broken.+ `is_flag=False, flag_value=...` pattern is broken.See: https://github.com/pallets/click/issues/3084"""diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 8a06b01922..9ab6385425 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -32,11 +32,11 @@ def _enrich_branded_types(branded types.msgspec.json.schema_components() strips NewType wrappers, emitting plain- ``{type: string}`` for fields like ``CellId_t``. This function:+ `{type: string}` for fields like `CellId_t`. This function:- 1. Adds named schemas for each branded type (e.g. ``CellId: {type: string}``).+ 1. Adds named schemas for each branded type (e.g. `CellId: {type: string}`).2. Walks every model struct's type hints and replaces inline schemas with- ``$ref`` pointers wherever a field's annotation is (or contains) a+ `$ref` pointers wherever a field's annotation is (or contains) aregistered NewType."""import types as _types@@ -77,7 +77,7 @@ def _enrich_branded_types(return origin is Union or origin is getattr(_types, "UnionType", None)def resolve(ty: Any) -> dict[str, Any] | None:- """Produce a branded schema for *ty*, or ``None``."""+ """Produce a branded schema for *ty*, or `None`."""if ty in branded:return make_ref(branded[ty][0])diff --git a/marimo/_cli/pair/commands.py b/marimo/_cli/pair/commands.pyindex adf618091c..91bc38b3d4 100644--- a/marimo/_cli/pair/commands.py+++ b/marimo/_cli/pair/commands.py@@ -52,14 +52,14 @@ def _opencode_skill_dirs() -> list[Path]:"""Return directories where an opencode skill (or compatible layout) may live.https://opencode.ai/docs/skills/- Checked roots are the parent of ``<skill-name>/SKILL.md`` for:-- - Project opencode: ``.opencode/skills/``- - Global opencode: ``~/.config/opencode/skills/``- - Project Claude-compatible: ``.claude/skills/``- - Global Claude-compatible: ``~/.claude/skills/``- - Project agent-compatible: ``.agents/skills/``- - Global agent-compatible: ``~/.agents/skills/``+ Checked roots are the parent of `<skill-name>/SKILL.md` for:++ - Project opencode: `.opencode/skills/`+ - Global opencode: `~/.config/opencode/skills/`+ - Project Claude-compatible: `.claude/skills/`+ - Global Claude-compatible: `~/.claude/skills/`+ - Project agent-compatible: `.agents/skills/`+ - Global agent-compatible: `~/.agents/skills/`"""cwd = Path.cwd()home = Path.home()@@ -74,7 +74,7 @@ def _opencode_skill_dirs() -> list[Path]:def pair_agents() -> dict[str, AgentConfig]:- """Return agent configs; paths use ``Path.cwd()`` at call time."""+ """Return agent configs; paths use `Path.cwd()` at call time."""cwd = Path.cwd()home = Path.home()return {diff --git a/marimo/_code_mode/_better_inspect.py b/marimo/_code_mode/_better_inspect.pyindex 8397f63f6c..b64a16e889 100644--- a/marimo/_code_mode/_better_inspect.py+++ b/marimo/_code_mode/_better_inspect.py@@ -9,25 +9,25 @@ to feed to tools.These two functions fix that:-``better_dir(obj)``+`better_dir(obj)`Filters out all private/dunder attributes.- Appends type annotations to data attributes (e.g. ``host: str``).- Appends full signatures to callables (e.g. ``send(data: bytes) -> int``).- Returns a plain ``list[str]`` so it's a drop-in ``__dir__`` return value.- Uses ``object.__dir__(obj)`` internally to avoid infinite recursion- when wired as ``__dir__``.+ Appends type annotations to data attributes (e.g. `host: str`).+ Appends full signatures to callables (e.g. `send(data: bytes) -> int`).+ Returns a plain `list[str]` so it's a drop-in `__dir__` return value.+ Uses `object.__dir__(obj)` internally to avoid infinite recursion+ when wired as `__dir__`.-``better_help(obj)``+`better_help(obj)`Returns a compact, markdown-ish summary: class name, docstring,attributes with types, methods with signatures and one-line docs.No pager, no dunders, no self parameter, no scroll.- Returns ``str`` so it can be wired to ``__repr__`` and will also be- picked up by ``help()`` via pydoc's repr fallback.+ Returns `str` so it can be wired to `__repr__` and will also be+ picked up by `help()` via pydoc's repr fallback.-``@helpable``- Class decorator that rewrites ``__doc__`` at definition time so- ``help()`` shows the clean summary natively via pydoc -- no need to- touch ``__repr__``. Also wires ``__dir__`` automatically.+`@helpable`+ Class decorator that rewrites `__doc__` at definition time so+ `help()` shows the clean summary natively via pydoc -- no need to+ touch `__repr__`. Also wires `__dir__` automatically.Usage::@@ -71,16 +71,16 @@ from typing import Anydef _public_attrs(obj: Any) -> list[str]:- """Return sorted public attribute names using ``object.__dir__``.+ """Return sorted public attribute names using `object.__dir__`.- Uses ``object.__dir__(obj)`` instead of ``dir(obj)`` to avoid infinite- recursion when this is called from inside ``__dir__`` itself.+ Uses `object.__dir__(obj)` instead of `dir(obj)` to avoid infinite+ recursion when this is called from inside `__dir__` itself.Args:obj: Any Python object.Returns:- Sorted list of attribute names that don't start with ``_``.+ Sorted list of attribute names that don't start with `_`."""# Enum classes: only show member names.if isinstance(obj, type) and issubclass(obj, Enum):@@ -97,9 +97,9 @@ _MISSING: Any = object()def _safe_getattr_static(obj: Any, name: str) -> Any:"""Fetch an attribute without invoking descriptors or properties.- Uses ``inspect.getattr_static`` so that ``dir()``/``help()`` never+ Uses `inspect.getattr_static` so that `dir()`/`help()` nevertrigger property getters (which could raise or have side effects).- Returns ``_MISSING`` if the attribute cannot be retrieved.+ Returns `_MISSING` if the attribute cannot be retrieved."""try:return inspect.getattr_static(obj, name)@@ -121,14 +121,14 @@ def _type_label(val: Any) -> str:def _unwrap_callable(val: Any) -> Any:- """Unwrap ``classmethod``/``staticmethod`` to the underlying function."""+ """Unwrap `classmethod`/`staticmethod` to the underlying function."""if isinstance(val, (classmethod, staticmethod)):return val.__func__return valdef _format_signature(func: Any) -> str:- """Return a string signature with ``self``/``cls`` stripped."""+ """Return a string signature with `self`/`cls` stripped."""sig = inspect.signature(func)params = [p for n, p in sig.parameters.items() if n not in ("self", "cls")]return str(sig.replace(parameters=params))@@ -141,21 +141,21 @@ def _first_doc_line(doc: str | None) -> str:def better_dir(obj: Any) -> list[str]:- """A cleaner ``dir()`` that shows only the public interface.+ """A cleaner `dir()` that shows only the public interface.- Designed to be returned directly from ``__dir__``::+ Designed to be returned directly from `__dir__`::def __dir__(self):return better_dir(self)- Improvements over built-in ``dir()``:+ Improvements over built-in `dir()`:- Excludes all private and dunder attributes.- - Data attributes show their type -> ``host: str``- - Callables show their full signature -> ``send(data: bytes) -> int``+ - Data attributes show their type -> `host: str`+ - Callables show their full signature -> `send(data: bytes) -> int`- Sorted alphabetically for easy scanning.- - Returns ``list[str]`` -- the exact type ``__dir__`` requires.- - Safe from infinite recursion (uses ``object.__dir__`` internally).+ - Returns `list[str]` -- the exact type `__dir__` requires.+ - Safe from infinite recursion (uses `object.__dir__` internally).Args:obj: Any Python object (instance, class, module, ...).@@ -198,24 +198,24 @@ def better_dir(obj: Any) -> list[str]:def better_help(obj: Any) -> str:- """A compact, AI-friendly replacement for ``help()``.+ """A compact, AI-friendly replacement for `help()`.- Can be used standalone, or applied automatically via the ``@helpable``- decorator which rewrites ``__doc__`` at class definition time so that- ``help()`` shows this output natively through pydoc.+ Can be used standalone, or applied automatically via the `@helpable`+ decorator which rewrites `__doc__` at class definition time so that+ `help()` shows this output natively through pydoc.- Improvements over built-in ``help()``:+ Improvements over built-in `help()`:- Markdown-style heading with the class/module name.- Shows only the first line of each docstring -- enough to understandintent without the filler.- - ``self`` is stripped from method signatures by ``inspect.signature``.+ - `self` is stripped from method signatures by `inspect.signature`.- Attributes and methods are grouped into clearly labelled sections.- No pager, no quitting, no scrolling -- just a string.- Output is structured for LLMs: paste it straight into a prompt,a README, or a tool description.- - Returns ``str`` instead of printing, so it composes cleanly with- logging, f-strings, ``__repr__``, etc.+ - Returns `str` instead of printing, so it composes cleanly with+ logging, f-strings, `__repr__`, etc.Args:obj: Any Python object (instance, class, module, ...).@@ -318,8 +318,8 @@ def _build_enum_help(cls: type) -> str:def _enum_member_doc(cls: type, name: str) -> str:"""Extract the inline docstring for an enum member, if any.- Python 3.13+ stores the immediately-following ``\"\"\"docstring\"\"\"``- literal as ``member.__doc__``. On older Pythons this is just the+ Python 3.13+ stores the immediately-following `\"\"\"docstring\"\"\"`+ literal as `member.__doc__`. On older Pythons this is just theclass docstring; we treat that as "no per-member doc" and return ""."""member = cls[name] # type: ignore[index]@@ -334,7 +334,7 @@ def _build_help(cls: type) -> str:Works at decoration time with no instance available, so it inspectsthe class itself -- methods via the class dict, and type hints via- ``__annotations__`` and ``__init__`` annotations.+ `__annotations__` and `__init__` annotations.Args:cls: The class to document.@@ -419,10 +419,10 @@ def _build_help(cls: type) -> str:class _HelpableEnumMeta(EnumMeta):- """Metaclass for enum classes that makes ``dir(EnumClass)`` clean.+ """Metaclass for enum classes that makes `dir(EnumClass)` clean.- ``EnumType`` is the default metaclass for all ``Enum`` subclasses.- By subclassing it and overriding ``__dir__``, ``dir(MyEnum)`` returns+ `EnumType` is the default metaclass for all `Enum` subclasses.+ By subclassing it and overriding `__dir__`, `dir(MyEnum)` returnsonly the enum member names with values."""@@ -431,12 +431,12 @@ class _HelpableEnumMeta(EnumMeta):class _HelpableMeta(type):- """Metaclass that makes ``dir(ClassName)`` return ``better_dir`` output.+ """Metaclass that makes `dir(ClassName)` return `better_dir` output.- Without this, ``dir(cls)`` always calls ``type.__dir__(cls)`` which+ Without this, `dir(cls)` always calls `type.__dir__(cls)` whichreturns the raw attribute list including dunders. By overriding- ``__dir__`` on the metaclass, ``dir(MyClass)`` now returns the same- clean list that ``dir(instance)`` does.+ `__dir__` on the metaclass, `dir(MyClass)` now returns the same+ clean list that `dir(instance)` does."""def __dir__(cls) -> list[str]: # type: ignore[override]@@ -444,13 +444,13 @@ class _HelpableMeta(type):def helpable(cls: type) -> type:- """Class decorator that wires ``better_dir`` and ``better_help`` automatically.+ """Class decorator that wires `better_dir` and `better_help` automatically.- Rewrites ``__doc__`` on the class at definition time so that ``help(obj)``+ Rewrites `__doc__` on the class at definition time so that `help(obj)`shows a clean, AI-friendly summary through pydoc's normal machinery. Also- installs ``__dir__`` to return ``better_dir(self)``.+ installs `__dir__` to return `better_dir(self)`.- The original docstring is preserved in ``_original_doc__`` and used as the+ The original docstring is preserved in `_original_doc__` and used as thedescription line in the generated help output.Works on both classes and instances::@@ -466,21 +466,21 @@ def helpable(cls: type) -> type:help(MyClient()) # clean output (via __doc__)Caveat:- For classes whose metaclass is the default ``type``, the decorator- recreates the class with ``_HelpableMeta`` so that ``dir(Class)``- is also clean. Methods that use zero-argument ``super()`` inside+ For classes whose metaclass is the default `type`, the decorator+ recreates the class with `_HelpableMeta` so that `dir(Class)`+ is also clean. Methods that use zero-argument `super()` insidesuch classes will still bind to the *original* class (via the- ``__class__`` closure cell the compiler injects), which is not in+ `__class__` closure cell the compiler injects), which is not inthe new class's MRO. In practice this is only an issue if thedecorated class subclasses another class *and* its methods call- ``super()``; keep ``@helpable`` for simple, leaf-level data/API- classes, or use explicit ``super(ClassName, self)`` calls.+ `super()`; keep `@helpable` for simple, leaf-level data/API+ classes, or use explicit `super(ClassName, self)` calls.Args:cls: The class to decorate.Returns:- The decorated class with new ``__doc__`` and ``__dir__``.+ The decorated class with new `__doc__` and `__dir__`."""original_doc = cls.__doc__diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.pyindex a6233ccbbd..40fed04fa6 100644--- a/marimo/_code_mode/_context.py+++ b/marimo/_code_mode/_context.py@@ -103,8 +103,8 @@ if TYPE_CHECKING:class CellStatusType(str, Enum, metaclass=_HelpableEnumMeta):"""Synthesized cell execution status.- Returned by ``NotebookCell.status``. Compares equal to plain- strings, so ``cell.status == "idle"`` works as expected.+ Returned by `NotebookCell.status`. Compares equal to plain+ strings, so `cell.status == "idle"` works as expected."""idle = "idle"@@ -143,14 +143,14 @@ class CellError:Parameters----------- kind : ``"graph"`` or ``"runtime"``- ``"graph"`` — a dataflow-graph error that *prevents* execution+ kind : `"graph"` or `"runtime"`+ `"graph"` — a dataflow-graph error that *prevents* execution(multiply-defined variable, cycle, etc.).- ``"runtime"`` — an exception raised during execution.+ `"runtime"` — an exception raised during execution.msg : strHuman-readable description.exception : Exception | None- The original ``Exception`` for runtime errors; ``None`` for+ The original `Exception` for runtime errors; `None` forgraph errors."""@@ -163,7 +163,7 @@ class CellError:class CellRuntimeState(Protocol):- """The subset of ``CellImpl`` that ``NotebookCell`` reads."""+ """The subset of `CellImpl` that `NotebookCell` reads."""@propertydef code(self) -> str: ...@@ -194,7 +194,7 @@ def get_context(skip_validation: bool = False,skip_staleness_check: bool = False,) -> AsyncCodeModeContext:- """Return an ``AsyncCodeModeContext`` for the running kernel.+ """Return an `AsyncCodeModeContext` for the running kernel.Use as an async context manager::@@ -211,10 +211,10 @@ def get_context(intentionally need to insert code that would fail validation(e.g. incomplete stubs the user plans to fix by hand).skip_staleness_check : bool, default False- When False (the default), ``edit_cell`` raises+ When False (the default), `edit_cell` raises:class:`StaleCellError` if the agent tries to overwrite a cellwhose code has changed since the agent last read it (e.g. via- ``ctx.cells[cell_id]``). Set to True to overwrite blindly —+ `ctx.cells[cell_id]`). Set to True to overwrite blindly —useful when the agent intentionally discards prior content."""runtime_ctx = _get_runtime_context()@@ -230,10 +230,10 @@ def get_context(class StaleCellError(RuntimeError):- """Raised when ``edit_cell`` targets a cell the agent has not read at+ """Raised when `edit_cell` targets a cell the agent has not read atits current version.- ``stale_cells`` is the full set of cells in the same boat, so the agent+ `stale_cells` is the full set of cells in the same boat, so the agentcan re-read all of them in one pass."""@@ -273,12 +273,12 @@ class NotebookCell:status : CellStatusType | NoneSynthesized execution status. Priority order:transient state (queued/running/disabled) > stale > last run result.- ``None`` if the cell has never been registered in the graph.+ `None` if the cell has never been registered in the graph.errors : list[CellError]Structured errors affecting this cell.- Each entry is a ``CellError`` with ``kind``, ``msg``, and- ``exception`` fields. Covers both runtime exceptions- (e.g. ``NameError``) and graph errors (multiply-defined+ Each entry is a `CellError` with `kind`, `msg`, and+ `exception` fields. Covers both runtime exceptions+ (e.g. `NameError`) and graph errors (multiply-definedvariables, cycles, etc.)."""@@ -336,16 +336,16 @@ class NotebookCell:Possible values:- - ``"idle"`` — ran successfully, up to date.- - ``"exception"`` — cell raised an exception.- - ``"stale"`` — needs re-run (code edited, inputs changed, or never run).- - ``"cancelled"`` — ancestor raised an exception.- - ``"interrupted"`` — execution was interrupted.- - ``"marimo-error"`` — prevented from executing (e.g. multiply-defined name).- - ``"disabled"`` — cell is disabled.- - ``"queued"`` — waiting to run.- - ``"running"`` — currently executing.- - ``None`` — empty cell, never registered in the graph.+ - `"idle"` — ran successfully, up to date.+ - `"exception"` — cell raised an exception.+ - `"stale"` — needs re-run (code edited, inputs changed, or never run).+ - `"cancelled"` — ancestor raised an exception.+ - `"interrupted"` — execution was interrupted.+ - `"marimo-error"` — prevented from executing (e.g. multiply-defined name).+ - `"disabled"` — cell is disabled.+ - `"queued"` — waiting to run.+ - `"running"` — currently executing.+ - `None` — empty cell, never registered in the graph.Priority: transient state (queued/running/disabled) >stale > last run result.@@ -377,8 +377,8 @@ class NotebookCell:"""All errors affecting this cell.Returns a list of :class:`CellError` objects. Each has a- ``kind`` (``"graph"`` or ``"runtime"``), a human-readable- ``msg``, and for runtime errors the original ``exception``.+ `kind` (`"graph"` or `"runtime"`), a human-readable+ `msg`, and for runtime errors the original `exception`.Returns an empty list when the cell is healthy."""@@ -428,7 +428,7 @@ class _CellsView:ctx.cells["Abcd1234"] # by cell IDctx.cells["my_cell"] # by cell name- Iteration yields ``NotebookCell`` objects with runtime status::+ Iteration yields `NotebookCell` objects with runtime status::for cell in ctx.cells:print(cell.id, cell.code, cell.status)@@ -470,9 +470,9 @@ class _CellsView:return doc_cell.name or Nonedef _resolve(self, target: str) -> CellId_t:- """Resolve a cell ID or cell name to a ``CellId_t``.+ """Resolve a cell ID or cell name to a `CellId_t`.- Raises ``KeyError`` if not found.+ Raises `KeyError` if not found."""if target in self._doc:return CellId_t(target)@@ -619,7 +619,7 @@ class AsyncCodeModeContext:ctx.edit_cell("my_cell", code="x = 42")ctx.delete_cell("old_cell")- Read cells via ``ctx.cells[key]`` where *key* is an integer index,+ Read cells via `ctx.cells[key]` where *key* is an integer index,cell ID string, or cell name."""@@ -847,7 +847,7 @@ class AsyncCodeModeContext:return cell is not None and cell.exception is not Nonedef _cell_label(self, cell_id: CellId_t) -> str:- """Return a display label: ``'id' (name)`` or ``'id'``."""+ """Return a display label: `'id' (name)` or `'id'`."""short = repr(str(cell_id)[:8])doc_cell = self._document.get(cell_id)if doc_cell and doc_cell.name:@@ -869,7 +869,7 @@ class AsyncCodeModeContext:Mutations via :meth:`run_cell` update the kernel globals but*not* the scratchpad's copy. Read values through this property- (``ctx.globals["x"]``) rather than bare variable names.+ (`ctx.globals["x"]`) rather than bare variable names."""return self._kernel.globals@@ -906,10 +906,10 @@ class AsyncCodeModeContext:# ------------------------------------------------------------------def _resolve_target(self, target: str) -> CellId_t:- """Resolve a cell ID or name to a ``CellId_t``.+ """Resolve a cell ID or name to a `CellId_t`.Checks the live graph first, then pending adds (by ID and by- name), then queued renames from ``edit_cell``.+ name), then queued renames from `edit_cell`."""# Try the live graph.try:@@ -939,10 +939,10 @@ class AsyncCodeModeContext:def _resolve_new_cell(self, name: str | None) -> tuple[CellId_t, str | None]:- """Return ``(cell_id, resolved_name)`` for a new cell.+ """Return `(cell_id, resolved_name)` for a new cell.- The ``"setup"`` name is special-cased to use the well-known setup- cell ID. Raises ``ValueError`` if a setup cell already exists.+ The `"setup"` name is special-cased to use the well-known setup+ cell ID. Raises `ValueError` if a setup cell already exists."""if name == SETUP_CELL_NAME:# Check if a setup cell already exists (by name or by ID).@@ -977,9 +977,9 @@ class AsyncCodeModeContext:"""Queue a new cell. Returns the new cell's ID.The returned ID can be used in subsequent operations within the- same batch (e.g. as an ``after`` target for the next cell).+ same batch (e.g. as an `after` target for the next cell).- Cells are not executed automatically. Use ``run_cell`` to queue+ Cells are not executed automatically. Use `run_cell` to queuethem for execution::cid = ctx.create_cell("x = 1")@@ -1002,16 +1002,16 @@ class AsyncCodeModeContext:Args:code (str): Python source code for the cell.before (str, optional): Insert before this cell (ID or name).- Mutually exclusive with ``after``.+ Mutually exclusive with `after`.after (str, optional): Insert after this cell (ID or name).- Mutually exclusive with ``before``.+ Mutually exclusive with `before`.hide_code (bool): Collapse the code editor in the UI.Defaults to True.disabled (bool): Prevent the cell from executing.Defaults to False.column (int, optional): Column index for multi-column layouts.name (str, optional): Cell names are a human-facing label,- reserved for special cases (e.g. ``"setup"``). Prefer+ reserved for special cases (e.g. `"setup"`). Preferreferencing cells by the returned cell ID unlessnaming is important for the user."""@@ -1055,9 +1055,9 @@ class AsyncCodeModeContext:"""Queue an update to an existing cell's code and/or config.Only the arguments you explicitly pass are changed — the cell's- existing config is preserved for any argument left as ``None``.+ existing config is preserved for any argument left as `None`.- Editing a cell does not automatically execute it. Use ``run_cell``+ Editing a cell does not automatically execute it. Use `run_cell`to queue it for execution::ctx.edit_cell("my_cell", "x = 42")@@ -1205,9 +1205,9 @@ class AsyncCodeModeContext:Args:target (str): Cell ID or cell name to move.before (str, optional): Place before this cell (ID or name).- Mutually exclusive with ``after``.+ Mutually exclusive with `after`.after (str, optional): Place after this cell (ID or name).- Mutually exclusive with ``before``.+ Mutually exclusive with `before`."""self._require_entered()if before is not None and after is not None:@@ -1233,10 +1233,10 @@ class AsyncCodeModeContext:"""Queue a cell for execution.Cells created or edited in the same batch are not executed- automatically — use ``run_cell`` to mark them for execution.+ automatically — use `run_cell` to mark them for execution.Can also be used to re-run an existing cell without editing it.- All queued ``run_cell`` targets are executed in a single batch+ All queued `run_cell` targets are executed in a single batchon context exit, after structural operations (create/edit/delete)have been applied.@@ -1287,20 +1287,20 @@ class AsyncCodeModeContext:Launches a headless Chromium browser (reused across calls)connected to this server in kiosk mode.- Requires ``playwright`` + its Chromium binary::+ Requires `playwright` + its Chromium binary::ctx.install_packages("playwright")# then once: python -m playwright install chromium- Does **not** require ``async with``.+ Does **not** require `async with`.Args:target: Cell to screenshot.- - ``None`` — last cell.- - ``int`` — cell index (negative OK).- - ``str`` — cell ID or name.- - ``NotebookCell`` — e.g. ``ctx.cells[0]``.+ - `None` — last cell.+ - `int` — cell index (negative OK).+ - `str` — cell ID or name.+ - `NotebookCell` — e.g. `ctx.cells[0]`.For an object defined by a cell, resolve first::@@ -1308,12 +1308,12 @@ class AsyncCodeModeContext:img = await ctx.screenshot(cid)timeout_ms: Max wait (ms) for the output to be visible.- as_data_url: Return ``data:image/png;base64,...`` str+ as_data_url: Return `data:image/png;base64,...` strinstead of raw bytes.save_to: Also write the PNG to this path.Returns:- ``bytes`` (PNG), or ``str`` (data URL) if *as_data_url*.+ `bytes` (PNG), or `str` (data URL) if *as_data_url*.Raises:ScreenshotError: Missing playwright, missing browser,@@ -1376,8 +1376,8 @@ class AsyncCodeModeContext:async def close_screenshot_session(self) -> None:"""Close the Playwright browser opened by :meth:`screenshot`.- Called automatically in ``__aexit__``. Call this explicitly- when using ``screenshot()`` outside ``async with`` to avoid+ Called automatically in `__aexit__`. Call this explicitly+ when using `screenshot()` outside `async with` to avoidleaking a headless browser process."""if self._screenshot_session is not None:@@ -1439,10 +1439,10 @@ class AsyncCodeModeContext:)def find_cell_defining_object(self, obj: Any) -> CellId_t | None:- """Return the cell ID whose ``defs`` include a variable bound to *obj*.+ """Return the cell ID whose `defs` include a variable bound to *obj*.- Uses identity (``is``) matching against kernel globals.- Returns ``None`` if no cell defines *obj*.+ Uses identity (`is`) matching against kernel globals.+ Returns `None` if no cell defines *obj*.Example::@@ -1471,12 +1471,12 @@ class AsyncCodeModeContext:"""Compile and graph-check every op before mutating real state.For each op with code:- 1. ``compile_cell`` — validates syntax, extracts defs/refs.+ 1. `compile_cell` — validates syntax, extracts defs/refs.2. Temporarily register in the graph to detect multiply-definednames and cycles.3. Always clean up so the graph is left unchanged.- Raises ``SyntaxError`` for invalid code or ``RuntimeError`` for+ Raises `SyntaxError` for invalid code or `RuntimeError` forgraph conflicts (multiply-defined names, cycles)."""graph = self.graph@@ -1741,7 +1741,7 @@ class AsyncCodeModeContext:```Args:- element: A marimo UI element (e.g. ``mo.ui.slider``).+ element: A marimo UI element (e.g. `mo.ui.slider`).value: The new value, matching the type the element expects."""self._require_entered()diff --git a/marimo/_code_mode/_packages.py b/marimo/_code_mode/_packages.pyindex 96e5fddd95..3e8e1a6d83 100644--- a/marimo/_code_mode/_packages.py+++ b/marimo/_code_mode/_packages.py@@ -1,8 +1,8 @@# Copyright 2026 Marimo. All rights reserved.-"""Packages: queued package operations for ``AsyncCodeModeContext``.+"""Packages: queued package operations for `AsyncCodeModeContext`.Accessed via :attr:`AsyncCodeModeContext.packages`. Mutations are-queued during the ``async with`` block and flushed on exit *before*+queued during the `async with` block and flushed on exit *before*cell operations."""@@ -58,7 +58,7 @@ class Packages:"""Package management for the running notebook's environment.Accessed as :attr:`AsyncCodeModeContext.packages`. Mutations are- queued during the ``async with`` block and flushed on exit *before*+ queued during the `async with` block and flushed on exit *before*cell operations, so newly added cells can import newly installedpackages.diff --git a/marimo/_code_mode/_plan.py b/marimo/_code_mode/_plan.pyindex 9c3b4dc57f..023ae447a6 100644--- a/marimo/_code_mode/_plan.py+++ b/marimo/_code_mode/_plan.py@@ -142,7 +142,7 @@ def _build_plan(def _validate_ops(ops: list[_Op]) -> None:- """Check for conflicting operations. Raises ``ValueError`` on conflict."""+ """Check for conflicting operations. Raises `ValueError` on conflict."""deleted: set[CellId_t] = set()updated: set[CellId_t] = set()moved: set[CellId_t] = set()diff --git a/marimo/_code_mode/screenshot.py b/marimo/_code_mode/screenshot.pyindex 3648dd5c5f..fa77aef3a9 100644--- a/marimo/_code_mode/screenshot.py+++ b/marimo/_code_mode/screenshot.py@@ -57,13 +57,13 @@ class ScreenshotError(RuntimeError):def _to_data_url(image: bytes) -> str:- """Convert raw PNG bytes to a ``data:image/png;base64,...`` string."""+ """Convert raw PNG bytes to a `data:image/png;base64,...` string."""encoded = base64.b64encode(image).decode("ascii")return f"data:image/png;base64,{encoded}"def _require_playwright() -> Any:- """Import ``async_playwright``, raising :class:`ScreenshotError` if missing."""+ """Import `async_playwright`, raising :class:`ScreenshotError` if missing."""from marimo._dependencies.dependencies import DependencyManagerif not DependencyManager.playwright.has():diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex f71d1f264c..bac58a3d5a 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -512,14 +512,14 @@ class LintConfig(TypedDict, total=False):"""Configuration for lint rule selection.Follows ruff-inspired semantics for selecting which rules to run- during ``marimo check``.+ during `marimo check`.**Keys.**- - ``select``: list of rule code prefixes that replaces the default- enabled set. Use ``"ALL"`` to select all rules.- Example: ``["MB", "MR001"]``- - ``ignore``: list of rule code prefixes to remove from the+ - `select`: list of rule code prefixes that replaces the default+ enabled set. Use `"ALL"` to select all rules.+ Example: `["MB", "MR001"]`+ - `ignore`: list of rule code prefixes to remove from theenabled set."""diff --git a/marimo/_convert/ipynb/to_ir.py b/marimo/_convert/ipynb/to_ir.pyindex 4ac77e3382..cd9bf20325 100644--- a/marimo/_convert/ipynb/to_ir.py+++ b/marimo/_convert/ipynb/to_ir.py@@ -53,18 +53,18 @@ _CLOSE_P_RE = re.compile(r"</p>", re.IGNORECASE)def _strip_paragraph_tags(source: str) -> str:- """Remove bare ``<p>`` / ``</p>`` HTML tags from markdown source.+ """Remove bare `<p>` / `</p>` HTML tags from markdown source.- Jupyter markdown cells often wrap content in ``<p>…</p>`` tags which are+ Jupyter markdown cells often wrap content in `<p>…</p>` tags which areredundant in plain markdown and can break LaTeX rendering inside- ``mo.md()``.+ `mo.md()`.- Only bare ``<p>`` tags (without attributes) are removed. Styled tags such- as ``<p style="color: red">`` are preserved because they carry semantic- meaning. The matching ``</p>`` is only removed when it closes a bare- ``<p>``.+ Only bare `<p>` tags (without attributes) are removed. Styled tags such+ as `<p style="color: red">` are preserved because they carry semantic+ meaning. The matching `</p>` is only removed when it closes a bare+ `<p>`.- Closing ``</p>`` tags for bare opens are replaced with a newline to+ Closing `</p>` tags for bare opens are replaced with a newline topreserve paragraph separation. Content inside fenced code blocks isleft untouched."""@@ -1266,7 +1266,7 @@ def bind_cell_metadata(- If "hide-cell" or the standard nbconvert "remove-input" tag is present,the cell is marked hidden (and the tag is consumed).- - The Jupyter UI hint ``metadata.jupyter.source_hidden`` is also treated as+ - The Jupyter UI hint `metadata.jupyter.source_hidden` is also treated asa hidden-code signal.- Remaining tags (if any) are inserted as a comment at the top of the source.- If marimo-specific metadata is present, it is used to restore cell config.diff --git a/marimo/_ipc/connection.py b/marimo/_ipc/connection.pyindex a8a1507968..4ece955ddd 100644--- a/marimo/_ipc/connection.py+++ b/marimo/_ipc/connection.py@@ -94,8 +94,8 @@ class Channel(typing.Generic[T]):Args:context: ZeroMQ context for creating socketsmsg_type: The type to decode incoming messages as. Accepts- concrete types, union types (e.g. ``A | B``), and NewTypes;- msgspec's ``Decoder`` handles all three.+ concrete types, union types (e.g. `A | B`), and NewTypes;+ msgspec's `Decoder` handles all three.maxsize: Maximum queue size (0 = unlimited)"""import zmqdiff --git a/marimo/_lint/linter.py b/marimo/_lint/linter.pyindex 7f4f59c106..e421ee3f06 100644--- a/marimo/_lint/linter.py+++ b/marimo/_lint/linter.py@@ -120,7 +120,7 @@ class Linter:def _rule_engine_for_file(self, file_path: str) -> RuleEngine:"""Return a RuleEngine for the given file.- If the file contains PEP 723 ``[tool.marimo.lint]`` metadata and no+ If the file contains PEP 723 `[tool.marimo.lint]` metadata and noexplicit rules were provided, create a per-file engine that mergesthe file-level config with the global lint config."""diff --git a/marimo/_lint/rule_selector.py b/marimo/_lint/rule_selector.pyindex b32ae12ce4..f4beab4372 100644--- a/marimo/_lint/rule_selector.py+++ b/marimo/_lint/rule_selector.py@@ -33,9 +33,9 @@ def resolve_rules(3. Return instantiated rules in sorted code order.Args:- config: LintConfig with optional ``select`` and ``ignore`` keys.+ config: LintConfig with optional `select` and `ignore` keys.all_rules: Available rule classes keyed by code.- Defaults to ``RULE_CODES`` when None.+ Defaults to `RULE_CODES` when None.Returns:Instantiated LintRule list, sorted by code.diff --git a/marimo/_lint/rules/runtime/reusable_definition_order.py b/marimo/_lint/rules/runtime/reusable_definition_order.pyindex 86a7285e8b..a75a2ead01 100644--- a/marimo/_lint/rules/runtime/reusable_definition_order.py+++ b/marimo/_lint/rules/runtime/reusable_definition_order.py@@ -28,7 +28,7 @@ class ReusableDefinitionOrderRule(UnsafeFixRule):"""MR003: Invalid ordering of potentially reusable definitions.This rule detects cells that could be reusable definitions (i.e., decorated- with ``@app.function`` or ``@app.class_definition``) but which _cannot_ be+ with `@app.function` or `@app.class_definition`) but which _cannot_ besafely serialized as reusable due to the ordering of marimo cells.diff --git a/marimo/_messaging/notebook/changes.py b/marimo/_messaging/notebook/changes.pyindex d1de5e67db..9c88a8d634 100644--- a/marimo/_messaging/notebook/changes.py+++ b/marimo/_messaging/notebook/changes.py@@ -49,7 +49,7 @@ class ReorderCells():"""Replace the full cell ordering.- Cell IDs present in the document but missing from ``cell_ids``+ Cell IDs present in the document but missing from `cell_ids`are appended at the end. IDs not in the document are ignored."""@@ -106,9 +106,9 @@ TransactionSource = Literal[class Transaction(msgspec.Struct, frozen=True, rename="camel"):"""An atomic batch of changes applied to a NotebookDocument.- ``source`` identifies the writer (e.g. ``"frontend"``, ``"kernel"``).- ``version`` is ``None`` when created and stamped by- ``NotebookDocument.apply()``.+ `source` identifies the writer (e.g. `"frontend"`, `"kernel"`).+ `version` is `None` when created and stamped by+ `NotebookDocument.apply()`."""changes: tuple[DocumentChange, ...]diff --git a/marimo/_messaging/notebook/document.py b/marimo/_messaging/notebook/document.pyindex 119a20fad9..47fa91e130 100644--- a/marimo/_messaging/notebook/document.py+++ b/marimo/_messaging/notebook/document.py@@ -1,19 +1,19 @@# Copyright 2026 Marimo. All rights reserved."""Canonical notebook document model.-``NotebookDocument`` maintains an ordered list of ``NotebookCell`` entries and-applies ``Transaction``s atomically. It is a pure state machine — no IO, no+`NotebookDocument` maintains an ordered list of `NotebookCell` entries and+applies `Transaction`s atomically. It is a pure state machine — no IO, nonotifications, no kernel interaction.Concurrency model------------------The session holds the single ``NotebookDocument`` and applies+The session holds the single `NotebookDocument` and appliestransactions sequentially. There is no concurrent access. Everythingthat goes through this model is last-write-wins with intra-transaction-conflict detection (``_validate`` catches contradictions like delete ++conflict detection (`_validate` catches contradictions like delete +update on the same cell within one batch).-``SetCode`` is a wholesale replacement without character-level+`SetCode` is a wholesale replacement without character-levelmerge. Loro CRDT may handle real-time collaborative text editing inthe future, but cell code would then live outside this model entirely."""@@ -50,8 +50,8 @@ from marimo._types.ids import CellId_tclass NotebookCell(msgspec.Struct):"""A single cell in the document. Mutable — owned by the document.- ``version`` increments on each ``SetCode`` that actually changes- ``code``. Other property changes don't bump it.+ `version` increments on each `SetCode` that actually changes+ `code`. Other property changes don't bump it."""id: CellId_t@@ -115,21 +115,21 @@ class NotebookDocument:return self._versiondef get_cell(self, cell_id: CellId_t) -> NotebookCell:- """Lookup by ID. Raises ``KeyError`` if not found."""+ """Lookup by ID. Raises `KeyError` if not found."""for cell in self._cells:if cell.id == cell_id:return cellraise KeyError(f"Cell {cell_id!r} not found in document")def get(self, cell_id: CellId_t) -> NotebookCell | None:- """Lookup by ID, returning ``None`` if not found."""+ """Lookup by ID, returning `None` if not found."""for cell in self._cells:if cell.id == cell_id:return cellreturn Nonedef get_cell_version(self, cell_id: CellId_t) -> int | None:- """Return the cell's version counter, or ``None`` if not found."""+ """Return the cell's version counter, or `None` if not found."""cell = self.get(cell_id)return cell.version if cell is not None else None@@ -147,9 +147,9 @@ class NotebookDocument:# ------------------------------------------------------------------def apply(self, tx: Transaction) -> Transaction:- """Validate and apply *tx*, return it with ``version`` assigned.+ """Validate and apply *tx*, return it with `version` assigned.- Raises ``ValueError`` for validation failures and ``KeyError``+ Raises `ValueError` for validation failures and `KeyError`when a change references a non-existent cell."""if not tx.changes:@@ -238,19 +238,19 @@ class NotebookDocument:# ------------------------------------------------------------------def _replace_cells(self, cells: list[NotebookCell]) -> None:- """Bulk-replace the cell list in place, bypassing ``apply``.+ """Bulk-replace the cell list in place, bypassing `apply`.Transitional. Used for full-document rebuilds (save round-trip)until those flows are expressed as diff Transactions. The- ``_cells`` attribute is reassigned (not mutated element-wise)+ `_cells` attribute is reassigned (not mutated element-wise)so any external holder of the prior list keeps a snapshot ofpre-rebuild state — useful for diff comparison. Bumps- ``version`` so observers see the state change like they would- after ``apply()``.+ `version` so observers see the state change like they would+ after `apply()`.- Per-cell ``version`` is reconciled against the prior state: an id+ Per-cell `version` is reconciled against the prior state: an idwhose code matches inherits the prior version (agent reads stay- valid); an id whose code changed gets ``prior + 1`` (invalidates+ valid); an id whose code changed gets `prior + 1` (invalidatesstale agent reads); brand-new ids keep the version they wereconstructed with."""@@ -269,12 +269,12 @@ class NotebookDocument:def _rekey(self, mapping: dict[CellId_t, CellId_t]) -> None:"""Rekey cells by an old-id to new-id mapping, preserving order.- Cells whose id is not in ``mapping`` keep their existing id.- Each rekeyed cell is replaced by a fresh ``NotebookCell`` so its+ Cells whose id is not in `mapping` keep their existing id.+ Each rekeyed cell is replaced by a fresh `NotebookCell` so itsprimary key is stable from construction to disposal. Bumps- ``version`` so observers see the rekey as a state change.+ `version` so observers see the rekey as a state change.- Raises ``ValueError`` if the rekey would produce duplicate ids.+ Raises `ValueError` if the rekey would produce duplicate ids."""final_ids: set[CellId_t] = set()for c in self._cells:@@ -349,7 +349,7 @@ def notebook_document_context(def _validate(changes: tuple[DocumentChange, ...], cells: list[NotebookCell]) -> None:- """Check for conflicting changes. Raises ``ValueError``."""+ """Check for conflicting changes. Raises `ValueError`."""existing_ids = {c.id for c in cells}created: set[CellId_t] = set()deleted: set[CellId_t] = set()diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.pyindex 6fc7f111ee..15fd418a9e 100644--- a/marimo/_messaging/notification.py+++ b/marimo/_messaging/notification.py@@ -242,8 +242,8 @@ class CompletedRunNotification(Notification, tag="completed-run"):Attributes:run_id: Correlation ID echoed from the command that triggered- this completion. ``None`` for handlers that don't take a- ``run_id`` (everything except ``handle_execute_scratchpad``+ this completion. `None` for handlers that don't take a+ `run_id` (everything except `handle_execute_scratchpad`today). Consumers that want to wait for a specific command'scompletion filter on this field."""diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.pyindex f3629e011c..65c72634e8 100644--- a/marimo/_messaging/types.py+++ b/marimo/_messaging/types.py@@ -41,14 +41,14 @@ class NoopStream(Stream):def _ensure_plain_str(s: str) -> str:- """Coerce str subclasses to plain ``str``.+ """Coerce str subclasses to plain `str`.- Some libraries (e.g. loguru) emit str subclasses whose ``__slots__``- carry extra metadata (loguru's ``Message.record``). When such an+ Some libraries (e.g. loguru) emit str subclasses whose `__slots__`+ carry extra metadata (loguru's `Message.record`). When such anobject reaches msgspec serialization the encoder may serialize theslots/attributes instead of the string value, corrupting console output.- Converting to a bare ``str`` strips those attributes cheaply and is- a no-op for regular strings (``type(s) is str`` fast-path).+ Converting to a bare `str` strips those attributes cheaply and is+ a no-op for regular strings (`type(s) is str` fast-path).Raises TypeError for non-str inputs to preserve io.TextIOBase.write()semantics.diff --git a/marimo/_output/formatters/pytorch_formatters.py b/marimo/_output/formatters/pytorch_formatters.pyindex 2c1596956b..8692ecfc23 100644--- a/marimo/_output/formatters/pytorch_formatters.py+++ b/marimo/_output/formatters/pytorch_formatters.py@@ -75,8 +75,8 @@ class TrainableInfo:def _comma_to_br(html_str: str) -> str:"""Replace top-level comma separators with <br> for multi-line display.- Also replaces the ``=`` between key/value pairs with a space for the- expanded view, without touching ``=`` inside HTML attributes.+ Also replaces the `=` between key/value pairs with a space for the+ expanded view, without touching `=` inside HTML attributes."""result = _TOP_COMMA_RE.sub("<br>", html_str)return result.replace("</span>=", "</span> ")@@ -106,10 +106,10 @@ def _collect_dtype_device() -> tuple[str, str]:"""Summarise dtype and device across parameters.- Returns ``(dtype_str, device_str)``. When all parameters agree the- value is a single token (e.g. ``"float32"``); when mixed the unique- values are joined with ``"/"`` (e.g. ``"float32/float16"``).- If *params* is empty both strings are ``"–"``.+ Returns `(dtype_str, device_str)`. When all parameters agree the+ value is a single token (e.g. `"float32"`); when mixed the unique+ values are joined with `"/"` (e.g. `"float32/float16"`).+ If *params* is empty both strings are `"–"`."""dtypes: set[str] = set()devices: set[str] = set()@@ -129,7 +129,7 @@ def _extra_repr_html(module: torch.nn.Module) -> ExtraRepr:Uses PyTorch's own extra_repr() hook -- every built-in layer alreadyimplements this, and custom modules can override it too. We highlight- the ``key=`` portions of ``key=value`` pairs; positional arguments and+ the `key=` portions of `key=value` pairs; positional arguments andvalues are preserved as-is.Returns an ExtraRepr with positional and keyword HTML fragments.@@ -575,10 +575,10 @@ def format(module: torch.nn.Module) -> Html: # noqa: A001with child modules rendered as an expandable tree below.Args:- module: A ``torch.nn.Module`` instance.+ module: A `torch.nn.Module` instance.Returns:- A ``marimo.Html`` object with the rendered tree.+ A `marimo.Html` object with the rendered tree."""all_params = list(module.parameters())children = list(module.named_children())diff --git a/marimo/_output/formatters/repr_formatters.py b/marimo/_output/formatters/repr_formatters.pyindex 595b081f75..74e4cb0dcd 100644--- a/marimo/_output/formatters/repr_formatters.py+++ b/marimo/_output/formatters/repr_formatters.py@@ -24,11 +24,11 @@ MEDIA_MIME_PREFIXES = (def _maybe_as_anywidget_html(contents: dict[str, Any],) -> tuple[KnownMimeType, str] | None:- """If the mimebundle is for an anywidget, return ``text/html``.+ """If the mimebundle is for an anywidget, return `text/html`.- Converts ``application/vnd.jupyter.widget-view+json`` mimebundles- into the same ``<marimo-anywidget>`` HTML that ``mo.ui.anywidget()``- produces. Works for any comm whose open state included ``_esm``+ Converts `application/vnd.jupyter.widget-view+json` mimebundles+ into the same `<marimo-anywidget>` HTML that `mo.ui.anywidget()`+ produces. Works for any comm whose open state included `_esm`(both descriptor-based and ipywidgets-based anywidgets).Traditional (non-anywidget) jupyter widgets are left untouched sodiff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.pyindex 03efb476a5..c2df29b945 100644--- a/marimo/_output/hypertext.py+++ b/marimo/_output/hypertext.py@@ -290,16 +290,16 @@ class Html(MIME):class _BlockWrapped(Html):- """Wraps another Html in a plain block ``<div>``.+ """Wraps another Html in a plain block `<div>`.Used by :meth:`Html.center`, :meth:`Html.left`, and :meth:`Html.right`so that the wrapped content renders inside a single block container(preserving normal block flow and margin collapsing between innerelements) rather than becoming multiple flex-column siblings when the- inner wrapper uses ``display: contents`` (as ``mo.md`` does).+ inner wrapper uses `display: contents` (as `mo.md` does).- The inner Html is re-rendered on every ``text`` access so mutable- children (e.g. ``mo.status.spinner``) keep updating live.+ The inner Html is re-rendered on every `text` access so mutable+ children (e.g. `mo.status.spinner`) keep updating live."""def __init__(self, inner: Html) -> None:diff --git a/marimo/_output/md_extensions/display_math.py b/marimo/_output/md_extensions/display_math.pyindex 87dc6b9f1e..267a96ea08 100644--- a/marimo/_output/md_extensions/display_math.py+++ b/marimo/_output/md_extensions/display_math.py@@ -67,10 +67,10 @@ class DisplayMathPreprocessor(preprocessors.Preprocessor): # type: ignore[misc]"""Convert supported math delimiters in non-inline-code regions.Supported conversions:- - ``:math:`...``` and ``:math:<code>...</code>`` -> ``$...$``- - ``.. math::`` blocks -> ``$$...$$``- - ``\\(...\\)`` -> ``$...$``- - ``\\[...\\]`` -> ``$$...$$``+ - `:math:` inline roles and `:math:<code>` HTML variants -> `$...$`+ - `.. math::` blocks -> `$$...$$`+ - `\\(...\\)` -> `$...$`+ - `\\[...\\]` -> `$$...$$`"""converted_segments: list[str] = []for segment, is_inline_code in self._split_by_inline_code(text):@@ -193,7 +193,7 @@ class DisplayMathPreprocessor(preprocessors.Preprocessor): # type: ignore[misc]return segmentsdef _convert_rst_math_blocks(self, text: str) -> str:- """Convert ``.. math::`` directives to markdown display math blocks.+ """Convert `.. math::` directives to markdown display math blocks.Handles inline and multiline directive bodies, optional directiveoptions, and a permissive unindented LaTeX continuation case used indiff --git a/marimo/_plugins/ui/_impl/anywidget/comm_provider.py b/marimo/_plugins/ui/_impl/anywidget/comm_provider.pyindex da08c0cfc0..3c99c0a895 100644--- a/marimo/_plugins/ui/_impl/anywidget/comm_provider.py+++ b/marimo/_plugins/ui/_impl/anywidget/comm_provider.py@@ -1,8 +1,8 @@# Copyright 2026 Marimo. All rights reserved.-"""Comm backend for the ``comm`` library.+"""Comm backend for the `comm` library.-Patches ``comm.create_comm`` so that anywidget's descriptor API-(``MimeBundleDescriptor``) creates comms that broadcast through+Patches `comm.create_comm` so that anywidget's descriptor API+(`MimeBundleDescriptor`) creates comms that broadcast throughmarimo's notification system instead of being silent no-ops."""@@ -26,8 +26,8 @@ LOGGER = marimo_logger()def _is_anywidget_comm(target_name: str, data: dict[str, Any] | None) -> bool:"""Check if this comm is being opened by anywidget.- anywidget's ``open_comm`` always uses ``target_name="jupyter.widget"``- and includes ``_model_module: "anywidget"`` in the state.+ anywidget's `open_comm` always uses `target_name="jupyter.widget"`+ and includes `_model_module: "anywidget"` in the state."""if target_name != "jupyter.widget":return False@@ -38,11 +38,11 @@ def _is_anywidget_comm(target_name: str, data: dict[str, Any] | None) -> bool:def patch_comm_create() -> None:- """Replace ``comm.create_comm`` with a marimo-backed implementation.+ """Replace `comm.create_comm` with a marimo-backed implementation.Only intercepts comms created by anywidget (identified by- ``target_name`` and ``_model_module``). All other comms fall- through to a no-op ``DummyComm``.+ `target_name` and `_model_module`). All other comms fall+ through to a no-op `DummyComm`.This is idempotent -- calling it multiple times is safe."""diff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.pyindex 35fb560270..a3d3406aab 100644--- a/marimo/_plugins/ui/_impl/comm.py+++ b/marimo/_plugins/ui/_impl/comm.py@@ -75,14 +75,14 @@ BufferType = list[Buffer] | Nonedef _ensure_bytes(buf: object) -> bytes:- """Coerce a buffer to plain ``bytes`` for msgspec serialization.+ """Coerce a buffer to plain `bytes` for msgspec serialization.- msgspec natively handles ``bytes``, ``memoryview``, and ``bytearray``.+ msgspec natively handles `bytes`, `memoryview`, and `bytearray`.Some libraries (e.g. obstore) use custom types that hold binary databut aren't subclasses of these, so msgspec can't serialize them directly.- ``bytes()`` handles memoryview/bytearray on all Python versions, and- on Python 3.12+ also handles any object implementing ``__buffer__``.+ `bytes()` handles memoryview/bytearray on all Python versions, and+ on Python 3.12+ also handles any object implementing `__buffer__`."""if isinstance(buf, bytes):return bufdiff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pyindex 3703fa6bea..b2ec97eed5 100644--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -400,7 +400,7 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):@memoize_last_valuedef _get_json_size_bytes(self, manager: TableManager[Any]) -> int | None:- """JSON-serialized size of ``manager``; see table._get_json_size_bytes."""+ """JSON-serialized size of `manager`; see table._get_json_size_bytes."""try:return len(manager.to_json(strict_json=True))except Exception:diff --git a/marimo/_plugins/ui/_impl/file_browser.py b/marimo/_plugins/ui/_impl/file_browser.pyindex 602de44f07..085c86adb2 100644--- a/marimo/_plugins/ui/_impl/file_browser.py+++ b/marimo/_plugins/ui/_impl/file_browser.py@@ -27,13 +27,13 @@ _VALID_KINDS: Final[frozenset[str]] = frozenset({"file", "directory"})def _normalize_selection_mode(value: object,) -> frozenset[str]:- """Normalize ``selection_mode`` to a frozenset of selectable kinds.+ """Normalize `selection_mode` to a frozenset of selectable kinds.Accepted inputs:- - ``"file"`` -> ``{"file"}``- - ``"directory"`` -> ``{"directory"}``- - ``"all"`` -> ``{"file", "directory"}``- - list/tuple containing ``"file"`` and/or ``"directory"`` (deduped)+ - `"file"` -> `{"file"}`+ - `"directory"` -> `{"directory"}`+ - `"all"` -> `{"file", "directory"}`+ - list/tuple containing `"file"` and/or `"directory"` (deduped)"""if isinstance(value, str):if value == "all":diff --git a/marimo/_plugins/ui/_impl/from_mpl_interactive.py b/marimo/_plugins/ui/_impl/from_mpl_interactive.pyindex bc0380aad1..9adff1f8cd 100644--- a/marimo/_plugins/ui/_impl/from_mpl_interactive.py+++ b/marimo/_plugins/ui/_impl/from_mpl_interactive.py@@ -31,16 +31,16 @@ LOGGER = _loggers.marimo_logger()def _disconnect_owner_callbacks(canvas: Any, owner: Any) -> None:- """Disconnect every callback on ``canvas.callbacks`` whose receiver is ``owner``.+ """Disconnect every callback on `canvas.callbacks` whose receiver is `owner`.- ``FigureCanvasBase.callbacks`` is a property returning- ``figure._canvas_callbacks``, so every canvas bound to the same- figure shares one registry. ``NavigationToolbar2.__init__``- registers ``_zoom_pan_handler`` (and a few siblings) on this+ `FigureCanvasBase.callbacks` is a property returning+ `figure._canvas_callbacks`, so every canvas bound to the same+ figure shares one registry. `NavigationToolbar2.__init__`+ registers `_zoom_pan_handler` (and a few siblings) on thisshared registry; matplotlib has no public counterpart thatdisconnects them when a canvas/toolbar is discarded. Without thiscleanup, every cell rerun would stack another toolbar's handler on- the registry, leading to duplicate ``press_pan``/``release_pan``+ the registry, leading to duplicate `press_pan`/`release_pan`dispatch."""registry = canvas.callbacks@@ -97,9 +97,9 @@ def _get_mpl_css() -> str:page / iframe that would leak into the host page. Only mpl.css andfbm.css have properly scoped class-based selectors.- All rules are wrapped inside a ``.mpl-interactive-figure`` scope so- that any remaining broad selectors (e.g. ``body``, ``#figure``) do- not leak into the host page when loaded as a ``<link>`` stylesheet.+ All rules are wrapped inside a `.mpl-interactive-figure` scope so+ that any remaining broad selectors (e.g. `body`, `#figure`) do+ not leak into the host page when loaded as a `<link>` stylesheet."""from matplotlib.backends.backend_webagg_core import (FigureManagerWebAgg,@@ -123,10 +123,10 @@ def _get_mpl_css() -> str:def _scope_css(css: str, scope: str) -> str:"""Scope CSS rules using native CSS nesting.- Wraps all rules inside a ``<scope> { … }`` block so that child+ Wraps all rules inside a `<scope> { … }` block so that childselectors are implicitly prefixed. This replaces the previous- regex-based rewriter and correctly handles ``@keyframes``,- ``@media``, and any other at-rules or complex selectors.+ regex-based rewriter and correctly handles `@keyframes`,+ `@media`, and any other at-rules or complex selectors.Requires browser support for CSS Nesting (Chrome 120+, Firefox 117+,Safari 17.2+).diff --git a/marimo/_plugins/ui/_impl/mpl.py b/marimo/_plugins/ui/_impl/mpl.pyindex 69a665752f..5148c21ad7 100644--- a/marimo/_plugins/ui/_impl/mpl.py+++ b/marimo/_plugins/ui/_impl/mpl.py@@ -32,9 +32,9 @@ def _to_numeric(arr: NDArray[Any]) -> NDArray[Any]:"""Convert a numpy array to matplotlib's numeric representation.Only called on the slow path when a direct comparison raises- ``TypeError`` (e.g. datetime vs float). Uses- ``matplotlib.dates.date2num`` which handles ``datetime.datetime``,- ``datetime.date``, and ``numpy.datetime64``.+ `TypeError` (e.g. datetime vs float). Uses+ `matplotlib.dates.date2num` which handles `datetime.datetime`,+ `datetime.date`, and `numpy.datetime64`."""from matplotlib.dates import date2num # type: ignore[import-untyped]@@ -138,14 +138,14 @@ class EmptySelection:"""def get_mask(self, x: ArrayLike, y: ArrayLike) -> NDArray[np.bool_]: # noqa: ARG002- """Return an all-``False`` mask.+ """Return an all-`False` mask.Args:x: Array-like of x-coordinates.y: Array-like of y-coordinates.Returns:- A boolean numpy array of all ``False``.+ A boolean numpy array of all `False`."""import numpy as npdiff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.pyindex 6f4847fef6..73b1f127fc 100644--- a/marimo/_plugins/ui/_impl/plotly.py+++ b/marimo/_plugins/ui/_impl/plotly.py@@ -2031,9 +2031,9 @@ def _compute_waterfall_bar_extents(Waterfall bars stack on top of each other, so the visual position ofeach bar depends on the cumulative sum of preceding relative bars:- * ``"absolute"`` — bar runs from *base* to y[i]; resets running total.- * ``"relative"`` — bar runs from running_total to running_total + y[i].- * ``"total"`` — bar runs from *base* to running_total (display only;+ * `"absolute"` — bar runs from *base* to y[i]; resets running total.+ * `"relative"` — bar runs from running_total to running_total + y[i].+ * `"total"` — bar runs from *base* to running_total (display only;does not alter the running total)."""running_total = base@@ -2385,13 +2385,13 @@ def _append_violin_points_to_selection("""Expand violin plot selections into individual underlying data points.Handles three cases:- - Range/lasso with individual points already sent by Plotly (``points``+ - Range/lasso with individual points already sent by Plotly (`points`enabled): Plotly already delivered the right individual data points via- the ``onSelected`` event; pass them through unchanged.- - Range/lasso without individual points (``points`` disabled): extract+ the `onSelected` event; pass them through unchanged.+ - Range/lasso without individual points (`points` disabled): extractall underlying sample rows whose category position overlaps the selectionrange from the figure data.- - Click events (no range/lasso): the frontend sends ``pointNumbers`` for+ - Click events (no range/lasso): the frontend sends `pointNumbers` forthe clicked violin element; expand these into one dict per sample row soPython callers get row-level data."""@@ -2573,7 +2573,7 @@ def _extract_violin_points_from_range(horizontal) and the value axis are compared against the selection range.Only sample rows whose category group overlaps the selection *and* whoseindividual value falls within the value-axis bounds are returned. When the- value-axis range is absent from ``range_data`` (e.g. a selection spanning+ value-axis range is absent from `range_data` (e.g. a selection spanningthe full y-axis) all rows in matching categories are included."""if DependencyManager.numpy.has():@@ -2588,7 +2588,7 @@ def _extract_violin_points_numpy(Filters by both the category axis (which violin group falls inside theselection box) and the value axis (which individual sample values fall- inside the selection box). When ``points`` is disabled in the Plotly+ inside the selection box). When `points` is disabled in the Plotlyfigure, Plotly does not send individual point coordinates, so we deriveinclusion from the underlying trace arrays."""@@ -2736,18 +2736,18 @@ def _append_box_points_to_selection("""Expand box plot selections into individual underlying data points.Handles three cases:- - Range/lasso with individual points already sent by Plotly (``boxpoints``+ - Range/lasso with individual points already sent by Plotly (`boxpoints`enabled): Plotly already delivered the right individual data points via- the ``onSelected`` event; pass them through unchanged.- - Range/lasso without individual points (``boxpoints`` disabled): extract+ the `onSelected` event; pass them through unchanged.+ - Range/lasso without individual points (`boxpoints` disabled): extractall underlying sample rows whose category position overlaps the selectionrange from the figure data.- - Click events (no range/lasso): the frontend sends ``pointNumbers`` for+ - Click events (no range/lasso): the frontend sends `pointNumbers` forthe clicked box/whisker element; expand these into one dict per samplerow so Python callers get row-level data.- This also handles strip charts (``px.strip()``) which are rendered as- ``go.Box`` traces with ``boxpoints="all"`` and transparent fills.+ This also handles strip charts (`px.strip()`) which are rendered as+ `go.Box` traces with `boxpoints="all"` and transparent fills."""all_points = cast(list[dict[str, Any]], selection_data.get("points", []))all_indices = cast(list[Any], selection_data.get("indices", []))diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 4d9ed8eaa7..f817ee60a7 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -933,7 +933,7 @@ class table(JSON is the largest format we export, so this is a conservative size estimate:if the JSON fits under a host's download limit, CSV and Parquet willtoo. Memoized on manager identity — recomputed when filters/search- produce a new ``_searched_manager``.+ produce a new `_searched_manager`."""try:return len(manager.to_json(strict_json=True))@@ -951,24 +951,24 @@ class table(When a requested format requires a package that isn't installed(e.g., Parquet without pyarrow/pandas/polars), returns a- ``DownloadAsResponse`` with ``error`` and ``missing_packages``+ `DownloadAsResponse` with `error` and `missing_packages`populated instead of raising. The frontend uses this to prompt theuser to install the dependency and retry.Args:args (DownloadAsArgs): The requested download format. Must be- one of ``'csv'``, ``'json'``, or ``'parquet'``.+ one of `'csv'`, `'json'`, or `'parquet'`.Returns:- DownloadAsResponse: Either a success response with ``url`` and- ``filename`` populated, or a missing-packages response with- ``error`` and ``missing_packages`` populated when the+ DownloadAsResponse: Either a success response with `url` and+ `filename` populated, or a missing-packages response with+ `error` and `missing_packages` populated when theformat's dependencies are not available.Raises:NotImplementedError: If the current selection resolves to- something other than a ``TableManager`` (e.g., a raw list- of ``TableCell`` from cell-selection modes).+ something other than a `TableManager` (e.g., a raw list+ of `TableCell` from cell-selection modes)."""# Short-circuit Parquet when no parquet-capable lib is importable.if args.format == "parquet":@@ -1405,7 +1405,7 @@ class table("""Get the row IDs for a page of data.When all rows are present (no filter applied, e.g. sort-only),- this reads actual ``_marimo_row_id`` values from the searched+ this reads actual `_marimo_row_id` values from the searchedmanager so that style/hover dict keys match what the frontenduses for lookup -- regardless of sort column or direction.diff --git a/marimo/_runtime/_wasm/_duckdb/__init__.py b/marimo/_runtime/_wasm/_duckdb/__init__.pyindex 1d1540692d..6494209870 100644--- a/marimo/_runtime/_wasm/_duckdb/__init__.py+++ b/marimo/_runtime/_wasm/_duckdb/__init__.py@@ -1,16 +1,16 @@# Copyright 2026 Marimo. All rights reserved."""Install WASM-only DuckDB fallbacks for remote file scans.-DuckDB-WASM cannot use ``httpfs``. marimo fetches supported URLs itself,+DuckDB-WASM cannot use `httpfs`. marimo fetches supported URLs itself,materializes supported files as pandas DataFrames, then hands those framesback to DuckDB through replacement scans.We have two concrete use cases to patch:-* **Direct read methods** — ``duckdb.read_csv/read_parquet/read_json`` are+* **Direct read methods** — `duckdb.read_csv/read_parquet/read_json` arewrapped with :class:`WasmPatchSet`. Supported remote URLs are fetched bymarimo and returned as DuckDB relations.-* **SQL remote scans** — raw DuckDB APIs and marimo's ``mo.sql`` path call the+* **SQL remote scans** — raw DuckDB APIs and marimo's `mo.sql` path call thesame sqlglot rewrite helper. It replaces supported URL scans with generatedtable names and evaluates the original DuckDB call with fetched DataFramesin scope so DuckDB replacement scans can resolve them.@@ -216,14 +216,14 @@ def patch_duckdb_query_for_wasm() -> WasmDuckDBQueryPatch | None:"""Replace supported remote file reads with generated table names.- For example, ``SELECT * FROM read_csv('https://example.com/cars.csv')``- becomes ``SELECT * FROM __marimo_wasm_duckdb_remote_0`` when suffix ``0``- is free. The returned ``tables`` mapping binds that name to the fetched- DataFrame. If the query or ``reserved_names`` already use that identifier,+ For example, `SELECT * FROM read_csv('https://example.com/cars.csv')`+ becomes `SELECT * FROM __marimo_wasm_duckdb_remote_0` when suffix `0`+ is free. The returned `tables` mapping binds that name to the fetched+ DataFrame. If the query or `reserved_names` already use that identifier,the rewriter uses the next free suffix.In Pyodide this raises if sqlglot is unavailable and the query may contain- a remote source. Returns ``None`` when:+ a remote source. Returns `None` when:- marimo is not running in Pyodide;- the query has no remote URL;@@ -597,7 +597,7 @@ def _show_duckdb_tables(args: tuple[Any, ...],kwargs: Mapping[str, Any],) -> Any:- """Run ``SHOW TABLES`` through the same DuckDB entry point being patched."""+ """Run `SHOW TABLES` through the same DuckDB entry point being patched."""import duckdboriginal_call = inspect.unwrap(original)diff --git a/marimo/_runtime/_wasm/_duckdb/dataframe.py b/marimo/_runtime/_wasm/_duckdb/dataframe.pyindex 27ebe070a4..ff6c05f3b7 100644--- a/marimo/_runtime/_wasm/_duckdb/dataframe.py+++ b/marimo/_runtime/_wasm/_duckdb/dataframe.py@@ -4,7 +4,7 @@The WASM patch fetches remote bytes in Python, but DuckDB's Python readersstill expect local paths for CSV, JSON, and parquet parsing. This modulematerializes fetched bytes through short-lived temp files where DuckDB parsing-is needed and synthesizes DataFrames for ``read_text`` and ``read_blob``.+is needed and synthesizes DataFrames for `read_text` and `read_blob`."""from __future__ import annotations@@ -121,7 +121,7 @@ def _read_json_objects_path(def read_text_dataframe(data: bytes, url: str) -> pd.DataFrame:- """Match DuckDB's ``read_text`` shape for an already-fetched object."""+ """Match DuckDB's `read_text` shape for an already-fetched object."""import pandas as pdreturn pd.DataFrame(@@ -135,7 +135,7 @@ def read_text_dataframe(data: bytes, url: str) -> pd.DataFrame:def read_blob_dataframe(data: bytes, url: str) -> pd.DataFrame:- """Match DuckDB's ``read_blob`` shape for an already-fetched object."""+ """Match DuckDB's `read_blob` shape for an already-fetched object."""import pandas as pdreturn pd.DataFrame(diff --git a/marimo/_runtime/_wasm/_duckdb/io.py b/marimo/_runtime/_wasm/_duckdb/io.pyindex 508916ee3a..63f36a38b3 100644--- a/marimo/_runtime/_wasm/_duckdb/io.py+++ b/marimo/_runtime/_wasm/_duckdb/io.py@@ -5,7 +5,7 @@ DuckDB's native network scanner is unavailable in Pyodide. This module is thecompatibility layer that recognizes supported URL shapes, validates the readeroptions we can reproduce, fetches bytes through WASM fetch shim, anddispatches to a local DataFrame reader. Unsupported readers or option-combinations return ``None`` so callers can use the unpatched DuckDB path+combinations return `None` so callers can use the unpatched DuckDB pathand surface the underlying error."""@@ -369,7 +369,7 @@ def _reader_by_name(def reader_for_url(url: str) -> _DataFrameReader | None:- """Infer a reader from direct URL table syntax such as ``FROM 'x.csv'``."""+ """Infer a reader from direct URL table syntax such as `FROM 'x.csv'`."""path = urlparse(url).path.lower()return next((diff --git a/marimo/_runtime/_wasm/_duckdb/sources.py b/marimo/_runtime/_wasm/_duckdb/sources.pyindex 8086cfa75c..fa89cfba5a 100644--- a/marimo/_runtime/_wasm/_duckdb/sources.py+++ b/marimo/_runtime/_wasm/_duckdb/sources.py@@ -3,8 +3,8 @@The SQL patch should only rewrite queries it can execute with fetchedDataFrames. This module recognizes direct URL table syntax and supported-``read_*`` table functions, extracts literal URL/options from sqlglot's AST,-and returns ``None`` for dynamic expressions so they continue through DuckDB+`read_*` table functions, extracts literal URL/options from sqlglot's AST,+and returns `None` for dynamic expressions so they continue through DuckDBunchanged."""@@ -163,7 +163,7 @@ def _read_function_options(def _read_function_option(option_expr: exp.Expression,) -> tuple[str, Any] | None:- """Return one static option or ``None`` for unsupported expressions."""+ """Return one static option or `None` for unsupported expressions."""import sqlglot.expressions as expproperty_eq = getattr(exp, "PropertyEQ", None)diff --git a/marimo/_runtime/_wasm/_patches.py b/marimo/_runtime/_wasm/_patches.pyindex 06662c80eb..3d4c2b77e1 100644--- a/marimo/_runtime/_wasm/_patches.py+++ b/marimo/_runtime/_wasm/_patches.py@@ -25,8 +25,8 @@ WrapperFactory = Callable[[Callable[..., Any]], Callable[..., Any]]class WasmPatchSet:"""Collects WASM-only monkey-patches with a single unpatch handle.- `patch` replaces ``owner.attr`` with a wrapper: calls original; on- ``catch`` exception, runs ``fallback(original, *args, **kwargs)``. If the+ `patch` replaces `owner.attr` with a wrapper: calls original; on+ `catch` exception, runs `fallback(original, *args, **kwargs)`. If thefallback also raises, re-raises the original with the fallback chained sousers see the real underlying error."""@@ -43,9 +43,9 @@ class WasmPatchSet:*,catch: tuple[type[BaseException], ...] = (NameError, Exception),) -> None:- """Register a patch on ``owner.attr``.+ """Register a patch on `owner.attr`.- No-op outside pyodide or if ``attr`` is missing (e.g. renamed across+ No-op outside pyodide or if `attr` is missing (e.g. renamed acrosspolars versions)."""@@ -79,9 +79,9 @@ class WasmPatchSet:attr: str,wrapper_factory: WrapperFactory,) -> None:- """Replace ``owner.attr`` with a WASM-only wrapper.+ """Replace `owner.attr` with a WASM-only wrapper.- Unlike ``patch``, this does not call the original first. Use this for+ Unlike `patch`, this does not call the original first. Use this forAPIs where an original call can have side effects before failing."""if not self._active:diff --git a/marimo/_runtime/_wasm/_polars.py b/marimo/_runtime/_wasm/_polars.pyindex c212653588..1d2900c34b 100644--- a/marimo/_runtime/_wasm/_polars.py+++ b/marimo/_runtime/_wasm/_polars.py@@ -12,9 +12,9 @@ Two flavors of fallback live here, both built on :class:`WasmPatchSet`:* **DataFrame.write_json** — file system / native JSON writers can fail inWASM. On failure we round-trip via CSV and emit JSON manually.-Read/scan path is best-effort: polars-only kwargs (``n_rows``,-``try_parse_dates``, ...) are ignored; common kwargs with a pyarrow-equivalent (``columns``, csv ``separator``, ``has_header``) are honored.+Read/scan path is best-effort: polars-only kwargs (`n_rows`,+`try_parse_dates`, ...) are ignored; common kwargs with a pyarrow+equivalent (`columns`, csv `separator`, `has_header`) are honored.All patches are no-ops outside pyodide."""@@ -137,7 +137,7 @@ _ARROW_READERS: dict[str, Callable[..., Any]] = {def _make_fallback(fmt: str, lazy: bool) -> Callable[..., Any]:- """Decode ``source`` via pyarrow and return polars."""+ """Decode `source` via pyarrow and return polars."""import polars as plfrom marimo._dependencies.dependencies import DependencyManager@@ -189,9 +189,9 @@ def _write_json_fallback() -> str | None:"""Convert the frame to dicts and emit JSON.- ``to_dicts`` preserves types and handles quoting/embedded delimiters+ `to_dicts` preserves types and handles quoting/embedded delimiterscorrectly (unlike a naive CSV split), and avoids I/O so it works in WASM.- ``default=str`` covers temporal/decimal types that aren't JSON-native.+ `default=str` covers temporal/decimal types that aren't JSON-native."""import jsondiff --git a/marimo/_runtime/agent.py b/marimo/_runtime/agent.pyindex eadc9e00d7..1d582decad 100644--- a/marimo/_runtime/agent.py+++ b/marimo/_runtime/agent.py@@ -41,6 +41,6 @@ class AgentReadTracker:@dataclassclass Agent:- """One per ``Kernel`` — long-lived across scratchpad executions."""+ """One per `Kernel` — long-lived across scratchpad executions."""read_tracker: AgentReadTracker = field(default_factory=AgentReadTracker)diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.pyindex 6134dec0af..7173ee7446 100644--- a/marimo/_runtime/commands.py+++ b/marimo/_runtime/commands.py@@ -75,9 +75,9 @@ SerializedCLIArgs = dict[str, ListOrValue[Primitive]]def _user_to_dict(user: Any) -> dict[str, Encodable]:"""Normalize an auth user into a serializable dict.- Starlette's authentication middleware sets ``request.scope["user"]`` to a- ``BaseUser`` instance (commonly ``SimpleUser``). Storing the raw object on- ``HTTPRequest.user`` breaks msgspec serialization on the IPC path. Convert+ Starlette's authentication middleware sets `request.scope["user"]` to a+ `BaseUser` instance (commonly `SimpleUser`). Storing the raw object on+ `HTTPRequest.user` breaks msgspec serialization on the IPC path. Convertto a dict matching the documented contract: "info from authenticationmiddleware (e.g., is_authenticated, username)"."""@@ -93,10 +93,10 @@ def _user_to_dict(user: Any) -> dict[str, Encodable]:def _meta_to_dict(meta: Any) -> dict[str, Encodable]:- """Normalize user-defined ``request.scope["meta"]`` at the boundary.+ """Normalize user-defined `request.scope["meta"]` at the boundary.- Trusted shape per the public contract (``mo.app_meta().request``); we- just enforce dict-ness at the seam. Non-``Encodable`` values inside will+ Trusted shape per the public contract (`mo.app_meta().request`); we+ just enforce dict-ness at the seam. Non-`Encodable` values inside willsurface at IPC encode time rather than being silently coerced."""if meta is None or not isinstance(meta, dict):@@ -361,10 +361,10 @@ class ExecuteScratchpadCommand(Command):Used to populate the document ContextVar so code_mode can readcell ordering, code, names, and configs.run_id: Optional correlation ID. When set, the- ``CompletedRunNotification`` emitted at the end of this command- carries the same ``run_id`` so a caller holding a- ``ScratchCellListener`` can filter for *its* completion and- ignore ``CompletedRun`` events from unrelated commands on the+ `CompletedRunNotification` emitted at the end of this command+ carries the same `run_id` so a caller holding a+ `ScratchCellListener` can filter for *its* completion and+ ignore `CompletedRun` events from unrelated commands on thesame session."""diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.pyindex 8928a997c5..97af4a57b6 100644--- a/marimo/_runtime/complete.py+++ b/marimo/_runtime/complete.py@@ -423,7 +423,7 @@ def _key_options_from_ipython_method(obj: Any) -> list[str]:def _key_options_via_keys_method(obj: Mapping[Any, Any]) -> list[str]:- """Completion keys from a mapping. Only used after ``isinstance(obj, Mapping)``."""+ """Completion keys from a mapping. Only used after `isinstance(obj, Mapping)`."""return [str(key) for key in obj]diff --git a/marimo/_runtime/kernel_lifecycle.py b/marimo/_runtime/kernel_lifecycle.pyindex 21bb482750..ce7fd96042 100644--- a/marimo/_runtime/kernel_lifecycle.py+++ b/marimo/_runtime/kernel_lifecycle.py@@ -88,10 +88,10 @@ _T = TypeVar("_T")def drain_stale(queue: Any, *, latest: _T) -> _T:- """Discard stale items queued behind ``latest`` and return the newest.+ """Discard stale items queued behind `latest` and return the newest.- Drains via ``get_nowait()`` until exhausted; ``empty()`` is intentionally- avoided because ``multiprocessing.Queue.empty()`` can lie.+ Drains via `get_nowait()` until exhausted; `empty()` is intentionally+ avoided because `multiprocessing.Queue.empty()` can lie."""while True:try:diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex a2911ede32..52e08ccb5a 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -504,9 +504,9 @@ def _flush_console(Console messages (stdout/stderr) are batched by a background threadfor performance. Without an explicit flush, the messages may arrive- at the frontend *after* the cell is marked idle and ``completed-run``+ at the frontend *after* the cell is marked idle and `completed-run`is sent. A subsequent run would then clear the console (via- ``console=[]``) before the user sees the output.+ `console=[]`) before the user sees the output."""del celldel run_resultdiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 8bc605838e..0eacd1d26c 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -1801,15 +1801,15 @@ class Kernel:Args:request: The UI element update command.notify_frontend: Whether to broadcast the new value back to- the frontend via a ``marimo-ui-value-update`` message.- Set ``False`` for user-initiated updates from the frontend+ the frontend via a `marimo-ui-value-update` message.+ Set `False` for user-initiated updates from the frontend(the frontend already has the value locally;re-broadcasting causes redundant traffic and, on transportswith non-negligible round-trip latency (LSP, remotekernels), can visibly snap the rendered widget backward to- a stale value). Set ``True`` for genuinely+ a stale value). Set `True` for genuinelykernel-initiated changes (e.g. code_mode's- ``set_ui_value``) where the frontend has no other way to+ `set_ui_value`) where the frontend has no other way tolearn about the update.Returns True if any ui elements were set, False otherwisediff --git a/marimo/_runtime/virtual_file/storage.py b/marimo/_runtime/virtual_file/storage.pyindex 089f500087..1986555632 100644--- a/marimo/_runtime/virtual_file/storage.py+++ b/marimo/_runtime/virtual_file/storage.py@@ -47,7 +47,7 @@ class VirtualFileStorage(Protocol):Args:key: storage key- byte_length: total number of bytes to yield (after applying ``start``)+ byte_length: total number of bytes to yield (after applying `start`)chunk_size: chunk size in bytesstart: offset in bytes to begin reading from (default 0)@@ -283,7 +283,7 @@ class VirtualFileStorageManager:Raises:KeyError: If file not found- RuntimeError: When ``SharedMemoryStorage`` is used on the Pyodide platform.+ RuntimeError: When `SharedMemoryStorage` is used on the Pyodide platform."""storage = self.storageif storage is None:@@ -306,7 +306,7 @@ class VirtualFileStorageManager:Raises:KeyError: If file not found- RuntimeError: When ``SharedMemoryStorage`` is used on the Pyodide platform.+ RuntimeError: When `SharedMemoryStorage` is used on the Pyodide platform."""storage = self.storageif storage is None:diff --git a/marimo/_runtime/virtual_file/virtual_file.py b/marimo/_runtime/virtual_file/virtual_file.pyindex 2a26a7cf39..d713b6467b 100644--- a/marimo/_runtime/virtual_file/virtual_file.py+++ b/marimo/_runtime/virtual_file/virtual_file.py@@ -319,7 +319,7 @@ def read_virtual_file_chunked(Args:filename: virtual file name- byte_length: number of bytes to read (after applying ``start``)+ byte_length: number of bytes to read (after applying `start`)start: offset in bytes to begin reading from (for HTTP Range requests)"""try:diff --git a/marimo/_save/cache.py b/marimo/_save/cache.pyindex 919ca35338..26ceb8c12f 100644--- a/marimo/_save/cache.py+++ b/marimo/_save/cache.py@@ -66,7 +66,7 @@ CACHE_PREFIX: dict[CacheType, str] = {class CacheState:"""Groups cache-related state on RuntimeContext.- The ``is_memoizable`` method controls which value types are eligible+ The `is_memoizable` method controls which value types are eligiblefor content-hash memoization. Override (or swap the instance) tobroaden memoization for cached / parallel execution."""diff --git a/marimo/_save/encode.py b/marimo/_save/encode.pyindex b62930482f..7236c138f0 100644--- a/marimo/_save/encode.py+++ b/marimo/_save/encode.py@@ -154,7 +154,7 @@ def attempt_signed_bytes(value: bytes, label: str) -> bytes:def deterministic_dumps(obj: Any, hash_type: str) -> bytes:- """``pickle.dumps`` replacement that produces more deterministic bytes."""+ """`pickle.dumps` replacement that produces more deterministic bytes."""from marimo._save.stubs import maybe_get_custom_stubclass _ContentHashPickler(pickle.Pickler):diff --git a/marimo/_save/loaders/lazy.py b/marimo/_save/loaders/lazy.pyindex 171e93b58a..2a917118c2 100644--- a/marimo/_save/loaders/lazy.py+++ b/marimo/_save/loaders/lazy.py@@ -48,8 +48,8 @@ class _BlobStatus(Enum):def maybe_update_lazy_stub(value: Any) -> str:"""Return the loader strategy string for *value*, caching the result.- Walks the MRO of ``type(value)`` against ``LAZY_STUB_LOOKUP`` (a- fq-class-name → loader-string registry). Falls back to ``"pickle"``+ Walks the MRO of `type(value)` against `LAZY_STUB_LOOKUP` (a+ fq-class-name → loader-string registry). Falls back to `"pickle"`when no match is found."""value_type = type(value)diff --git a/marimo/_save/stubs/stubs.py b/marimo/_save/stubs/stubs.pyindex d8f39a06f9..ae2b1f22f4 100644--- a/marimo/_save/stubs/stubs.py+++ b/marimo/_save/stubs/stubs.py@@ -14,10 +14,10 @@ _T = TypeVar("_T")def mro_lookup(value_type: type, registry: dict[str, _T]) -> tuple[str, _T] | None:- """Walk the MRO of value_type, return ``(fq_name, value)`` for first match.+ """Walk the MRO of value_type, return `(fq_name, value)` for first match.Matches against fully-qualified class names of the form- ``"{cls.__module__}.{cls.__name__}"``. Returns ``None`` if no class in+ `"{cls.__module__}.{cls.__name__}"`. Returns `None` if no class inthe MRO is found in *registry*."""try:diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex 64e53a2138..fb50b36842 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -622,10 +622,10 @@ _RANGE_RE = re.compile(r"^bytes=(\d*)-(\d*)$", re.IGNORECASE)def _parse_range_header(range_header: str, total_size: int) -> tuple[int, int] | None:- """Parse a single-range HTTP ``Range`` header.+ """Parse a single-range HTTP `Range` header.- Returns ``(start, end)`` byte offsets (inclusive) on success, or- ``None`` if the range is unsatisfiable. Multi-range requests are+ Returns `(start, end)` byte offsets (inclusive) on success, or+ `None` if the range is unsatisfiable. Multi-range requests aretreated as unsatisfiable since marimo only supports single ranges."""match = _RANGE_RE.match(range_header.strip())diff --git a/marimo/_server/api/endpoints/ws/ws_connection_validator.py b/marimo/_server/api/endpoints/ws/ws_connection_validator.pyindex b36bc1b4da..7b42fc88a2 100644--- a/marimo/_server/api/endpoints/ws/ws_connection_validator.py+++ b/marimo/_server/api/endpoints/ws/ws_connection_validator.py@@ -121,8 +121,8 @@ class WebSocketConnectionValidator:def _extract_file_key(self) -> FileKey | None:"""Extract a FileKey from query params or fall back to the workspace.- An empty ``?file=`` value falls back to the workspace key — same as a- missing query param — to preserve the prior ``or``-chain semantics.+ An empty `?file=` value falls back to the workspace key — same as a+ missing query param — to preserve the prior `or`-chain semantics."""raw = self.app_state.query_params(FILE_QUERY_PARAM_KEY)if raw:diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.pyindex d63581e887..e19b4196e6 100644--- a/marimo/_server/api/endpoints/ws_endpoint.py+++ b/marimo/_server/api/endpoints/ws_endpoint.py@@ -455,9 +455,9 @@ class WebSocketHandler(SessionConsumer):async def _safe_close(self, code: int, reason: str) -> None:"""Close the WebSocket, ignoring errors from uninitialized state.- uvicorn never calls websockets' ``connection_open()``, so internal- attributes like ``transfer_data_task`` are missing. Closing a- websocket in that state raises ``AttributeError``. The connection+ uvicorn never calls websockets' `connection_open()`, so internal+ attributes like `transfer_data_task` are missing. Closing a+ websocket in that state raises `AttributeError`. The connectionis cleaned up when the handler returns regardless."""try:diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.pyindex e767ac1138..dcc7bcc990 100644--- a/marimo/_server/api/lifespans.py+++ b/marimo/_server/api/lifespans.py@@ -217,7 +217,7 @@ async def signal_handler(app: Starlette) -> AsyncIterator[None]:async def server_registry(app: Starlette) -> AsyncIterator[None]:"""Register this server in the local registry for discovery.- Only servers started **without** an auth token (``--no-token``)+ Only servers started **without** an auth token (`--no-token`)are registered. This ensures only servers that have explicitlyopted into relaxed local access are discoverable."""diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex 7a03536260..8d121d375c 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -228,7 +228,7 @@ class OSFileSystem(FileSystem):"""Stream-write an uploaded file to disk, chunk by chunk.Avoids loading the full payload into memory (the HTTP multipart- path can otherwise buffer 100 MB at once). Writes to a ``.part``+ path can otherwise buffer 100 MB at once). Writes to a `.part`temp file and atomically renames on success so a failed uploaddoesn't leave a half-written file at the final path."""diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.pyindex 248b713d77..c0dfd5ed9d 100644--- a/marimo/_server/models/files.py+++ b/marimo/_server/models/files.py@@ -62,8 +62,8 @@ class FileCreateMultipartRequest(msgspec.Struct, rename="camel"):Schema-only: this struct exists to describe the multipart shape inOpenAPI. At runtime, the endpoint reads the string fields from- ``MultipartRequest.body`` and the uploaded bytes from- ``MultipartRequest.files["file"]`` — ``body.file`` is never populated.+ `MultipartRequest.body` and the uploaded bytes from+ `MultipartRequest.files["file"]` — `body.file` is never populated."""# The path where to create the file or directorydiff --git a/marimo/_server/scratchpad.py b/marimo/_server/scratchpad.pyindex e5ddb98993..4c9ecf1cc1 100644--- a/marimo/_server/scratchpad.py+++ b/marimo/_server/scratchpad.py@@ -47,12 +47,12 @@ class ConsoleEvent(TypedDict):class Done(TypedDict):- """Terminal SSE event for ``/api/kernel/execute``.+ """Terminal SSE event for `/api/kernel/execute`.- ``success`` drives the CLI exit code. ``output`` is the scratch- cell's rendered value on success, or ``{mimetype: "text/plain",- data: ""}`` on failure — the actual error detail (traceback, etc.)- was already streamed via preceding ``stderr`` events.+ `success` drives the CLI exit code. `output` is the scratch+ cell's rendered value on success, or `{mimetype: "text/plain",+ data: ""}` on failure — the actual error detail (traceback, etc.)+ was already streamed via preceding `stderr` events."""success: bool@@ -70,17 +70,17 @@ def _format_sse(event: str, data: Any) -> str:class ScratchCellListener(EventAwareExtension):"""Listens for scratch cell notifications via an asyncio.Queue.- Supports both SSE streaming (via ``stream()``) and simple blocking- wait (via ``wait()``) so the same listener works for the HTTP- ``/execute`` endpoint and the MCP ``execute_code`` tool.+ Supports both SSE streaming (via `stream()`) and simple blocking+ wait (via `wait()`) so the same listener works for the HTTP+ `/execute` endpoint and the MCP `execute_code` tool.In addition to the scratch cell's own output, the listener capturesconsole output (stdout/stderr) from *other* cells that execute whilethe scratchpad is active — e.g. cells created and run by- ``_code_mode``. The done sentinel fires on the- ``CompletedRunNotification`` whose ``run_id`` matches this- listener's ``run_id`` — other completion events (e.g. from the- ``session.instantiate`` that happens before the scratchpad runs, or+ `_code_mode`. The done sentinel fires on the+ `CompletedRunNotification` whose `run_id` matches this+ listener's `run_id` — other completion events (e.g. from the+ `session.instantiate` that happens before the scratchpad runs, orfrom concurrent browser activity) are ignored, so we can'tmisidentify someone else's completion as ours."""@@ -160,7 +160,7 @@ class ScratchCellListener(EventAwareExtension):async def wait(self, timeout: float = EXECUTION_TIMEOUT) -> None:"""Block until execution completes, discarding streamed events.- Sets ``self.timed_out`` if the deadline is exceeded.+ Sets `self.timed_out` if the deadline is exceeded."""import time@@ -209,12 +209,12 @@ def build_done_event(session: Session,listener: ScratchCellListener | None = None,) -> str:- """Build the terminal ``done`` SSE event.+ """Build the terminal `done` SSE event.- ``success`` is false when the scratch cell itself errored OR any+ `success` is false when the scratch cell itself errored OR anydownstream cell captured by the listener errored. The actual error- detail was already streamed via ``stderr`` events earlier in the- response — ``done`` carries only the success bit plus the scratch+ detail was already streamed via `stderr` events earlier in the+ response — `done` carries only the success bit plus the scratchcell's rendered output on success (empty on failure)."""cell_notif = session.session_view.cell_notifications.get(SCRATCH_CELL_ID)diff --git a/marimo/_server/server_registry.py b/marimo/_server/server_registry.pyindex c32e06b72c..c3c42f53ef 100644--- a/marimo/_server/server_registry.py+++ b/marimo/_server/server_registry.py@@ -2,14 +2,14 @@"""Local discovery registry for running marimo instances.Each marimo server writes a small JSON file to-``~/.local/state/marimo/servers/<host>_<port>.json`` at startup and-removes it on shutdown. External tools (e.g. ``list-sessions.sh``)+`~/.local/state/marimo/servers/<host>_<port>.json` at startup and+removes it on shutdown. External tools (e.g. `list-sessions.sh`)read these files to discover running instances — no marimo import orHTTP endpoint is required.SECURITY: Only instances that have opted into relaxed local access —-started **without** an auth token (``--no-token``) — should be-registered. See the guard in ``lifespans.server_registry``.+started **without** an auth token (`--no-token`) — should be+registered. See the guard in `lifespans.server_registry`."""from __future__ import annotationsdiff --git a/marimo/_server/workspace/__init__.py b/marimo/_server/workspace/__init__.pyindex daff539588..5605d49fd3 100644--- a/marimo/_server/workspace/__init__.py+++ b/marimo/_server/workspace/__init__.py@@ -4,10 +4,10 @@A :class:`NotebookWorkspace` represents the set of notebooks a server ishosting. Concrete subclasses cover:-- :class:`EmptyWorkspace` — untitled (``__new__``) notebook-- :class:`SingleFileWorkspace` — single notebook (``marimo edit nb.py``)-- :class:`FixedFilesWorkspace` — fixed allowlist (``marimo run a.py b.py``)-- :class:`DirectoryWorkspace` — lazy directory scan (``marimo edit ./``)+- :class:`EmptyWorkspace` — untitled (`__new__`) notebook+- :class:`SingleFileWorkspace` — single notebook (`marimo edit nb.py`)+- :class:`FixedFilesWorkspace` — fixed allowlist (`marimo run a.py b.py`)+- :class:`DirectoryWorkspace` — lazy directory scan (`marimo edit ./`)"""import osdiff --git a/marimo/_server/workspace/_base.py b/marimo/_server/workspace/_base.pyindex 15b1f3c391..3725546ee3 100644--- a/marimo/_server/workspace/_base.py+++ b/marimo/_server/workspace/_base.py@@ -29,7 +29,7 @@ if TYPE_CHECKING:class NotebookWorkspace(abc.ABC):"""A server-side abstraction for the set of notebooks a server is hosting.- Owned by ``SessionManager``. Handles workspace browsing, allowlisting, lazy+ Owned by `SessionManager`. Handles workspace browsing, allowlisting, lazydirectory scanning, and security validation."""@@ -53,7 +53,7 @@ class NotebookWorkspace(abc.ABC):@abc.abstractmethoddef resolve(self, key: FileKey) -> str | None:- """Resolve a key to an absolute path; ``None`` for new files.+ """Resolve a key to an absolute path; `None` for new files.Useful for endpoints that need file-backed resources (e.g. thumbnails)without the overhead of parsing/loading a notebook.@@ -64,10 +64,10 @@ class NotebookWorkspace(abc.ABC):key: FileKey,defaults: AppDefaults | None = None,) -> AppFileManager:- """Load the notebook for the given key into an ``AppFileManager``.+ """Load the notebook for the given key into an `AppFileManager`.- Built on top of :meth:`resolve` — subclasses customize ``resolve`` and- inherit the right ``load`` semantics for free.+ Built on top of :meth:`resolve` — subclasses customize `resolve` and+ inherit the right `load` semantics for free."""defaults = defaults or AppDefaults()resolved = self.resolve(key)@@ -89,7 +89,7 @@ class NotebookWorkspace(abc.ABC):def register_allowed_path(self, path: str) -> None:"""Allow a file path that wasn't part of the original collection.- No-op by default. ``SingleFileWorkspace`` overrides to extend its+ No-op by default. `SingleFileWorkspace` overrides to extend itsallowlist for files created at runtime."""del path@@ -97,15 +97,15 @@ class NotebookWorkspace(abc.ABC):def register_temp_dir(self, temp_dir: str) -> None:"""Register a temp directory as allowed for file access.- No-op by default. ``DirectoryWorkspace`` overrides for tutorial+ No-op by default. `DirectoryWorkspace` overrides for tutorialsupport."""del temp_dirdef is_in_allowed_temp_dir(self, path: str) -> bool:- """Whether ``path`` lives inside an allowed temp directory.+ """Whether `path` lives inside an allowed temp directory.- Returns ``False`` by default. ``DirectoryWorkspace`` overrides.+ Returns `False` by default. `DirectoryWorkspace` overrides."""del pathreturn False@@ -113,13 +113,13 @@ class NotebookWorkspace(abc.ABC):def invalidate(self) -> None: # noqa: B027 — intentional no-op default"""Invalidate any cached listing.- No-op by default. ``DirectoryWorkspace`` overrides.+ No-op by default. `DirectoryWorkspace` overrides."""def set_include_markdown(self, include_markdown: bool) -> None:"""Toggle markdown inclusion in directory listings.- No-op by default. ``DirectoryWorkspace`` overrides — mutates in+ No-op by default. `DirectoryWorkspace` overrides — mutates inplace."""del include_markdowndiff --git a/marimo/_server/workspace/_directory.py b/marimo/_server/workspace/_directory.pyindex b5fb9339f8..30522139aa 100644--- a/marimo/_server/workspace/_directory.py+++ b/marimo/_server/workspace/_directory.py@@ -29,7 +29,7 @@ LOGGER = _loggers.marimo_logger()class DirectoryWorkspace(NotebookWorkspace):"""A workspace backed by a directory, scanned lazily on demand.- Used by ``marimo edit ./`` and ``marimo run ./``. File access is validated+ Used by `marimo edit ./` and `marimo run ./`. File access is validatedvia :class:`PathValidator` to ensure paths stay within the directory (or anexplicitly registered temp directory)."""diff --git a/marimo/_server/workspace/_empty.py b/marimo/_server/workspace/_empty.pyindex b9c93ec348..85c72fd820 100644--- a/marimo/_server/workspace/_empty.py+++ b/marimo/_server/workspace/_empty.py@@ -23,11 +23,11 @@ if TYPE_CHECKING:class EmptyWorkspace(NotebookWorkspace):- """An empty (untitled) workspace, used by ``marimo new``.+ """An empty (untitled) workspace, used by `marimo new`.- The workspace key is the ``__new__`` sentinel; concrete file paths are+ The workspace key is the `__new__` sentinel; concrete file paths areaccepted as a fallback so that callers which bootstrap with- ``EmptyWorkspace`` and later open a real file (e.g. via the homepage)+ `EmptyWorkspace` and later open a real file (e.g. via the homepage)continue to work."""diff --git a/marimo/_server/workspace/_fixed.py b/marimo/_server/workspace/_fixed.pyindex 8e0bf8d2db..1836115cd2 100644--- a/marimo/_server/workspace/_fixed.py+++ b/marimo/_server/workspace/_fixed.py@@ -1,5 +1,5 @@# Copyright 2026 Marimo. All rights reserved.-"""Workspace for a fixed list of notebooks (``marimo run a.py b.py``)."""+"""Workspace for a fixed list of notebooks (`marimo run a.py b.py`)."""from __future__ import annotations@@ -25,7 +25,7 @@ if TYPE_CHECKING:class FixedFilesWorkspace(NotebookWorkspace):"""A workspace pointing at a fixed allowlist of notebooks.- Used by ``marimo run a.py b.py`` and ``marimo run dir/`` snapshots. The+ Used by `marimo run a.py b.py` and `marimo run dir/` snapshots. Theallowlist is set at construction time and never grows."""diff --git a/marimo/_server/workspace/_keys.py b/marimo/_server/workspace/_keys.pyindex f617580691..f053f44dd9 100644--- a/marimo/_server/workspace/_keys.py+++ b/marimo/_server/workspace/_keys.py@@ -1,10 +1,10 @@# Copyright 2026 Marimo. All rights reserved."""Tagged-union ADT for notebook file keys.-The wire format is a string (HTTP query params, session ``initialization_id``)+The wire format is a string (HTTP query params, session `initialization_id`)but inside the server we model the two cases explicitly:-- :class:`NewFileKey` — the untitled (``__new__``) notebook+- :class:`NewFileKey` — the untitled (`__new__`) notebook- :class:`PathFileKey` — a notebook identified by a filesystem path"""@@ -26,7 +26,7 @@ class NewFileKey:class PathFileKey:"""Key for a notebook identified by a filesystem path.- The ``path`` is the raw value supplied at the boundary; workspaces are+ The `path` is the raw value supplied at the boundary; workspaces areresponsible for normalizing and validating it."""@@ -39,7 +39,7 @@ FileKey = NewFileKey | PathFileKeydef parse_file_key(raw: str) -> FileKey:"""Parse a wire-format string into a :class:`FileKey`.- The literal ``__new__`` becomes a :class:`NewFileKey`; any other string is+ The literal `__new__` becomes a :class:`NewFileKey`; any other string istreated as a path. We match the sentinel exactly so non-sentinel keysflow through normal path validation rather than being short-circuitedto the blank notebook.diff --git a/marimo/_server/workspace/_single.py b/marimo/_server/workspace/_single.pyindex e719827acf..54c8f73aa1 100644--- a/marimo/_server/workspace/_single.py+++ b/marimo/_server/workspace/_single.py@@ -1,5 +1,5 @@# Copyright 2026 Marimo. All rights reserved.-"""Workspace for a single notebook (``marimo edit nb.py``)."""+"""Workspace for a single notebook (`marimo edit nb.py`)."""from __future__ import annotations@@ -27,8 +27,8 @@ if TYPE_CHECKING:class SingleFileWorkspace(NotebookWorkspace):"""A workspace pointing at a single notebook.- Used by ``marimo edit nb.py`` and ``marimo run nb.py``. In edit mode the- allowlist can grow at runtime (via ``register_allowed_path``) to support+ Used by `marimo edit nb.py` and `marimo run nb.py`. In edit mode the+ allowlist can grow at runtime (via `register_allowed_path`) to supportnotebooks created during the session."""@@ -86,7 +86,7 @@ class SingleFileWorkspace(NotebookWorkspace):def register_allowed_path(self, path: str) -> None:"""Extend the allowlist for files created at runtime.- Always extends, unconditionally — ``SingleFileWorkspace`` represents+ Always extends, unconditionally — `SingleFileWorkspace` representssingle-file edit mode, where the user can branch off into newnotebooks created by the kernel. The fixed-allowlist behavior of:class:`FixedFilesWorkspace` is the read-only counterpart.diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.pyindex 139a67e54d..477b0b8120 100644--- a/marimo/_session/extensions/extensions.py+++ b/marimo/_session/extensions/extensions.py@@ -287,12 +287,12 @@ class NotificationListenerExtension(SessionExtension):"""Route a raw kernel message to the appropriate session method.Document transactions are intercepted and applied to the- ``session.document``, then ``session.notify()`` is invoked with the (versioned) result.+ `session.document`, then `session.notify()` is invoked with the (versioned) result.Kernel-sourced transactions also trigger an auto-save so agent-driven- mutations via ``code_mode`` land on disk the same way frontend edits do.+ mutations via `code_mode` land on disk the same way frontend edits do.- Everything else is forwarded verbatim via ``session.notify()``.+ Everything else is forwarded verbatim via `session.notify()`.TODO: if more notification types need server-side interception,consider a middleware chain instead of inline dispatch.@@ -327,11 +327,11 @@ class NotificationListenerExtension(SessionExtension):) -> None:"""Best-effort persistence of code-mode mutations to disk.- Only ``source="code-mode"`` transactions persist; ``"kernel"``+ Only `source="code-mode"` transactions persist; `"kernel"`bookkeeping (e.g. instantiation cell-order broadcasts) is skippedso opening or running a notebook never rewrites it on disk.Skipped in run mode and for unnamed notebooks. Failures surface as- an ``AlertNotification`` toast; they never raise out of the+ an `AlertNotification` toast; they never raise out of theinterceptor."""if source != "code-mode":diff --git a/marimo/_session/kernel_exit.py b/marimo/_session/kernel_exit.pyindex 23946f0c24..8b3575b36f 100644--- a/marimo/_session/kernel_exit.py+++ b/marimo/_session/kernel_exit.py@@ -1,8 +1,8 @@# Copyright 2026 Marimo. All rights reserved."""Classify how a kernel subprocess exited.-Used to turn a raw ``multiprocessing.Process.exitcode`` into a structured-``KernelExitInfo`` with a human-readable message. Best-effort cgroup+Used to turn a raw `multiprocessing.Process.exitcode` into a structured+`KernelExitInfo` with a human-readable message. Best-effort cgroupinspection adds memory diagnostics on Linux when the kernel was SIGKILLed,which on a container is almost always the cgroup OOM killer."""diff --git a/marimo/_session/managers/ipc.py b/marimo/_session/managers/ipc.pyindex 9510401078..e58a0859b4 100644--- a/marimo/_session/managers/ipc.py+++ b/marimo/_session/managers/ipc.py@@ -138,10 +138,10 @@ def construct_kernel_env("""Build environment variables for a kernel subprocess.Args:- base_env: Starting environment (typically ``os.environ.copy()``).+ base_env: Starting environment (typically `os.environ.copy()`).venv_python: Path to the Python executable in the target venv.is_ephemeral_sandbox: Whether this is an ephemeral sandbox venv- built by ``build_sandbox_venv``.+ built by `build_sandbox_venv`.writable: Whether the kernel venv supports package installs.kernel_pythonpath: Extra PYTHONPATH entries for read-onlyconfigured venvs that don't have marimo installed.diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.pyindex ac59ebc3e4..be35001b9d 100644--- a/marimo/_session/notebook/file_manager.py+++ b/marimo/_session/notebook/file_manager.py@@ -114,9 +114,9 @@ class AppFileManager:Args:app: The internal app to wrapfilename: Optional source path for the notebook. When set,- ``AppMetadata.filename`` (and therefore ``__file__`` /- ``mo.notebook_dir()`` inside cells) resolves to the source- file rather than the host process's ``__main__``.+ `AppMetadata.filename` (and therefore `__file__` /+ `mo.notebook_dir()` inside cells) resolves to the source+ file rather than the host process's `__main__`.Returns:AppFileManager instance@@ -133,17 +133,17 @@ class AppFileManager:def reload(self) -> tuple[Transaction, set[CellId_t]]:"""Reload the app from storage.- Splices the existing ``CellManager`` into the freshly loaded- ``InternalApp`` so ``app.cell_manager`` and- ``app.cell_manager.document`` identity is preserved across reload.+ Splices the existing `CellManager` into the freshly loaded+ `InternalApp` so `app.cell_manager` and+ `app.cell_manager.document` identity is preserved across reload.The diff between old and new state is applied to the existing- document via ``apply()``, which advances ``_version`` monotonically+ document via `apply()`, which advances `_version` monotonicallyand stamps the returned transaction.Returns:- ``(transaction, changed_cell_ids)``. ``transaction`` is+ `(transaction, changed_cell_ids)`. `transaction` isstamped with the post-apply document version and is suitable- for broadcasting to consumers. ``changed_cell_ids`` are the+ for broadcasting to consumers. `changed_cell_ids` are theids whose code, name, or config changed, plus all createdand deleted ids (reorder-only is excluded)."""@@ -214,7 +214,7 @@ class AppFileManager:) -> str:"""Save notebook to storage using appropriate format handler.- All file writes go through this method under ``_save_lock``.+ All file writes go through this method under `_save_lock`.Args:path: Target file path@@ -495,9 +495,9 @@ class AppFileManager:) -> str:"""Persist the notebook from a snapshot of document cells.- Used by the server-side auto-save path for ``code_mode``- mutations. Unlike ``save()``, this takes cells directly — the- caller is responsible for snapshotting ``session.document.cells``+ Used by the server-side auto-save path for `code_mode`+ mutations. Unlike `save()`, this takes cells directly — the+ caller is responsible for snapshotting `session.document.cells`on a thread where the document is quiescent.Raises:@@ -715,10 +715,10 @@ def _maybe_path(path: str | Path | None) -> Path | None:def _build_transaction(*, prev: CellManager, new: CellManager) -> tuple[Transaction, set[CellId_t]]:- """Diff two CellManagers, returning ``(transaction, changed_cell_ids)``.+ """Diff two CellManagers, returning `(transaction, changed_cell_ids)`.The transaction is unstamped; the caller applies it to the document- (which assigns ``version``). ``changed_cell_ids`` covers code, name,+ (which assigns `version`). `changed_cell_ids` covers code, name,or config changes plus all creates and deletes — reorder-only cellsare excluded."""diff --git a/marimo/_session/notebook/loader.py b/marimo/_session/notebook/loader.pyindex 2868d96411..7e1bf63421 100644--- a/marimo/_session/notebook/loader.py+++ b/marimo/_session/notebook/loader.py@@ -17,11 +17,11 @@ def load_notebook(*,defaults: AppDefaults | None = None,) -> AppFileManager:- """Load a notebook from a path into an ``AppFileManager``.+ """Load a notebook from a path into an `AppFileManager`.- The path is validated as a marimo source file (``.py`` / ``.md`` / ``.qmd``)+ The path is validated as a marimo source file (`.py` / `.md` / `.qmd`)and resolved to an absolute path before being handed to the file manager,- so a later ``chdir`` cannot change which file the manager points at.+ so a later `chdir` cannot change which file the manager points at."""marimo_path = MarimoPath(path)return AppFileManager(marimo_path.absolute_name, defaults=defaults)@@ -31,5 +31,5 @@ def new_notebook(*,defaults: AppDefaults | None = None,) -> AppFileManager:- """Create an unbacked ``AppFileManager`` for an untitled notebook."""+ """Create an unbacked `AppFileManager` for an untitled notebook."""return AppFileManager(None, defaults=defaults)diff --git a/marimo/_session/session.py b/marimo/_session/session.pyindex a25f23311b..6149396e0b 100644--- a/marimo/_session/session.py+++ b/marimo/_session/session.py@@ -257,9 +257,9 @@ class SessionImpl(Session):def document(self) -> NotebookDocument:"""The notebook document this session reflects.- Derived from ``self.app_file_manager.app.cell_manager.document``+ Derived from `self.app_file_manager.app.cell_manager.document`rather than stored, so any code path that swaps the underlying- ``CellManager`` or ``app`` (save round-trip, file-watch reload,+ `CellManager` or `app` (save round-trip, file-watch reload,export reload) is automatically picked up — no rebinding neededat the call sites. Read-only by design: the document's identitybelongs to the cell manager.diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.pyindex 805ef69ca3..20ad8f9b47 100644--- a/marimo/_session/state/session_view.py+++ b/marimo/_session/state/session_view.py@@ -64,7 +64,7 @@ class ModelReplayState:Internally uses a dict for buffers (path → bytes) so mergingupdates is a simple dict operation. Converted back to the wire- format (parallel lists) on replay via ``to_notification()``.+ format (parallel lists) on replay via `to_notification()`."""model_id: WidgetModelIddiff --git a/marimo/_session/types.py b/marimo/_session/types.pyindex f20fd6c469..3014a03b4d 100644--- a/marimo/_session/types.py+++ b/marimo/_session/types.py@@ -109,13 +109,13 @@ class KernelState(Enum):class KernelExitInfo:"""Information about how a kernel exited.- Populated after the kernel task has stopped. ``exitcode`` follows the- convention of ``multiprocessing.Process.exitcode``: ``>= 0`` for a normal- exit with that status, and ``< 0`` if the process was terminated by signal- ``-exitcode``. ``None`` means the exit status is unavailable -- either the+ Populated after the kernel task has stopped. `exitcode` follows the+ convention of `multiprocessing.Process.exitcode`: `>= 0` for a normal+ exit with that status, and `< 0` if the process was terminated by signal+ `-exitcode`. `None` means the exit status is unavailable -- either thetask has not yet terminated, or the underlying task type does not expose- one (e.g. threads). ``cause`` is a short machine-readable tag and- ``message`` is a human-readable one-liner suitable for logs or end-user+ one (e.g. threads). `cause` is a short machine-readable tag and+ `message` is a human-readable one-liner suitable for logs or end-userdisplay."""@@ -153,9 +153,9 @@ class Session(Protocol):...def kernel_exit_info(self) -> KernelExitInfo | None:- """Describe how the kernel exited, or ``None`` if it is still running.+ """Describe how the kernel exited, or `None` if it is still running.- Only meaningful once ``kernel_state() == KernelState.STOPPED``.+ Only meaningful once `kernel_state() == KernelState.STOPPED`."""...diff --git a/marimo/_sql/engines/adbc.py b/marimo/_sql/engines/adbc.pyindex 3fbd2dcffa..c7c7427a9a 100644--- a/marimo/_sql/engines/adbc.py+++ b/marimo/_sql/engines/adbc.py@@ -89,11 +89,11 @@ def _adbc_info_to_dialect(*, info: dict[str | int, Any]) -> str:"""Infer marimo's dialect identifier from ADBC metadata.Notes:- ADBC DB-API wrappers expose driver/database metadata via ``adbc_get_info()``,- including a ``vendor_name`` and ``driver_name`` (see ADBC quickstart:+ ADBC DB-API wrappers expose driver/database metadata via `adbc_get_info()`,+ including a `vendor_name` and `driver_name` (see ADBC quickstart:https://arrow.apache.org/adbc/current/python/quickstart.html).- In marimo, ``engine.dialect`` is used primarily for editor/formatter dialect+ In marimo, `engine.dialect` is used primarily for editor/formatter dialectselection and for display in the UI."""diff --git a/marimo/_sql/engines/sqlalchemy.py b/marimo/_sql/engines/sqlalchemy.pyindex e3ce61c124..31039c82bd 100644--- a/marimo/_sql/engines/sqlalchemy.py+++ b/marimo/_sql/engines/sqlalchemy.py@@ -69,10 +69,10 @@ def safe_execute(fallback: Value returned when the wrapped function raises.message: Message written to the logger on failure.log_level: Logger level – must be one of- ``'debug'``, ``'info'``, ``'warning'``, or ``'error'``.+ `'debug'`, `'info'`, `'warning'`, or `'error'`.silent_exceptions: Exception types that should return *fallback*without any logging. Useful for expected control-flow- exceptions like ``NotImplementedError``.+ exceptions like `NotImplementedError`."""def decorator(func: Callable[P, T]) -> Callable[P, T | F]:@@ -143,8 +143,8 @@ class SQLAlchemyEngine(SQLConnection["Engine"]):this opens a connection, executes the command, and yields aninspector bound to that connection.- For all other dialects, it yields ``self.inspector`` (which may- be ``None``).+ For all other dialects, it yields `self.inspector` (which may+ be `None`).Usage::diff --git a/marimo/_utils/asyncio_utils.py b/marimo/_utils/asyncio_utils.pyindex 94297c5973..16319af7d6 100644--- a/marimo/_utils/asyncio_utils.py+++ b/marimo/_utils/asyncio_utils.py@@ -1,12 +1,12 @@# Copyright 2026 Marimo. All rights reserved."""Small in-tree asyncio helpers.-- ``supervised_task`` / ``fire_and_forget``: create a task that won't be+- `supervised_task` / `fire_and_forget`: create a task that won't begarbage-collected mid-flight and whose non-cancellation exceptionsare always logged on completion (intended for fire-and-forget workwhere the loop's default handler would otherwise swallow them).-- ``cancel_and_wait``: the ``task.cancel(); await task`` /- ``except CancelledError`` dance, in one place.+- `cancel_and_wait`: the `task.cancel(); await task` /+ `except CancelledError` dance, in one place."""from __future__ import annotations@@ -49,20 +49,20 @@ def supervised_task(registry: set[asyncio.Task[Any]] | None = None,on_exception: Callable[[BaseException], None] | None = None,) -> asyncio.Task[T]:- """Schedule ``coro`` with a strong reference and exception logging.+ """Schedule `coro` with a strong reference and exception logging.Intended for fire-and-forget or shutdown-cancelled background tasks.A done-callback logs every non-cancellation exception at error level.- **Do not use this for tasks you plan to ``await``.** The done-callback+ **Do not use this for tasks you plan to `await`.** The done-callbacklogs the exception even if the awaiter also handles it, producing- duplicate logs. For awaited tasks, prefer plain ``asyncio.create_task``- — or pass ``on_exception=lambda _: None`` to opt out of logging while- still benefiting from the strong-ref ``registry`` tracking.+ duplicate logs. For awaited tasks, prefer plain `asyncio.create_task`+ — or pass `on_exception=lambda _: None` to opt out of logging while+ still benefiting from the strong-ref `registry` tracking.Args:coro: The coroutine to schedule.- name: Task name (shows up in logs and ``asyncio.all_tasks()``).+ name: Task name (shows up in logs and `asyncio.all_tasks()`).registry: Optional set the task is added to and removed from oncompletion. Pass one for lifespan-scoped tracking.on_exception: Optional callback that replaces the default error@@ -102,7 +102,7 @@ def supervised_task(def initialize_asyncio() -> None:"""Platform-specific initialization of asyncio.- Sessions use the ``add_reader()`` API, which is only available in+ Sessions use the `add_reader()` API, which is only available inthe SelectorEventLoop policy; Windows defaults to the Proactor."""if sys.platform == "win32":@@ -112,12 +112,12 @@ def initialize_asyncio() -> None:def fire_and_forget(coro: Coroutine[Any, Any, Any], *, name: str) -> asyncio.Task[Any] | None:- """Schedule ``coro`` on the running loop; caller will not await it.+ """Schedule `coro` on the running loop; caller will not await it.- Falls back to a synchronous ``asyncio.run`` (returning ``None``) when+ Falls back to a synchronous `asyncio.run` (returning `None`) whenno loop is running. The platform policy is initialized first so thefallback loop matches the selector-loop policy marimo relies on- elsewhere (required on Windows for ``add_reader``).+ elsewhere (required on Windows for `add_reader`)."""try:asyncio.get_running_loop()@@ -129,12 +129,12 @@ def fire_and_forget(async def cancel_and_wait(task: asyncio.Task[Any]) -> None:- """Cancel ``task`` and await its completion, suppressing ``CancelledError``.+ """Cancel `task` and await its completion, suppressing `CancelledError`.If the task is already done, any attached exception is markedretrieved so the loop doesn't log a "Task exception was neverretrieved" warning. The exception itself remains queryable via- ``task.exception()``. Non-cancellation exceptions raised during+ `task.exception()`. Non-cancellation exceptions raised duringcancellation propagate to the caller."""if task.done():diff --git a/marimo/_utils/distributor.py b/marimo/_utils/distributor.pyindex b4b9574de7..4230e8ba87 100644--- a/marimo/_utils/distributor.py+++ b/marimo/_utils/distributor.py@@ -93,7 +93,7 @@ class ConnectionDistributor(Distributor[T]):"""Start distributing the response.Must be called from a thread that has a running event loop —- ``add_reader`` is loop-bound.+ `add_reader` is loop-bound."""self._loop = asyncio.get_running_loop()self._loop.add_reader(self.input_connection.fileno(), self._on_change)diff --git a/marimo/_utils/log_formatter.py b/marimo/_utils/log_formatter.pyindex 15f6eeffee..9207946958 100644--- a/marimo/_utils/log_formatter.py+++ b/marimo/_utils/log_formatter.py@@ -37,13 +37,13 @@ class LogFormatter(logging.Formatter):Color support on Windows versions that do not support ANSI color codes isenabled by use of the colorama__ library. Applications that wish to use- this must first initialize colorama with a call to ``colorama.init``.+ this must first initialize colorama with a call to `colorama.init`.See the colorama documentation for details.__ https://pypi.python.org/pypi/colorama.. versionchanged:: 4.5- Added support for ``colorama``. Changed the constructor+ Added support for `colorama`. Changed the constructorsignature to be compatible with `logging.config.dictConfig`."""@@ -69,16 +69,16 @@ class LogFormatter(logging.Formatter)::arg bool color: Enables color support.:arg str fmt: Log message format.It will be applied to the attributes dict of log records. The- text between ``%(color)s`` and ``%(end_color)s`` will be colored+ text between `%(color)s` and `%(end_color)s` will be coloreddepending on the level if color support is on.:arg dict colors: color mappings from logging level to terminal colorcode:arg str datefmt: Datetime format.- Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.+ Used for formatting `(asctime)` placeholder in `prefix_fmt`... versionchanged:: 3.2- Added ``fmt`` and ``datefmt`` arguments.+ Added `fmt` and `datefmt` arguments."""del stylelogging.Formatter.__init__(self, datefmt=datefmt)diff --git a/marimo/_utils/methods.py b/marimo/_utils/methods.pyindex 55bd14e922..58bada1ca0 100644--- a/marimo/_utils/methods.py+++ b/marimo/_utils/methods.py@@ -10,11 +10,11 @@ from typing import Any, castdef is_callable_method(obj: Any, attr: str) -> bool:"""Check if an attribute is a real callable method on an object.- Uses ``inspect.getattr_static`` so that attributes synthesized by- ``__getattr__`` (e.g. ``pandas.api.typing.Expression``, which returns a- new ``Expression`` for *any* attribute name) are not treated as protocol+ Uses `inspect.getattr_static` so that attributes synthesized by+ `__getattr__` (e.g. `pandas.api.typing.Expression`, which returns a+ new `Expression` for *any* attribute name) are not treated as protocolmethods. Without this, dynamic-attribute objects appear to implement- ``_display_`` / ``_mime_`` / ``_repr_*_`` and trigger infinite recursion+ `_display_` / `_mime_` / `_repr_*_` and trigger infinite recursionin the formatter."""# Use getattr_static first so that we don't trigger __getattr__ trapsdiff --git a/marimo/_utils/net.py b/marimo/_utils/net.pyindex f8f8930ca4..398e32852e 100644--- a/marimo/_utils/net.py+++ b/marimo/_utils/net.py@@ -56,13 +56,13 @@ def _bind_sockets(or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwiseboth will be used if available.- The ``backlog`` argument has the same meaning as for+ The `backlog` argument has the same meaning as for`socket.listen() <socket.socket.listen>`.- ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like- ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.+ `flags` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like+ `socket.AI_PASSIVE | socket.AI_NUMERICHOST`.- ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket+ `reuse_port` option sets `SO_REUSEPORT` option for every socketin the list. If your platform doesn't support this option ValueError willbe raised."""diff --git a/marimo/_utils/paths.py b/marimo/_utils/paths.pyindex e8f3d39878..71716178d1 100644--- a/marimo/_utils/paths.py+++ b/marimo/_utils/paths.py@@ -58,15 +58,15 @@ MARIMO_DIR_NAME = "__marimo__"def notebook_output_dir(notebook_path: Path | str | None) -> Path:"""Compute the __marimo__ output directory for a given notebook.- When ``sys.pycache_prefix`` is set and the notebook path is absolute, the+ When `sys.pycache_prefix` is set and the notebook path is absolute, thedirectory tree is mirrored under the prefix (similar to how Python mirrors- ``__pycache__`` directories). Otherwise the ``__marimo__`` directory is+ `__pycache__` directories). Otherwise the `__marimo__` directory isplaced next to the notebook file.Resolution order:- 1. ``sys.pycache_prefix`` (if set and path is absolute): mirror tree- 2. Default: ``<notebook_parent>/__marimo__``- 3. Fallback (``None`` path): ``__marimo__`` relative to CWD+ 1. `sys.pycache_prefix` (if set and path is absolute): mirror tree+ 2. Default: `<notebook_parent>/__marimo__`+ 3. Fallback (`None` path): `__marimo__` relative to CWD"""if notebook_path is None:return Path(MARIMO_DIR_NAME)diff --git a/marimo/_utils/serial_task_runner.py b/marimo/_utils/serial_task_runner.pyindex f2101a10de..1fb510bcfd 100644--- a/marimo/_utils/serial_task_runner.py+++ b/marimo/_utils/serial_task_runner.py@@ -11,10 +11,10 @@ Usage::runner.shutdown() # on session closeawait runner.drain() # in async tests-``submit`` and ``shutdown`` must be called from the asyncio event loop-thread (or from any thread when no loop is running). ``work`` runs on-the executor thread; ``on_error`` is routed back to the loop thread via-``call_soon_threadsafe`` so it can safely touch asyncio primitives.+`submit` and `shutdown` must be called from the asyncio event loop+thread (or from any thread when no loop is running). `work` runs on+the executor thread; `on_error` is routed back to the loop thread via+`call_soon_threadsafe` so it can safely touch asyncio primitives."""from __future__ import annotations@@ -57,17 +57,17 @@ class SerialTaskRunner:*,on_error: Callable[[Exception], None] | None = None,) -> None:- """Run ``work()`` on the serial worker thread.+ """Run `work()` on the serial worker thread.Offloads to the executor when called from the event loop;otherwise runs inline on the caller thread (e.g. the- ``QueueDistributor`` worker thread). ``on_error`` is invoked- with any exception raised by ``work`` — posted back to the event- loop when off-loop, inline otherwise. A failing ``on_error`` is+ `QueueDistributor` worker thread). `on_error` is invoked+ with any exception raised by `work` — posted back to the event+ loop when off-loop, inline otherwise. A failing `on_error` islogged and swallowed.- After ``shutdown()``, ``submit`` is a no-op (and logs at debug).- Without this guard, ``cached_property`` would silently+ After `shutdown()`, `submit` is a no-op (and logs at debug).+ Without this guard, `cached_property` would silentlyre-materialize a fresh executor — and a new worker thread — forany late submissions that race session teardown."""@@ -129,7 +129,7 @@ class SerialTaskRunner:async def drain(self) -> None:"""Await every in-flight task, then clear the pending list.- ``return_exceptions=True`` so a failing task doesn't abort the drain.+ `return_exceptions=True` so a failing task doesn't abort the drain."""if not self._pending:return@@ -139,10 +139,10 @@ class SerialTaskRunner:def shutdown(self, *, wait: bool = False) -> None:"""Tear down the executor. Idempotent; no-op if never materialized.- Uses ``__dict__.pop`` so we don't trigger the ``cached_property``- just to shut it down. Sets ``_closed`` so any subsequent- ``submit`` becomes a no-op instead of re-materializing a new- executor via ``cached_property``.+ Uses `__dict__.pop` so we don't trigger the `cached_property`+ just to shut it down. Sets `_closed` so any subsequent+ `submit` becomes a no-op instead of re-materializing a new+ executor via `cached_property`."""self._closed = Trueexecutor = self.__dict__.pop("_executor", None)diff --git a/marimo/_utils/strings.py b/marimo/_utils/strings.pyindex ea70395367..8468da5ad6 100644--- a/marimo/_utils/strings.py+++ b/marimo/_utils/strings.py@@ -61,13 +61,13 @@ def _mslex_quote(s: str) -> str:Quote a string for use as a command line argument in DOS or Windows.:param s: a string to quote- :param for_cmd: quote it for ``cmd.exe``+ :param for_cmd: quote it for `cmd.exe`:return: quoted string- If ``for_cmd`` is true, then this will quote the strings so the result will- be parsed correctly by ``cmd.exe`` and then by ``CommandLineToArgvW``. If+ If `for_cmd` is true, then this will quote the strings so the result will+ be parsed correctly by `cmd.exe` and then by `CommandLineToArgvW`. Iffalse, then this will quote the strings so the result will- be parsed correctly when passed directly to ``CommandLineToArgvW``.+ be parsed correctly when passed directly to `CommandLineToArgvW`."""if not s:return '""'diff --git a/marimo/_utils/url.py b/marimo/_utils/url.pyindex 22a6d4874b..abc937fda7 100644--- a/marimo/_utils/url.py+++ b/marimo/_utils/url.py@@ -98,8 +98,8 @@ pattern = re.compile(regex)def is_url(value: str, public: bool = False) -> bool:"""Return whether or not given value is a valid URL.- If the value is valid URL this function returns ``True``, otherwise- returns ``False``.+ If the value is valid URL this function returns `True`, otherwise+ returns `False`.This validator is based on the wonderful `URL validator of dperini`_... _URL validator of dperini:@@ -122,7 +122,7 @@ def is_url(value: str, public: bool = False) -> bool:Added support for various exotic URLs and fixed various falsepositives... versionchanged:: 0.10.3- Added ``public`` parameter.+ Added `public` parameter... versionchanged:: 0.11.0Made the regular expression this function uses case insensitive... versionchanged:: 0.11.3diff --git a/marimo/_utils/variable_name.py b/marimo/_utils/variable_name.pyindex 4e9e3e8a6b..42be9e5bfc 100644--- a/marimo/_utils/variable_name.py+++ b/marimo/_utils/variable_name.py@@ -10,10 +10,10 @@ LOGGER = _loggers.marimo_logger()def infer_variable_name(value: Any, fallback: str) -> str:- """Infer the variable name that holds ``value`` in the caller's caller.+ """Infer the variable name that holds `value` in the caller's caller.Walks up two frames (skipping this helper and the direct caller) and- searches locals for an identity match (``is``). Returns *fallback* if+ searches locals for an identity match (`is`). Returns *fallback* ifthe lookup fails for any reason.Frame references are always cleaned up to avoid reference cycles.diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 27dc721cb7..ab6028fd35 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -733,10 +733,10 @@ components:CompletedRunNotification:description: "Run of submitted cells and descendants completed.\n\n Attributes:\n\\ run_id: Correlation ID echoed from the command that triggered\n \- \ this completion. ``None`` for handlers that don't take a\n \- \ ``run_id`` (everything except ``handle_execute_scratchpad``\n \- \ today). Consumers that want to wait for a specific command's\n\- \ completion filter on this field."+ \ this completion. `None` for handlers that don't take a\n \+ \ `run_id` (everything except `handle_execute_scratchpad`\n \+ \ today). Consumers that want to wait for a specific command's\n \+ \ completion filter on this field."properties:op:enum:@@ -1512,11 +1512,11 @@ components:\ Snapshot of notebook cells from the session document.\n Used\\ to populate the document ContextVar so code_mode can read\n cell\\ ordering, code, names, and configs.\n run_id: Optional correlation\- \ ID. When set, the\n ``CompletedRunNotification`` emitted at the\- \ end of this command\n carries the same ``run_id`` so a caller\- \ holding a\n ``ScratchCellListener`` can filter for *its* completion\- \ and\n ignore ``CompletedRun`` events from unrelated commands\- \ on the\n same session."+ \ ID. When set, the\n `CompletedRunNotification` emitted at the\+ \ end of this command\n carries the same `run_id` so a caller holding\+ \ a\n `ScratchCellListener` can filter for *its* completion and\n\+ \ ignore `CompletedRun` events from unrelated commands on the\n\+ \ same session."properties:code:type: string@@ -1692,9 +1692,9 @@ components:FileCreateMultipartRequest:description: "multipart/form-data body for POST /api/files/create.\n\n Schema-only:\\ this struct exists to describe the multipart shape in\n OpenAPI. At runtime,\- \ the endpoint reads the string fields from\n ``MultipartRequest.body``\- \ and the uploaded bytes from\n ``MultipartRequest.files[\"file\"]`` \u2014\- \ ``body.file`` is never populated."+ \ the endpoint reads the string fields from\n `MultipartRequest.body` and\+ \ the uploaded bytes from\n `MultipartRequest.files[\"file\"]` \u2014 `body.file`\+ \ is never populated."properties:file:anyOf:@@ -2744,11 +2744,11 @@ components:type: objectLintConfig:description: "Configuration for lint rule selection.\n\n Follows ruff-inspired\- \ semantics for selecting which rules to run\n during ``marimo check``.\n\- \n **Keys.**\n\n - ``select``: list of rule code prefixes that replaces\- \ the default\n enabled set. Use ``\"ALL\"`` to select all rules.\n \- \ Example: ``[\"MB\", \"MR001\"]``\n - ``ignore``: list of rule code\- \ prefixes to remove from the\n enabled set."+ \ semantics for selecting which rules to run\n during `marimo check`.\n\+ \n **Keys.**\n\n - `select`: list of rule code prefixes that replaces\+ \ the default\n enabled set. Use `\"ALL\"` to select all rules.\n \+ \ Example: `[\"MB\", \"MR001\"]`\n - `ignore`: list of rule code prefixes\+ \ to remove from the\n enabled set."properties:ignore:items:@@ -3580,7 +3580,9 @@ components:title: MultipleDefinitionErrortype: objectNotebookCell:- description: "A single cell in the document. Mutable \u2014 owned by the document."+ description: "A single cell in the document. Mutable \u2014 owned by the document.\n\+ \n `version` increments on each `SetCode` that actually changes\n `code`.\+ \ Other property changes don't bump it."properties:code:type: string@@ -3590,6 +3592,9 @@ components:$ref: '#/components/schemas/CellId'name:type: string+ version:+ default: 0+ type: integerrequired:- id- code@@ -4072,8 +4077,8 @@ components:type: objectReorderCells:description: "Replace the full cell ordering.\n\n Cell IDs present in the\- \ document but missing from ``cell_ids``\n are appended at the end. IDs\- \ not in the document are ignored."+ \ document but missing from `cell_ids`\n are appended at the end. IDs not\+ \ in the document are ignored."properties:cellIds:items:@@ -5081,8 +5086,8 @@ components:type: objectTransaction:description: "An atomic batch of changes applied to a NotebookDocument.\n\n\- \ ``source`` identifies the writer (e.g. ``\"frontend\"``, ``\"kernel\"\- ``).\n ``version`` is ``None`` when created and stamped by\n ``NotebookDocument.apply()``."+ \ `source` identifies the writer (e.g. `\"frontend\"`, `\"kernel\"`).\n\+ \ `version` is `None` when created and stamped by\n `NotebookDocument.apply()`."properties:changes:items:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex e4b05c760a..9439fc0a3c 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -3810,8 +3810,8 @@ export interface components {** Attributes:* run_id: Correlation ID echoed from the command that triggered- * this completion. ``None`` for handlers that don't take a- * ``run_id`` (everything except ``handle_execute_scratchpad``+ * this completion. `None` for handlers that don't take a+ * `run_id` (everything except `handle_execute_scratchpad`* today). Consumers that want to wait for a specific command's* completion filter on this field.*/@@ -4279,10 +4279,10 @@ export interface components {* Used to populate the document ContextVar so code_mode can read* cell ordering, code, names, and configs.* run_id: Optional correlation ID. When set, the- * ``CompletedRunNotification`` emitted at the end of this command- * carries the same ``run_id`` so a caller holding a- * ``ScratchCellListener`` can filter for *its* completion and- * ignore ``CompletedRun`` events from unrelated commands on the+ * `CompletedRunNotification` emitted at the end of this command+ * carries the same `run_id` so a caller holding a+ * `ScratchCellListener` can filter for *its* completion and+ * ignore `CompletedRun` events from unrelated commands on the* same session.*/ExecuteScratchpadCommand: {@@ -4381,8 +4381,8 @@ export interface components {** Schema-only: this struct exists to describe the multipart shape in* OpenAPI. At runtime, the endpoint reads the string fields from- * ``MultipartRequest.body`` and the uploaded bytes from- * ``MultipartRequest.files["file"]`` — ``body.file`` is never populated.+ * `MultipartRequest.body` and the uploaded bytes from+ * `MultipartRequest.files["file"]` — `body.file` is never populated.*/FileCreateMultipartRequest: {/**@@ -5015,14 +5015,14 @@ export interface components {* @description Configuration for lint rule selection.** Follows ruff-inspired semantics for selecting which rules to run- * during ``marimo check``.+ * during `marimo check`.** **Keys.***- * - ``select``: list of rule code prefixes that replaces the default- * enabled set. Use ``"ALL"`` to select all rules.- * Example: ``["MB", "MR001"]``- * - ``ignore``: list of rule code prefixes to remove from the+ * - `select`: list of rule code prefixes that replaces the default+ * enabled set. Use `"ALL"` to select all rules.+ * Example: `["MB", "MR001"]`+ * - `ignore`: list of rule code prefixes to remove from the* enabled set.*/LintConfig: {@@ -5490,12 +5490,17 @@ export interface components {/*** NotebookCell* @description A single cell in the document. Mutable — owned by the document.+ *+ * `version` increments on each `SetCode` that actually changes+ * `code`. Other property changes don't bump it.*/NotebookCell: {code: string;config: components["schemas"]["CellConfig"];id: components["schemas"]["CellId"];name: string;+ /** @default 0 */+ version?: number;};/*** NotebookDocumentTransactionNotification@@ -5819,7 +5824,7 @@ export interface components {* ReorderCells* @description Replace the full cell ordering.*- * Cell IDs present in the document but missing from ``cell_ids``+ * Cell IDs present in the document but missing from `cell_ids`* are appended at the end. IDs not in the document are ignored.*/ReorderCells: {@@ -6456,9 +6461,9 @@ export interface components {* Transaction* @description An atomic batch of changes applied to a NotebookDocument.*- * ``source`` identifies the writer (e.g. ``"frontend"``, ``"kernel"``).- * ``version`` is ``None`` when created and stamped by- * ``NotebookDocument.apply()``.+ * `source` identifies the writer (e.g. `"frontend"`, `"kernel"`).+ * `version` is `None` when created and stamped by+ * `NotebookDocument.apply()`.*/Transaction: {changes: (diff --git a/scripts/check_docstring_backticks.py b/scripts/check_docstring_backticks.pynew file mode 100644index 0000000000..4b9ae73a12--- /dev/null+++ b/scripts/check_docstring_backticks.py@@ -0,0 +1,79 @@+# Copyright 2026 Marimo. All rights reserved.+"""Fail if any docstring uses double backticks for inline code.++marimo renders docstrings as Markdown, where inline code uses single+backticks (`value`). Double backticks are reStructuredText+syntax and render incorrectly. This check flags them.++Triple-backtick Markdown code fences are allowed.++Usage:+ python scripts/check_docstring_backticks.py [files...]+"""++from __future__ import annotations++import ast+import sys++# A run of exactly two backticks, not adjacent to a third. This matches+# RST-style inline code (``value``) while ignoring Markdown code fences+# (``` or longer), where every interior pair is backtick-adjacent.+import re++_DOUBLE_BACKTICK = re.compile(r"(?<!`)``(?!`)")++_DOCSTRINGABLE = (+ ast.Module,+ ast.ClassDef,+ ast.FunctionDef,+ ast.AsyncFunctionDef,+)+++def check_file(path: str) -> list[str]:+ """Return a list of `path:line: message` errors for one file."""+ try:+ with open(path, encoding="utf-8") as f:+ source = f.read()+ except (OSError, UnicodeDecodeError) as e:+ return [f"{path}: could not read file ({e})"]++ try:+ tree = ast.parse(source, filename=path)+ except SyntaxError:+ # Leave syntax errors to other tools (ruff, the compiler).+ return []++ errors: list[str] = []+ for node in ast.walk(tree):+ if not isinstance(node, _DOCSTRINGABLE):+ continue+ docstring = ast.get_docstring(node, clean=False)+ if docstring and _DOUBLE_BACKTICK.search(docstring):+ # ast.Module has no lineno; its docstring starts the file.+ lineno = getattr(node, "lineno", 1)+ errors.append(+ f"{path}:{lineno}: double backticks in docstring"+ )+ return errors+++def main(argv: list[str]) -> int:+ errors: list[str] = []+ for path in argv:+ errors.extend(check_file(path))++ if errors:+ print("\n".join(errors), file=sys.stderr)+ print(+ "\nUse single backticks for inline code in docstrings "+ "(`value`, not ``value``).",+ file=sys.stderr,+ )+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex c91e4bb854..b06bd21640 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -1715,11 +1715,11 @@ class TestAppComposition:class TestInternalAppWithData:- """``InternalApp.with_data`` rewrites the cell list from the+ """`InternalApp.with_data` rewrites the cell list from thefrontend's snapshot during the save round-trip. It must mutate theexisting cell manager in place — Session holds- ``app.cell_manager.document`` as a property, so swapping in a fresh- manager would orphan ``session.document``.+ `app.cell_manager.document` as a property, so swapping in a fresh+ manager would orphan `session.document`."""def test_preserves_cell_manager_identity(self) -> None:diff --git a/tests/_ast/test_cell_manager.py b/tests/_ast/test_cell_manager.pyindex febb2b24f9..f714be2b3b 100644--- a/tests/_ast/test_cell_manager.py+++ b/tests/_ast/test_cell_manager.py@@ -661,8 +661,8 @@ class TestSortCellIdsBySimilarity:class TestDocumentProperty:- """``cell_manager.document`` exposes the underlying NotebookDocument- that holds canonical cell state. Identity matters: ``Session.document``+ """`cell_manager.document` exposes the underlying NotebookDocument+ that holds canonical cell state. Identity matters: `Session.document`is a property that reads through this; consumers diff against the sameinstance over time."""@@ -682,8 +682,8 @@ class TestDocumentProperty:class TestGetCellDataView:- """``get_cell_data`` returns a freshly synthesized ``CellData`` view- over the stored ``NotebookCell``. The view is read-only by convention:+ """`get_cell_data` returns a freshly synthesized `CellData` view+ over the stored `NotebookCell`. The view is read-only by convention:rebinding a field on the returned object must not leak back into thedocument, since callers commonly use it as a scratch struct."""@@ -713,10 +713,10 @@ class TestGetCellDataView:class TestReplaceStateFrom:- """``_replace_state_from`` is the in-place substitute for- ``self = other``. It preserves identity of ``_document`` and- ``_compiled_cells`` so external holders of those references — most- notably the owning ``Session`` — see the new state without any+ """`_replace_state_from` is the in-place substitute for+ `self = other`. It preserves identity of `_document` and+ `_compiled_cells` so external holders of those references — most+ notably the owning `Session` — see the new state without anyrebinding."""@@ -782,9 +782,9 @@ class TestReplaceStateFrom:class TestSortCellIdsByCompiledCells:- """``sort_cell_ids_by_similarity`` rekeys ``_compiled_cells`` in+ """`sort_cell_ids_by_similarity` rekeys `_compiled_cells` inlockstep with the document's cell ids. This matters because lookups- in ``cell_data()`` join the two by id; drift between them surfaces as+ in `cell_data()` join the two by id; drift between them surfaces as"cell exists but has no compiled form" or vice versa."""diff --git a/tests/_code_mode/test_cells_view.py b/tests/_code_mode/test_cells_view.pyindex 9061fbc079..71c65b5313 100644--- a/tests/_code_mode/test_cells_view.py+++ b/tests/_code_mode/test_cells_view.py@@ -395,7 +395,7 @@ class TestCellsViewGrep:@dataclasses.dataclassclass _MockImpl:- """Minimal stand-in for CellImpl — satisfies ``CellRuntimeState`` protocol."""+ """Minimal stand-in for CellImpl — satisfies `CellRuntimeState` protocol."""code: str = ""runtime_state: str | None = Nonediff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.pyindex 6a4e17908b..9cad631f66 100644--- a/tests/_code_mode/test_context.py+++ b/tests/_code_mode/test_context.py@@ -36,7 +36,7 @@ def _ctx() -> Generator[AsyncCodeModeContext, None, None]:"""Build an AsyncCodeModeContext with a document snapshot from the kernel.- ``extra_doc_cells`` adds cells to the document that are *not* in the+ `extra_doc_cells` adds cells to the document that are *not* in thekernel graph, simulating cells that exist on disk but were never run."""cells = [diff --git a/tests/_code_mode/test_context_autosave.py b/tests/_code_mode/test_context_autosave.pyindex a0379b59ef..2cf5a6a6a3 100644--- a/tests/_code_mode/test_context_autosave.py+++ b/tests/_code_mode/test_context_autosave.py@@ -1,11 +1,11 @@# Copyright 2026 Marimo. All rights reserved."""End-to-end tests: code_mode mutations → interceptor → file on disk.-These tests connect two well-tested pieces (``code_mode`` producing-transactions and ``NotificationListenerExtension`` consuming them) by-taking the transactions code_mode emits from a real ``Kernel`` and+These tests connect two well-tested pieces (`code_mode` producing+transactions and `NotificationListenerExtension` consuming them) by+taking the transactions code_mode emits from a real `Kernel` andfeeding them through the auto-save interceptor against a real-``AppFileManager`` backed by a temp file.+`AppFileManager` backed by a temp file."""from __future__ import annotations@@ -79,7 +79,7 @@ def _ctx(k: Kernel) -> Generator[AsyncCodeModeContext, None, None]:def _read_disk(app_file_manager: AppFileManager) -> str:"""Sync helper to read a notebook file from disk (avoids ASYNC240 in- async tests driven by ``pytest-asyncio`` + code_mode fixtures)."""+ async tests driven by `pytest-asyncio` + code_mode fixtures)."""path = app_file_manager.pathassert path is not Nonereturn Path(path).read_text()@@ -87,7 +87,7 @@ def _read_disk(app_file_manager: AppFileManager) -> str:def _make_notebook_fixture(filename: str, contents: str):"""Build a parametrizable fixture that creates an AppFileManager backed- by ``tmp_path / filename`` pre-populated with ``contents``."""+ by `tmp_path / filename` pre-populated with `contents`."""@pytest.fixturedef _fixture(tmp_path: Path) -> AppFileManager:@@ -134,7 +134,7 @@ async def _drain(ext: NotificationListenerExtension,session: Mock,) -> None:- """Forward every NotebookDocumentTransactionNotification on ``k.stream``+ """Forward every NotebookDocumentTransactionNotification on `k.stream`through the interceptor so disk state catches up with the kernel graph.Auto-save is dispatched to the runner's executor when a running loop@@ -148,7 +148,7 @@ async def _drain(class TestCodeModeAutoSavePy:- """code_mode ops land on a ``.py`` file on disk."""+ """code_mode ops land on a `.py` file on disk."""async def test_create_cell_persists(self,@@ -229,7 +229,7 @@ class TestCodeModeAutoSavePy:class TestCodeModeAutoSaveMd:- """code_mode ops land on a ``.md`` file on disk."""+ """code_mode ops land on a `.md` file on disk."""async def test_create_cell_persists(self,diff --git a/tests/_code_mode/test_screenshot.py b/tests/_code_mode/test_screenshot.pyindex 06718de3d7..a3bbbc12c6 100644--- a/tests/_code_mode/test_screenshot.py+++ b/tests/_code_mode/test_screenshot.py@@ -77,10 +77,10 @@ class TestScreenshotSessionAuthUrl:class _FakeCells:- """Minimal stand-in for ``_CellsView`` used by the resolver tests.+ """Minimal stand-in for `_CellsView` used by the resolver tests.- Supports the operations ``_resolve_screenshot_target`` actually- calls — ``__len__``, integer indexing, and ``_resolve(str)`` — so+ Supports the operations `_resolve_screenshot_target` actually+ calls — `__len__`, integer indexing, and `_resolve(str)` — sothe resolver can run without a live kernel/document."""@@ -108,7 +108,7 @@ class _FakeCells:def _fake_ctx(cell_ids: list[str], names: dict[str, str] | None = None) -> Any:- """Build an object usable as ``self`` for the resolver method."""+ """Build an object usable as `self` for the resolver method."""return SimpleNamespace(cells=_FakeCells(cell_ids, names))diff --git a/tests/_plugins/ui/_impl/test_from_mpl_interactive.py b/tests/_plugins/ui/_impl/test_from_mpl_interactive.pyindex 6533eff0db..56bf0f243e 100644--- a/tests/_plugins/ui/_impl/test_from_mpl_interactive.py+++ b/tests/_plugins/ui/_impl/test_from_mpl_interactive.py@@ -189,9 +189,9 @@ class TestHandleDownload:class TestDpiPreservationOnRerun:"""Re-running a cell that wraps the same figure should not compound DPI.- matplotlib's ``FigureCanvasBase.__init__`` unconditionally captures- ``figure._original_dpi = figure.dpi``. After a HiDPI client connects- and scales ``figure.dpi`` up by the device pixel ratio, a subsequent+ matplotlib's `FigureCanvasBase.__init__` unconditionally captures+ `figure._original_dpi = figure.dpi`. After a HiDPI client connects+ and scales `figure.dpi` up by the device pixel ratio, a subsequentcanvas creation on the same figure would treat that scaled value as"original" and scale it again — making the resolution compound onevery rerun (see issue #9466).diff --git a/tests/_runtime/test_patches.py b/tests/_runtime/test_patches.pyindex 9b820f8f31..6c2cb56b8f 100644--- a/tests/_runtime/test_patches.py+++ b/tests/_runtime/test_patches.py@@ -255,7 +255,7 @@ def test_polars_write_json_patch(tmp_path: Path):def _const_fallback(value: object) -> Callable[..., object]:- """Build a fallback that ignores its arguments and returns ``value``."""+ """Build a fallback that ignores its arguments and returns `value`."""def _fb(*_args: object, **_kwargs: object) -> object:return valuediff --git a/tests/_runtime/test_requests.py b/tests/_runtime/test_requests.pyindex 86ad2079d3..190c2681d2 100644--- a/tests/_runtime/test_requests.py+++ b/tests/_runtime/test_requests.py@@ -184,10 +184,10 @@ def test_from_request_user_already_dict_passthrough():def test_command_msgspec_json_decode_command_with_http_request():- """Regression for the Pyodide path: ``parse_dataclass`` builds a- ``msgspec.json`` decoder for any Command containing an ``HTTPRequest``+ """Regression for the Pyodide path: `parse_dataclass` builds a+ `msgspec.json` decoder for any Command containing an `HTTPRequest`field. msgspec.json rejects unions with two array-like members, so- ``Encodable`` must avoid e.g. ``list | tuple`` simultaneously.+ `Encodable` must avoid e.g. `list | tuple` simultaneously."""from marimo._runtime.commands import ExecuteCellCommanddiff --git a/tests/_save/test_encode.py b/tests/_save/test_encode.pyindex 3599fcec8d..a364091643 100644--- a/tests/_save/test_encode.py+++ b/tests/_save/test_encode.py@@ -18,9 +18,9 @@ HAS_NUMPY = DependencyManager.numpy.has()class _ArrayWithSet:"""Array-like whose pickle is non-deterministic across processes.- The ``_tags`` set has hash-randomized iteration order across Python- processes (PYTHONHASHSEED), so ``pickle.dumps`` produces different bytes- on each run. But since this class has ``__array__``, ``_ContentHashPickler``+ The `_tags` set has hash-randomized iteration order across Python+ processes (PYTHONHASHSEED), so `pickle.dumps` produces different bytes+ on each run. But since this class has `__array__`, `_ContentHashPickler`replaces it with a deterministic content hash of the array data, discardingthe non-deterministic set entirely."""@@ -49,7 +49,7 @@ def test_deterministic_for_same_data_different_set() -> None:"""Two objects with same array data but different set attrs must hash the same.This mirrors the cross-process case: PYTHONHASHSEED changes set iteration- order, so ``pickle.dumps`` differs between processes. ``deterministic_dumps``+ order, so `pickle.dumps` differs between processes. `deterministic_dumps`must not — it is content-addressed on the array data only."""data = list(range(10))diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.pyindex 8d5e28be7a..316bb32afb 100644--- a/tests/_server/api/endpoints/test_execution.py+++ b/tests/_server/api/endpoints/test_execution.py@@ -163,7 +163,7 @@ class TestExecutionRoutes_EditMode:@with_session(SESSION_ID)def test_execute_injects_screenshot_meta(client: TestClient) -> None:"""`/api/kernel/execute` injects a trusted server URL + auth token- into ``HTTPRequest.meta`` so ``ctx.screenshot()`` can authenticate+ into `HTTPRequest.meta` so `ctx.screenshot()` can authenticatePlaywright against this server. Regression guard: deleting eitherinjection line in the endpoint should fail this test."""diff --git a/tests/_server/api/endpoints/ws/test_ws_kernel_ready.py b/tests/_server/api/endpoints/ws/test_ws_kernel_ready.pyindex 8ebceda304..41442a0a0a 100644--- a/tests/_server/api/endpoints/ws/test_ws_kernel_ready.py+++ b/tests/_server/api/endpoints/ws/test_ws_kernel_ready.py@@ -2,10 +2,10 @@"""Tests for _extract_cell_data reading from the NotebookDocument.The key change under test: `_extract_cell_data` now reads from-``session.document`` (a ``NotebookDocument``) rather than directly from-``session.app_file_manager.app.cell_manager``. This means that-document-level mutations (applied via ``notebook-document-transaction``)-are reflected when a new client connects and receives ``kernel-ready``.+`session.document` (a `NotebookDocument`) rather than directly from+`session.app_file_manager.app.cell_manager`. This means that+document-level mutations (applied via `notebook-document-transaction`)+are reflected when a new client connects and receives `kernel-ready`."""from __future__ import annotationsdiff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.pyindex b836921cd4..9e33816406 100644--- a/tests/_server/test_file_manager.py+++ b/tests/_server/test_file_manager.py@@ -231,7 +231,7 @@ def test_save_cannot_rename(app_file_manager: AppFileManager) -> None:def test_save_from_cells_persists_cells(app_file_manager: AppFileManager,) -> None:- """``save_from_cells`` should round-trip cells through the serializer."""+ """`save_from_cells` should round-trip cells through the serializer."""from marimo._messaging.notebook.document import NotebookCellapp_file_manager.save_from_cells(@@ -254,7 +254,7 @@ def test_save_from_cells_persists_cells(def test_save_from_cells_empty_name_normalizes(app_file_manager: AppFileManager,) -> None:- """Empty cell names must serialize as the default ``_`` rather than+ """Empty cell names must serialize as the default `_` rather thanfalling back to the unparsable-cell path."""from marimo._messaging.notebook.document import NotebookCell@@ -288,7 +288,7 @@ def test_save_from_cells_unnamed_raises(def test_save_from_cells_preserves_layout_file(app_file_manager: AppFileManager,) -> None:- """``save_from_cells`` must keep ``layout_file`` in app config."""+ """`save_from_cells` must keep `layout_file` in app config."""from marimo._messaging.notebook.document import NotebookCellapp_file_manager.app.update_config({"layout_file": "layouts/x.grid.json"})@@ -308,7 +308,7 @@ def test_save_from_cells_preserves_layout_file(def test_save_and_save_from_cells_serialize_under_lock(app_file_manager: AppFileManager,) -> None:- """Concurrent ``save`` + ``save_from_cells`` on the same manager must+ """Concurrent `save` + `save_from_cells` on the same manager mustproduce a valid (non-torn) file. Also regression-tests that thereentrant lock covers both entry points."""import threadingdiff --git a/tests/_server/test_scratchpad_integration.py b/tests/_server/test_scratchpad_integration.pyindex d9eef38ed9..5e556e0210 100644--- a/tests/_server/test_scratchpad_integration.py+++ b/tests/_server/test_scratchpad_integration.py@@ -1,31 +1,31 @@# Copyright 2026 Marimo. All rights reserved."""Snapshot tests for what an agent sees when driving code-mode.-``code_mode`` + ``/api/kernel/execute`` are the agent's window into+`code_mode` + `/api/kernel/execute` are the agent's window intothe notebook: whatever the agent does (run cells, mutate the graph,trigger reactive cascades, hit state setters) it learns about onlythrough the SSE stream that endpoint returns. We want explicitcoverage of that surface across the scenarios the agent can reach,so when the output changes we see it.-The existing in-process ``TestClient`` fixture mocks the scratchpad+The existing in-process `TestClient` fixture mocks the scratchpadstream out entirely, so real kernel timing and cross-processnotification ordering aren't testable there. These tests share one-``marimo edit`` subprocess across the module and drive it through+`marimo edit` subprocess across the module and drive it throughthe full HTTP surface: a websocket for session setup and-``completed-run`` synchronization, ``/api/document/transaction`` to-populate ``session.document`` (required for ``code_mode`` cell-lookup by name), ``/api/kernel/run`` to register and execute cells,-and ``/api/kernel/execute`` to hit the scratchpad. Each test gets a-fresh session via a per-test ``session`` fixture that calls-``/api/kernel/restart_session`` on teardown. The response body is+`completed-run` synchronization, `/api/document/transaction` to+populate `session.document` (required for `code_mode` cell+lookup by name), `/api/kernel/run` to register and execute cells,+and `/api/kernel/execute` to hit the scratchpad. Each test gets a+fresh session via a per-test `session` fixture that calls+`/api/kernel/restart_session` on teardown. The response body issnapshotted as SSE lines with volatile paths and version-specifictraceback noise scrubbed.Each test's snapshot encodes the expected SSE output for that-scenario — failure cases land in ``done`` with-``{success: false, output: {mimetype: "text/plain", data: ""}}``;-error detail arrives earlier in the stream as ``stderr`` SSE events.+scenario — failure cases land in `done` with+`{success: false, output: {mimetype: "text/plain", data: ""}}`;+error detail arrives earlier in the stream as `stderr` SSE events."""from __future__ import annotations@@ -98,11 +98,11 @@ def _wait_for_server(def _server(tmp_path_factory: pytest.TempPathFactory,) -> Generator[str, None, None]:- """One ``marimo edit`` subprocess shared across the module.+ """One `marimo edit` subprocess shared across the module.- Per-test isolation comes from the ``session`` fixture which uses- a unique ``session_id`` — each WS connect creates a fresh kernel- and empty ``session.document``.+ Per-test isolation comes from the `session` fixture which uses+ a unique `session_id` — each WS connect creates a fresh kernel+ and empty `session.document`."""tmp = tmp_path_factory.mktemp("mnb")port = _free_port()@@ -148,7 +148,7 @@ def _server(class _Session:"""Per-test session: unique ID → fresh kernel + empty document.- Wraps the websocket + HTTP calls. Use ``wait_for_completed_run`` to+ Wraps the websocket + HTTP calls. Use `wait_for_completed_run` tosynchronize with kernel activity instead of sleeping."""@@ -181,7 +181,7 @@ class _Session:predicate: Callable[[dict[str, Any]], bool],timeout_s: float = 10.0,) -> dict[str, Any]:- """Drain WS until a message matches ``predicate(msg)``."""+ """Drain WS until a message matches `predicate(msg)`."""deadline = time.monotonic() + timeout_swhile True:remaining = deadline - time.monotonic()@@ -193,7 +193,7 @@ class _Session:return msgdef wait_for_completed_run(self, timeout_s: float = 10.0) -> None:- """Block until the kernel broadcasts a ``completed-run`` event."""+ """Block until the kernel broadcasts a `completed-run` event."""self._recv_until(lambda m: m.get("op") == "completed-run",timeout_s=timeout_s,@@ -236,13 +236,13 @@ class _Session:codes: list[str],names: list[str] | None = None,) -> None:- """Register cells in both ``session.document`` and the kernel graph.+ """Register cells in both `session.document` and the kernel graph.- ``/api/kernel/run`` only touches the graph; ``ctx.edit_cell`` /- ``ctx.run_cell`` in code_mode look up cells from- ``session.document``, which is kept in sync via document+ `/api/kernel/run` only touches the graph; `ctx.edit_cell` /+ `ctx.run_cell` in code_mode look up cells from+ `session.document`, which is kept in sync via documenttransactions from the frontend. We emulate the frontend with- typed ``CreateCell`` changes.+ typed `CreateCell` changes."""if names is None:names = cell_ids@@ -260,7 +260,7 @@ class _Session:self.run_cells(cell_ids, codes)def execute(self, code: str) -> list[str]:- """Run ``code`` via /api/kernel/execute; return normalized SSE lines."""+ """Run `code` via /api/kernel/execute; return normalized SSE lines."""body = self._post("/api/kernel/execute", {"code": code})return _normalize(body)@@ -379,9 +379,9 @@ def test_scratchpad_compile_error(session: _Session) -> None:"""Scratchpad code that fails to compile (SyntaxError).Guards that compile-time errors reach the client with actionable- detail. Compile failures never go through ``redirect_streams`` /- ``write_traceback`` (the cell never runs), so the diagnostic has- to be emitted explicitly as a ``stderr`` SSE event before ``done``.+ detail. Compile failures never go through `redirect_streams` /+ `write_traceback` (the cell never runs), so the diagnostic has+ to be emitted explicitly as a `stderr` SSE event before `done`."""lines = session.execute("def :")@@ -430,12 +430,12 @@ def test_scratchpad_itself_errors(session: _Session) -> None:def test_state_setter_cascade_error(session: _Session) -> None:- """Scratchpad calls ``set_x(0)`` → downstream cell_b divides by zero.+ """Scratchpad calls `set_x(0)` → downstream cell_b divides by zero.- Issue #9255 scenario 1. ``state_updates`` flush happens after scratch+ Issue #9255 scenario 1. `state_updates` flush happens after scratchcell goes idle, so the listener sentinel fires before cell_b's- MARIMO_ERROR arrives. Currently fails on main — the ``done`` event- says ``success: true`` and the cascade error is silent.+ MARIMO_ERROR arrives. Currently fails on main — the `done` event+ says `success: true` and the cascade error is silent."""# cell_b sleeps past the listener's 50ms grace window so its# reactive re-run completes AFTER ``stream()`` returns — that's@@ -471,7 +471,7 @@ def test_state_setter_cascade_error(session: _Session) -> None:def test_state_chain_cascade_error(session: _Session) -> None:- """Nested state chain: ``set_x(0)`` → cell_b calls ``set_y`` →+ """Nested state chain: `set_x(0)` → cell_b calls `set_y` →slow cell_d divides by zero. Listener must capture cell_d's errortwo state-update hops away."""@@ -560,7 +560,7 @@ def test_multiple_downstream_cells_all_error(session: _Session) -> None:def test_scratchpad_raises_after_triggering_cascade(session: _Session,) -> None:- """Scratchpad calls ``set_x(0)`` (slow cascade) then ``raise``.+ """Scratchpad calls `set_x(0)` (slow cascade) then `raise`.Both the scratch error AND the cascade error should be visible —currently only the scratch error surfaces, so the agent sees the@@ -607,10 +607,10 @@ def test_scratchpad_raises_after_triggering_cascade(def test_ctx_run_cell_cascade_error(session: _Session) -> None:- """``ctx.edit_cell + ctx.run_cell`` on cell_a triggers cell_b to+ """`ctx.edit_cell + ctx.run_cell` on cell_a triggers cell_b toreactively re-run and error (issue #9255 scenario 2).- Goes through ``_apply_ops`` which awaits ``_run_cells``+ Goes through `_apply_ops` which awaits `_run_cells`synchronously — the listener sees the downstream error before thesentinel fires. Regression guard for the working path."""@@ -654,12 +654,12 @@ def test_ctx_run_cell_cascade_error(session: _Session) -> None:def test_ctx_create_cell_multiply_defined(session: _Session) -> None:- """``ctx.create_cell`` introducing a duplicate definition errors early.+ """`ctx.create_cell` introducing a duplicate definition errors early.- The notebook already has ``x = 10`` in ``cell_a``. code_mode's- dry-run compile detects the new cell would multiply-define ``x``- and raises ``RuntimeError`` before any real mutation — the new- cell is never registered and ``x`` stays ``10``.+ The notebook already has `x = 10` in `cell_a`. code_mode's+ dry-run compile detects the new cell would multiply-define `x`+ and raises `RuntimeError` before any real mutation — the new+ cell is never registered and `x` stays `10`."""session.setup_cells(["cell_a"], ["x = 10"])@@ -682,14 +682,14 @@ def test_ctx_create_cell_multiply_defined(session: _Session) -> None:def test_ctx_create_cell_skip_validation(session: _Session) -> None:- """``skip_validation=True`` bypasses the dry-run compile check.+ """`skip_validation=True` bypasses the dry-run compile check.Same setup as above, but the caller opts out of validation — no- ``RuntimeError`` is raised and the new cell is registered, as- evidenced by the ``created cell`` stdout summary. The kernel's own+ `RuntimeError` is raised and the new cell is registered, as+ evidenced by the `created cell` stdout summary. The kernel's owngraph-validity pass still flags the resulting multiply-definedstate (visible to the listener as a child error, hence- ``success: false``), but no traceback reaches stderr because the+ `success: false`), but no traceback reaches stderr because thenew cell never runs — the error is a pure graph-state marker."""session.setup_cells(["cell_a"], ["x = 10"])diff --git a/tests/_server/test_workspace.py b/tests/_server/test_workspace.pyindex 5d4be31b35..665530366d 100644--- a/tests/_server/test_workspace.py+++ b/tests/_server/test_workspace.py@@ -37,7 +37,7 @@ app = marimo.App()def _marimo_file(path: str, name: str = "test.py") -> MarimoFile:- """Build a ``MarimoFile`` for a real path on disk."""+ """Build a `MarimoFile` for a real path on disk."""return MarimoFile(name=name,path=path,@@ -268,7 +268,7 @@ class TestNotebookWorkspace(unittest.TestCase):assert exc.value.status_code == HTTPStatus.NOT_FOUNDdef test_fixed_files_accepts_dotdot_that_normalizes_to_allowed(self):- """Regression test for #8414 — ``..`` paths must normalize correctly."""+ """Regression test for #8414 — `..` paths must normalize correctly."""dotdot_path = os.path.join(self.nested_dir, "..", os.path.basename(self.test_file1.name))@@ -278,7 +278,7 @@ class TestNotebookWorkspace(unittest.TestCase):assert os.path.exists(resolved)def test_fixed_files_new_file_key_is_rejected(self):- """``__new__`` keys are not valid in run mode."""+ """`__new__` keys are not valid in run mode."""workspace = FixedFilesWorkspace([])with pytest.raises(HTTPException) as exc:workspace.resolve(NewFileKey())@@ -287,15 +287,15 @@ class TestNotebookWorkspace(unittest.TestCase):# ----- security: DirectoryWorkspace -----def test_directory_workspace_new_file_key_returns_none(self):- """``NewFileKey`` resolves to ``None`` (a blank notebook)."""+ """`NewFileKey` resolves to `None` (a blank notebook)."""workspace = DirectoryWorkspace(self.test_dir, include_markdown=False)assert workspace.resolve(NewFileKey()) is Nonedef test_directory_workspace_only_exact_sentinel_is_new(self):- """Only the exact ``__new__`` sentinel resolves to the blank notebook.+ """Only the exact `__new__` sentinel resolves to the blank notebook.After the FileKey ADT migration, anything other than the literal- ``__new__`` parses to a :class:`PathFileKey` and goes through normal+ `__new__` parses to a :class:`PathFileKey` and goes through normalcontainment validation."""workspace = DirectoryWorkspace(self.test_dir, include_markdown=False)@@ -311,7 +311,7 @@ class TestNotebookWorkspace(unittest.TestCase):)def test_directory_workspace_temp_dir_does_not_enable_traversal(self):- """A temp-dir bypass must not let attackers escape via ``..``."""+ """A temp-dir bypass must not let attackers escape via `..`."""with (tempfile.TemporaryDirectory() as base_dir,tempfile.TemporaryDirectory() as temp_dir,@@ -333,7 +333,7 @@ class TestNotebookWorkspace(unittest.TestCase):# ----- security: EmptyWorkspace -----def test_empty_workspace_load_with_new_file_key_returns_blank(self):- """Bare ``__new__`` key always yields an unbacked manager."""+ """Bare `__new__` key always yields an unbacked manager."""workspace = EmptyWorkspace()manager = workspace.load(NewFileKey())assert manager.filename is None@@ -346,7 +346,7 @@ class TestNotebookWorkspace(unittest.TestCase):assert exc.value.status_code == HTTPStatus.NOT_FOUNDdef test_empty_workspace_resolve_returns_absolute_normalized(self):- """``resolve`` must return an absolute, normalized path so downstream+ """`resolve` must return an absolute, normalized path so downstreamlookups (session keys, comparisons) don't mismatch between relativeand absolute spellings of the same file."""@@ -363,12 +363,12 @@ class TestNotebookWorkspace(unittest.TestCase):os.chdir(original_cwd)def test_empty_workspace_load_with_existing_path_falls_back(self):- """``marimo new`` boots an EmptyWorkspace; opening a recent file must+ """`marimo new` boots an EmptyWorkspace; opening a recent file muststill work via the unconditional existence fallback.This is intentionally permissive — there's no allowlist, since theboot mode has no concept of one. Threat model: anyone able to hit- ``marimo new``'s endpoint already has the same trust level as the+ `marimo new`'s endpoint already has the same trust level as theprocess owner."""workspace = EmptyWorkspace()@@ -392,7 +392,7 @@ def test_file_key_wire_format() -> None:def test_parse_file_key_only_exact_sentinel_is_new() -> None:- """Strings that look like ``__new__`` prefixes are paths, not new files."""+ """Strings that look like `__new__` prefixes are paths, not new files."""assert parse_file_key(NEW_FILE_WIRE) == NewFileKey()assert parse_file_key("__new__suffix.py") == PathFileKey("__new__suffix.py"diff --git a/tests/_session/extensions/test_notification_listener_autosave.py b/tests/_session/extensions/test_notification_listener_autosave.pyindex 9024401b52..e1fb1d77e5 100644--- a/tests/_session/extensions/test_notification_listener_autosave.py+++ b/tests/_session/extensions/test_notification_listener_autosave.py@@ -331,7 +331,7 @@ class TestUnnamedNotebook:def _get_alerts(session: Mock) -> list[AlertNotification]:- """Extract every ``AlertNotification`` the interceptor broadcast."""+ """Extract every `AlertNotification` the interceptor broadcast."""return [call.args[0]for call in session.notify.call_args_list@@ -424,9 +424,9 @@ class TestFailureSurfaces:class TestCellSnapshotIsolation:- """``_maybe_autosave`` must deep-copy cells before scheduling the- save. ``NotebookCell`` and ``CellConfig`` are mutable and owned by- the document, so a shallow ``list(...)`` would let the event-loop+ """`_maybe_autosave` must deep-copy cells before scheduling the+ save. `NotebookCell` and `CellConfig` are mutable and owned by+ the document, so a shallow `list(...)` would let the event-loopthread mutate fields under the worker thread's feet — a tornsnapshot / data race."""@@ -473,7 +473,7 @@ class TestCellSnapshotIsolation:existing_cell_id: CellId_t,) -> None:"""Regression: if the shallow-copy bug returned, clobbering- ``cell.code`` / ``cell.config`` on the document after submit+ `cell.code` / `cell.config` on the document after submitwould also clobber the snapshot the worker thread is about toread."""received: list[list[NotebookCell]] = []diff --git a/tests/_session/test_file_change_handler.py b/tests/_session/test_file_change_handler.pyindex 1caec18946..9f210b3e6f 100644--- a/tests/_session/test_file_change_handler.py+++ b/tests/_session/test_file_change_handler.py@@ -42,10 +42,10 @@ if TYPE_CHECKING:def _cm_from_doc(doc: NotebookDocument) -> CellManager:- """Build a ``CellManager`` mirroring ``doc``'s cells.+ """Build a `CellManager` mirroring `doc`'s cells.- Used to drive ``_build_transaction`` from tests that already- express the prior state as a synthetic ``NotebookDocument``.+ Used to drive `_build_transaction` from tests that already+ express the prior state as a synthetic `NotebookDocument`."""cm = CellManager()for cell in doc.cells:diff --git a/tests/_utils/test_serial_task_runner.py b/tests/_utils/test_serial_task_runner.pyindex 200a015f0a..7fbd5325ac 100644--- a/tests/_utils/test_serial_task_runner.py+++ b/tests/_utils/test_serial_task_runner.py@@ -120,8 +120,8 @@ class TestAsyncPath:async def test_on_error_runs_on_event_loop_thread(self, runner: SerialTaskRunner) -> None:- """``on_error`` must be posted back to the loop via- ``call_soon_threadsafe`` — many callers need to touch asyncio+ """`on_error` must be posted back to the loop via+ `call_soon_threadsafe` — many callers need to touch asyncioprimitives that are not thread-safe."""loop_thread = threading.current_thread()handler_thread: list[threading.Thread] = []@@ -199,8 +199,8 @@ class TestShutdown:def test_submit_after_shutdown_sync_is_noop(self) -> None:"""Regression: a stray submit() after shutdown must not- re-materialize the ``cached_property`` executor — otherwise- session teardown can race with ``QueueDistributor.stop()`` and+ re-materialize the `cached_property` executor — otherwise+ session teardown can race with `QueueDistributor.stop()` andspin up a brand-new worker thread on the way out."""runner = SerialTaskRunner(thread_name_prefix="closed-sync")runner.shutdown()diff --git a/tests/conftest.py b/tests/conftest.pyindex 657afcd9e2..d0d91f944a 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -461,9 +461,9 @@ def exec_req() -> ExecReqProvider:class MockPyodide:"""Simulate running in a Pyodide environment.- Patches ``sys.platform`` to ``"emscripten"`` so ``is_pyodide()`` returns- True, and stubs ``pyodide`` (plus any ``extra_modules``) in- ``sys.modules`` so ``import pyodide`` (and friends) succeeds.+ Patches `sys.platform` to `"emscripten"` so `is_pyodide()` returns+ True, and stubs `pyodide` (plus any `extra_modules`) in+ `sys.modules` so `import pyodide` (and friends) succeeds.Usable as a context manager or as a decorator on sync or async tests::diff --git a/tests/mocks.py b/tests/mocks.pyindex ea9461e18f..1871b3c4ad 100644--- a/tests/mocks.py+++ b/tests/mocks.py@@ -168,7 +168,7 @@ def _replace_braced_value(text: str, key: str, placeholder: str) -> str:Uses brace-counting so it works with arbitrarily nested objects.The quote style is inferred from *key* so the placeholder matches the- surrounding context (e.g. escaped ``\\"`` vs plain ``"``).+ surrounding context (e.g. escaped `\\"` vs plain `"`)."""q = '\\"' if '\\"' in key else '"'idx = 0