Skip to content

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

chore(ruff): enable type variable and docstring checks (#10660)

Shahmir Varqha5c888b9bf0c9
diff --git a/marimo/_ai/_tools/base.py b/marimo/_ai/_tools/base.py
index 89f2685e5e..e222ecf79c 100644
--- a/marimo/_ai/_tools/base.py
+++ b/marimo/_ai/_tools/base.py
@@ -44,9 +44,6 @@ LOGGER = _loggers.marimo_logger()
ArgsT = TypeVar("ArgsT")
OutT = TypeVar("OutT")
-ArgsP = TypeVar("ArgsP", contravariant=True)
-OutC = TypeVar("OutC", covariant=True)
-
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
diff --git a/marimo/_ast/dedent.py b/marimo/_ast/dedent.py
index d902af1a98..52b298e786 100644
--- a/marimo/_ast/dedent.py
+++ b/marimo/_ast/dedent.py
@@ -13,7 +13,7 @@ _NEWLINE_RE = re.compile(r"\r\n|\r|\n")
def split_source_lines(text: str, keepends: bool = False) -> list[str]:
- """Split source into lines the way `ast`/`tokenize` count them.
+ r"""Split source into lines the way `ast`/`tokenize` count them.
Unlike `str.splitlines()`, this only treats `\n`, `\r`, and `\r\n` as
line breaks. `str.splitlines()` additionally splits on `\f`, `\v`, the
diff --git a/marimo/_ast/parse.py b/marimo/_ast/parse.py
index eb7421344a..8a85e40d89 100644
--- a/marimo/_ast/parse.py
+++ b/marimo/_ast/parse.py
@@ -55,11 +55,11 @@ def ast_parse(
def split_source_lines(text: str) -> list[str]:
- """Split source into lines the way `ast`/`tokenize` count them.
+ r"""Split source into lines the way `ast`/`tokenize` count them.
- Unlike `str.splitlines()`, this only treats `\\n`, `\\r`, and `\\r\\n` as
- line breaks. `str.splitlines()` additionally splits on `\\f`, `\\v`, the
- `\\x1c`-`\\x1e` separators, and Unicode line separators.
+ Unlike `str.splitlines()`, this only treats `\n`, `\r`, and `\r\n` as
+ line breaks. `str.splitlines()` additionally splits on `\f`, `\v`, the
+ `\x1c`-`\x1e` separators, and Unicode line separators.
"""
return text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index bbaf3e89c6..d1212d805f 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -183,12 +183,12 @@ def _normalize_sandbox_dependencies(
def _resolve_local_path_line(line: str, script_dir: Path) -> str:
- """Resolve a relative local-path requirement to an absolute path.
+ r"""Resolve a relative local-path requirement to an absolute path.
>>> _resolve_local_path_line(
... "-e ../pkg ; py<'3.12' # via foo", Path("/a/b")
... )
- '-e /a/pkg ; py<\\'3.12\\' # via foo'
+ '-e /a/pkg ; py<\'3.12\' # via foo'
"""
rest = line.removeprefix("-e ")
path_and_comment, _, _ = rest.partition(";")
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index 4c4b3a2a0e..3b364e5ae4 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -612,14 +612,14 @@ class _CellsView:
]
def grep(self, pattern: str) -> Sequence[NotebookCell]:
- """Return cells whose code matches the regex *pattern*.
+ r"""Return cells whose code matches the regex *pattern*.
Uses :func:`re.search` so the pattern can match anywhere in
the cell's code.
Example::
- ctx.cells.grep(r"alt\\.Chart")
+ ctx.cells.grep(r"alt\.Chart")
"""
import re
diff --git a/marimo/_convert/ipynb/from_ir.py b/marimo/_convert/ipynb/from_ir.py
index dd43953a16..c3d77dc8ea 100644
--- a/marimo/_convert/ipynb/from_ir.py
+++ b/marimo/_convert/ipynb/from_ir.py
@@ -372,14 +372,14 @@ def _convert_output_to_ipynb(
def _clean_ansi_for_export(text: Any) -> str:
- """Clean ANSI escape codes for export, keeping color codes intact.
+ r"""Clean ANSI escape codes for export, keeping color codes intact.
ANSI codes are terminal styling sequences (colors, bold, cursor movement)
used by logging libraries like rich, colorama, and marimo's own logger.
- We keep standard color codes (like \\x1b[34m) so nbconvert's LaTeX template
+ We keep standard color codes (like \x1b[34m) so nbconvert's LaTeX template
can convert them to colors via its ansi2latex filter. However, we must strip
- character set selection sequences (like \\x1b(B) which nbconvert doesn't
+ character set selection sequences (like \x1b(B) which nbconvert doesn't
handle and cause LaTeX to fail with "invalid character" errors.
"""
if not isinstance(text, str):
diff --git a/marimo/_lint/rules/breaking/unparsable.py b/marimo/_lint/rules/breaking/unparsable.py
index 8db8cb73c1..4107c34b8a 100644
--- a/marimo/_lint/rules/breaking/unparsable.py
+++ b/marimo/_lint/rules/breaking/unparsable.py
@@ -12,7 +12,7 @@ if TYPE_CHECKING:
class UnparsableRule(LintRule):
- """MB001: Cell contains unparsable code.
+ r"""MB001: Cell contains unparsable code.
This rule detects cells that contain code that cannot be parsed as valid Python.
Unparsable cells typically occur when a notebook file is corrupted, contains invalid
@@ -34,7 +34,7 @@ class UnparsableRule(LintRule):
**Problematic:**
```python
# Cell with encoding issues or corrupt data
- x = 1 \\x00\\x01\\x02 # Binary data in source
+ x = 1 \x00\x01\x02 # Binary data in source
```
**Problematic:**
diff --git a/marimo/_lint/rules/formatting/parsing.py b/marimo/_lint/rules/formatting/parsing.py
index 4b9ee7c5f9..1847d43899 100644
--- a/marimo/_lint/rules/formatting/parsing.py
+++ b/marimo/_lint/rules/formatting/parsing.py
@@ -95,7 +95,7 @@ class StdoutRule(LintRule):
class StderrRule(LintRule):
- """MF003: Parse captured stderr during notebook loading.
+ r"""MF003: Parse captured stderr during notebook loading.
This rule processes any output that was captured from stderr while marimo
was parsing and loading a notebook file. Stderr output typically contains
@@ -123,13 +123,13 @@ class StderrRule(LintRule):
**Captured stderr:**
```
- notebook.py:68: SyntaxWarning: invalid escape sequence '\\l'
+ notebook.py:68: SyntaxWarning: invalid escape sequence '\l'
```
**Result:** Creates a diagnostic pointing to line 68 about the invalid escape sequence.
**Common issues:**
- - Raw strings needed: `r"\\path\\to\\file"` instead of `"\\path\\to\\file"`
+ - Raw strings needed: `r"\path\to\file"` instead of `"\path\to\file"`
- Deprecated library usage
- Missing import dependencies
diff --git a/marimo/_output/md_extensions/display_math.py b/marimo/_output/md_extensions/display_math.py
index 267a96ea08..835c5fd12d 100644
--- a/marimo/_output/md_extensions/display_math.py
+++ b/marimo/_output/md_extensions/display_math.py
@@ -64,13 +64,13 @@ class DisplayMathPreprocessor(preprocessors.Preprocessor): # type: ignore[misc]
)
def _normalize_math_syntax(self, text: str) -> str:
- """Convert supported math delimiters in non-inline-code regions.
+ r"""Convert supported math delimiters in non-inline-code regions.
Supported conversions:
- `: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):
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.py
index ec7bff949a..c59447f284 100644
--- a/marimo/_server/ai/providers.py
+++ b/marimo/_server/ai/providers.py
@@ -106,7 +106,7 @@ class BaseModelSettings:
thinking: ThinkingLevel | None
-ProviderT = TypeVar("ProviderT", bound="Provider", covariant=True)
+ProviderT_co = TypeVar("ProviderT_co", bound="Provider", covariant=True)
def _structured_completion_finish_reason(
@@ -128,7 +128,7 @@ def _structured_completion_finish_reason(
return "other"
-class PydanticProvider(ABC, Generic[ProviderT]):
+class PydanticProvider(ABC, Generic[ProviderT_co]):
def __init__(
self,
model: str,
@@ -152,10 +152,10 @@ class PydanticProvider(ABC, Generic[ProviderT]):
self.model: str = model
self.config: AnyProviderConfig = config
- self.provider: ProviderT = self.create_provider(config)
+ self.provider: ProviderT_co = self.create_provider(config)
@abstractmethod
- def create_provider(self, config: AnyProviderConfig) -> ProviderT:
+ def create_provider(self, config: AnyProviderConfig) -> ProviderT_co:
"""Create a provider for the given config."""
@abstractmethod
diff --git a/marimo/_server/templates/api.py b/marimo/_server/templates/api.py
index 0f55176fbe..f39b462b7c 100644
--- a/marimo/_server/templates/api.py
+++ b/marimo/_server/templates/api.py
@@ -82,7 +82,7 @@ def render_notebook(
asset_url: str | None = None,
custom_css: str | None = None,
) -> str:
- """Render a marimo notebook to HTML.
+ r"""Render a marimo notebook to HTML.
Handles all the conversions internally.
@@ -107,7 +107,7 @@ def render_notebook(
Example:
>>> html = render_notebook(
- ... code="import marimo as mo\\nmo.md('Hello')",
+ ... code="import marimo as mo\nmo.md('Hello')",
... filename="notebook.py",
... mode="edit",
... runtime_config=[{"url": "wss://kernel.example.com"}],
diff --git a/marimo/_utils/distributor.py b/marimo/_utils/distributor.py
index 4230e8ba87..f2ecc5b4b5 100644
--- a/marimo/_utils/distributor.py
+++ b/marimo/_utils/distributor.py
@@ -14,16 +14,16 @@ from marimo._utils.typed_connection import TypedConnection
LOGGER = _loggers.marimo_logger()
-T = TypeVar("T", covariant=True)
+T_co = TypeVar("T_co", covariant=True)
-Consumer = Callable[[T], None]
+Consumer = Callable[[T_co], None]
-class Distributor(Protocol, Generic[T]):
+class Distributor(Protocol, Generic[T_co]):
"""Base class for distributors."""
- def add_consumer(self, consumer: Consumer[T]) -> Disposable:
+ def add_consumer(self, consumer: Consumer[T_co]) -> Disposable:
"""Add a consumer to the distributor."""
...
@@ -36,7 +36,7 @@ class Distributor(Protocol, Generic[T]):
...
-class ConnectionDistributor(Distributor[T]):
+class ConnectionDistributor(Distributor[T_co]):
"""
Used to distribute the response of a multiprocessing Connection to multiple
consumers.
@@ -52,14 +52,14 @@ class ConnectionDistributor(Distributor[T]):
for context.
"""
- def __init__(self, input_connection: TypedConnection[T]) -> None:
- self.consumers: list[Consumer[T]] = []
+ def __init__(self, input_connection: TypedConnection[T_co]) -> None:
+ self.consumers: list[Consumer[T_co]] = []
self.input_connection = input_connection
# Captured on start() so stop() uses the same loop the reader
# was registered with — even if another loop is running by then.
self._loop: asyncio.AbstractEventLoop | None = None
- def add_consumer(self, consumer: Consumer[T]) -> Disposable:
+ def add_consumer(self, consumer: Consumer[T_co]) -> Disposable:
"""Add a consumer to the distributor."""
self.consumers.append(consumer)
@@ -109,9 +109,9 @@ class ConnectionDistributor(Distributor[T]):
self.consumers.clear()
-class QueueDistributor(Distributor[T]):
- def __init__(self, queue: QueueType[T | None]) -> None:
- self.consumers: list[Consumer[T]] = []
+class QueueDistributor(Distributor[T_co]):
+ def __init__(self, queue: QueueType[T_co | None]) -> None:
+ self.consumers: list[Consumer[T_co]] = []
# distributor uses None as a signal to stop
self.queue = queue
self.thread: threading.Thread | None = None
@@ -119,7 +119,7 @@ class QueueDistributor(Distributor[T]):
# protects the consumers list
self._lock = threading.Lock()
- def add_consumer(self, consumer: Consumer[T]) -> Disposable:
+ def add_consumer(self, consumer: Consumer[T_co]) -> Disposable:
"""Add a consumer to the distributor."""
with self._lock:
self.consumers.append(consumer)
diff --git a/marimo/_utils/requests.py b/marimo/_utils/requests.py
index 02eafa223c..630d43402c 100644
--- a/marimo/_utils/requests.py
+++ b/marimo/_utils/requests.py
@@ -47,7 +47,7 @@ class Response:
return json.loads(self.text())
def text(self) -> str:
- """Get response content as text.
+ r"""Get response content as text.
This assumes the response is UTF-8 encoded.
In future, we can infer the encoding from the headers.
diff --git a/marimo/_utils/strings.py b/marimo/_utils/strings.py
index 8468da5ad6..6b77eb65bc 100644
--- a/marimo/_utils/strings.py
+++ b/marimo/_utils/strings.py
@@ -96,7 +96,7 @@ def cmd_quote(s: str) -> str:
def standardize_annotation_quotes(annotation: str) -> str:
- """Standardize quotes in type annotations to use double quotes.
+ r"""Standardize quotes in type annotations to use double quotes.
This handles complex cases like Literal['foo', 'bar'] -> Literal["foo", "bar"]
while preserving mixed quote scenarios where double quotes are already present.
diff --git a/pyproject.toml b/pyproject.toml
index 5299cfa0ec..bfd4ca1ea6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -348,7 +348,6 @@ ignore = [
"G004", # Logging statement uses f-string
"TC001", # Move application import into a type-checking block
"TC006", # Add quotes to type expression in typing.cast()
- "D301", # Use r""" if any backslashes in a docstring
"PERF203", # try-except within a loop incurs performance overhead; not always possible
"PERF401", # Use {message_str} to create a transformed list; at the cost of readability
"PERF403", # Use a dictionary comprehension instead of a for-loop; at the cost of readability
@@ -381,7 +380,6 @@ ignore = [
"DTZ012", # `date.fromtimestamp()` called without `tzinfo`
"DTZ901", # `datetime.min` / `datetime.max` used
"S112", # `try`-`except`-`continue`
- "PLC0105", # Type name incorrect variance
"PLW1509", # `subprocess` `preexec_fn` argument
"DTZ002", # `datetime.today()` called without tz
"PLE0704", # Misplaced bare `raise`