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
chore: enable preview rules from ruff (#3663)
Myles Scolnick9acad2cac818
diff --git a/marimo/_ast/pytest.py b/marimo/_ast/pytest.pyindex 8fcd67cfd4..ad7d4dcfb1 100644--- a/marimo/_ast/pytest.py+++ b/marimo/_ast/pytest.py@@ -52,7 +52,7 @@ def wrap_fn_for_pytest(ast.arg(arg, lineno=args[arg].lineno, col_offset=args[arg].col_offset)for arg in fixtures]- (call_stub,) = call.keywords+ (_call_stub,) = call.keywordscall.keywords = [ast.keyword(arg=arg,diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.pyindex b6de2fbd84..c22c8dc19c 100644--- a/marimo/_cli/file_path.py+++ b/marimo/_cli/file_path.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport abcimport json-import loggingimport osimport pathlibimport urllib.parse@@ -12,10 +11,13 @@ from tempfile import TemporaryDirectoryfrom typing import Optional, Tuplefrom urllib.error import HTTPError+from marimo import _loggersfrom marimo._cli.print import greenfrom marimo._utils.marimo_path import MarimoPathfrom marimo._utils.url import is_url+LOGGER = _loggers.marimo_logger()+def is_github_src(url: str, ext: str) -> bool:if not is_url(url):@@ -99,7 +101,7 @@ class StaticNotebookReader(FileReader):@staticmethoddef _is_static_marimo_notebook_url(url: str) -> tuple[bool, str]:def download(url: str) -> tuple[bool, str]:- logging.info("Downloading %s", url)+ LOGGER.info("Downloading %s", url)request = urllib.request.Request(url,# User agent to avoid 403 Forbidden some bot protection@@ -278,11 +280,11 @@ class RemoteFileHandler(FileHandler):def _create_tmp_file_from_content(content: str, name: str, temp_dir: TemporaryDirectory[str]) -> str:- logging.info("Creating temporary file")+ LOGGER.info("Creating temporary file")path_to_app = os.path.join(temp_dir.name, name)with open(path_to_app, "w") as f:f.write(content)- logging.info("App saved to %s", path_to_app)+ LOGGER.info("App saved to %s", path_to_app)return path_to_appdiff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.pyindex 79daa98c62..199bba68d2 100644--- a/marimo/_output/formatting.py+++ b/marimo/_output/formatting.py@@ -325,14 +325,14 @@ def plain(value: Any) -> Plain:return Plain(value)+@dataclassclass Plain:"""Wrapper around a value to indicate that it should be displayedwithout any opinionated formatting."""- def __init__(self, child: Any):- self.child = child+ child: Any@mddocdiff --git a/marimo/_plugins/ui/_impl/tables/format.py b/marimo/_plugins/ui/_impl/tables/format.pyindex ffce47e6d1..9f66cf9445 100644--- a/marimo/_plugins/ui/_impl/tables/format.py+++ b/marimo/_plugins/ui/_impl/tables/format.py@@ -3,8 +3,11 @@ from __future__ import annotationsfrom typing import Callable, Dict, List, Union+from marimo import _loggersfrom marimo._plugins.core.web_component import JSONType+LOGGER = _loggers.marimo_logger()+FormatMapping = Dict[str, Union[str, Callable[..., JSONType]]]@@ -38,9 +41,7 @@ def format_value(if callable(formatter):return formatter(value)except Exception as e:- import logging-- logging.warning(+ LOGGER.warning(f"Error formatting for value {value} in column {col}: {str(e)}")return valuediff --git a/marimo/_save/ast.py b/marimo/_save/ast.pyindex 344c07fe29..52ee42c88c 100644--- a/marimo/_save/ast.py+++ b/marimo/_save/ast.py@@ -80,7 +80,7 @@ class ExtractWithBlock(ast.NodeTransformer):super().__init__(*arg, **kwargs)self.target_line = line- def generic_visit(self, node: ast.AST) -> tuple[ast.Module, ast.Module]: # type: ignore[override]+ def generic_visit(self, node: ast.AST) -> tuple[ast.Module, ast.Module]: # type: ignore[override]pre_block = []# There are a few strange edges cases like:diff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex 550f666b73..93beb4cd06 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -968,7 +968,7 @@ def content_cache_attempt_from_base(refs, scope, ctx)- refs, content, tmp_stateful_refs = hasher.collect_for_content_hash(+ refs, _content, tmp_stateful_refs = hasher.collect_for_content_hash(refs, scope, ctx, scoped_refs, apply_hash=True)# If the execution block covers this variable, then that's OKdiff --git a/marimo/_server/api/endpoints/terminal.py b/marimo/_server/api/endpoints/terminal.pyindex 91ed3a173d..b20b74df90 100644--- a/marimo/_server/api/endpoints/terminal.py+++ b/marimo/_server/api/endpoints/terminal.py@@ -91,7 +91,7 @@ async def websocket_endpoint(websocket: WebSocket) -> None:child_pid, fd = pty.fork()if child_pid == 0:default_shell = os.environ.get("SHELL", "/bin/bash")- subprocess.run([default_shell], shell=True) ## noqa: ASYNC221+ subprocess.run([default_shell], shell=True) # noqa: ASYNC221returnreader_task = asyncio.create_task(_read_from_pty(fd, websocket))@@ -118,5 +118,5 @@ async def websocket_endpoint(websocket: WebSocket) -> None:if writer_task and not writer_task.done():writer_task.cancel()os.kill(child_pid, signal.SIGKILL)- os.waitpid(child_pid, 0) ## noqa: ASYNC222+ os.waitpid(child_pid, 0) # noqa: ASYNC222LOGGER.debug("Terminal websocket closed")diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex d8dcc029c6..5043fa9e73 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -2,6 +2,7 @@from __future__ import annotationsimport asyncio+from dataclasses import dataclassfrom http.client import HTTPResponse, HTTPSConnectionfrom typing import (TYPE_CHECKING,@@ -162,14 +163,12 @@ class OpenTelemetryMiddleware(BaseHTTPMiddleware):return response+@dataclassclass _URLRequest:- def __init__(- self, url: str, method: str, headers: dict[str, str], data: Any- ):- self.full_url = url- self.method = method- self.headers = headers- self.data = data+ full_url: str+ method: str+ headers: dict[str, str]+ data: Anyclass _AsyncHTTPResponse:diff --git a/marimo/_server/export/utils.py b/marimo/_server/export/utils.pyindex 7c54e53458..892f6586b5 100644--- a/marimo/_server/export/utils.py+++ b/marimo/_server/export/utils.py@@ -13,7 +13,7 @@ from marimo._server.file_manager import AppFileManagerdef format_filename_title(filename: str) -> str:basename = os.path.basename(filename)- name, ext = os.path.splitext(basename)+ name, _ext = os.path.splitext(basename)title = re.sub("[-_]", " ", name)return title.title()diff --git a/pyproject.toml b/pyproject.tomlindex 9aeff506f8..dd09142183 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -304,9 +304,11 @@ exclude = [][tool.ruff.lint]+preview = trueignore = ["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@@ -331,6 +333,7 @@ extend-select = ["ARG",# flake8-bugbear"B",+ # Performance"PERF","ANN002", # missing-type-args"ANN003", # missing-type-kwargs@@ -386,7 +389,7 @@ unfixable = ["F401"]convention = "google"[tool.ruff.lint.per-file-ignores]-"**/{tests}/*" = ["ANN201", "ANN202", "T201", "D"]+"**/{tests}/*" = ["ANN201", "ANN202", "T201", "D", "F841"]"dagger/*" = ["TID252"][tool.ruff.lint.isort]diff --git a/tests/_output/test_md.py b/tests/_output/test_md.pyindex 552cf08f55..72c5d2293a 100644--- a/tests/_output/test_md.py+++ b/tests/_output/test_md.py@@ -69,7 +69,7 @@ def test_md_iconify() -> None:# Test multiple iconsmultiple_icons_input = "Icons: ::mdi:home:: ::fa:car:: ::lucide:settings::"- expected_output = '<span class="paragraph">Icons: <iconify-icon icon="mdi:home" inline=""></iconify-icon> <iconify-icon icon="fa:car" inline=""></iconify-icon> <iconify-icon icon="lucide:settings" inline=""></iconify-icon></span>' ## noqa: E501+ expected_output = '<span class="paragraph">Icons: <iconify-icon icon="mdi:home" inline=""></iconify-icon> <iconify-icon icon="fa:car" inline=""></iconify-icon> <iconify-icon icon="lucide:settings" inline=""></iconify-icon></span>' # noqa: E501assert (_md(multiple_icons_input, apply_markdown_class=False).text== expected_outputdiff --git a/tests/_output/test_try_format.py b/tests/_output/test_try_format.pyindex a52055c52e..e239d9487b 100644--- a/tests/_output/test_try_format.py+++ b/tests/_output/test_try_format.py@@ -160,9 +160,7 @@ def test_plain_object():result = try_format(obj)# Should fall back to string representation since we opted out of opinionated formatterassert is_html(result)- assert result.data.startswith(- "<pre style='font-size: 12px'><marimo._output.formatting.Plain object"- )+ assert result.data.startswith("<pre style='font-size: 12px'>Plain(")def test_opinionated_formatter():diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.pyindex 61615da1d3..521ab912e8 100644--- a/tests/_save/test_cache.py+++ b/tests/_save/test_cache.py@@ -75,7 +75,7 @@ class TestScriptCache:with persistent_cache(name="one",_loader=MockLoader(data={"X": 7, "Y": 8})- ) as cache: # noqa: E501+ ) as cache: # noqa: E501Y = 9X = 10# fmt: on@@ -114,8 +114,8 @@ class TestScriptCache:# fmt: offb = [2]if True:- with persistent_cache("if", _loader=_loader):- b = [+ with persistent_cache("if", _loader=_loader): # noqa: E111+ b = [ # noqa: E1117]# fmt: on@@ -222,7 +222,7 @@ class TestScriptCache:_loader = MockLoader()# fmt: off- with persistent_cache("else", _loader=_loader): call(False) # noqa: E701+ with persistent_cache("else", _loader=_loader): call(False) # noqa: E701# fmt: onwith pytest.raises(BlockException):diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex b82ed7f4ef..230f043319 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -477,9 +477,9 @@ def no_google_ai_config(config: UserConfigManager):class TestStreamResponse(unittest.TestCase):def simulate_stream(self, contents: List[str]) -> Any:+ @dataclassclass MockContent:- def __init__(self, content: str) -> None:- self.content = content+ content: strclass MockDelta:def __init__(self, content: str) -> None: