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: enable more ruff rules (#1121)

Myles Scolnick9b2cb0e54b06
diff --git a/marimo/_cli/upgrade.py b/marimo/_cli/upgrade.py
index 29ae0df92f..b0b0a4c373 100644
--- a/marimo/_cli/upgrade.py
+++ b/marimo/_cli/upgrade.py
@@ -9,6 +9,7 @@ from packaging import version
from marimo import __version__ as current_version
from marimo._cli.print import green, orange
+from marimo._server.api.status import HTTPException
from marimo._utils.config.config import ConfigReader
@@ -90,11 +91,13 @@ def _update_with_latest_version(state: MarimoCLIState) -> MarimoCLIState:
def _fetch_data_from_url(url: str) -> Dict[str, Any]:
with urllib.request.urlopen(url) as response:
- if response.status == 200:
+ status = response.status
+ if status == 200:
data = response.read()
encoding = response.info().get_content_charset("utf-8")
return json.loads(data.decode(encoding)) # type: ignore
else:
- raise Exception(
- f"HTTP request failed with status code {response.status}"
+ raise HTTPException(
+ status_code=status,
+ detail=f"HTTP request failed with status code {status}",
)
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 02d9d492f5..a2ae90aea1 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -5,6 +5,8 @@ import inspect
import sys
from typing import TYPE_CHECKING, Any, Callable, Dict, Final, List, Optional
+from marimo._plugins.ui._impl.dataframes.handlers import TransformsContainer
+from marimo._plugins.ui._impl.dataframes.transforms import Transformations
from marimo._plugins.ui._impl.tables.pandas_table import (
PandasTableManagerFactory,
)
@@ -20,9 +22,6 @@ from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.functions import EmptyArgs, Function
from marimo._utils.parse_dataclass import parse_raw
-from .handlers import TransformsContainer
-from .transforms import Transformations
-
@dataclass
class GetDataFrameResponse:
@@ -43,6 +42,18 @@ class GetColumnValuesResponse:
too_many_values: bool
+class ColumnNotFound(Exception):
+ def __init__(self, column: str):
+ self.column = column
+ super().__init__(f"Column {column} does not exist")
+
+
+class GetDataFrameError(Exception):
+ def __init__(self, error: str):
+ self.error = error
+ super().__init__(error)
+
+
@mddoc
class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
"""
@@ -131,7 +142,7 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
LIMIT = 100
if self._error is not None:
- raise Exception(self._error)
+ raise GetDataFrameError(self._error)
manager = PandasTableManagerFactory.create()(self._value.head(LIMIT))
url = mo_data.csv(manager.to_csv()).url
@@ -150,7 +161,7 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
LIMIT = 500
if args.column not in self._data.columns:
- raise Exception("Column %s does not exist" % args.column)
+ ColumnNotFound(args.column)
# We get the unique values from the original dataframe, not the
# transformed one
diff --git a/marimo/_plugins/ui/_impl/dataframes/handlers.py b/marimo/_plugins/ui/_impl/dataframes/handlers.py
index ca7ae78404..bebff7c739 100644
--- a/marimo/_plugins/ui/_impl/dataframes/handlers.py
+++ b/marimo/_plugins/ui/_impl/dataframes/handlers.py
@@ -1,7 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from typing import TYPE_CHECKING, Any, List, NoReturn, cast
-from .transforms import (
+from marimo._plugins.ui._impl.dataframes.transforms import (
AggregateTransform,
ColumnConversionTransform,
FilterRowsTransform,
diff --git a/marimo/_runtime/packages/conda_package_manager.py b/marimo/_runtime/packages/conda_package_manager.py
index 12f41a72ca..0ededdfdac 100644
--- a/marimo/_runtime/packages/conda_package_manager.py
+++ b/marimo/_runtime/packages/conda_package_manager.py
@@ -1,8 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import subprocess
-
from marimo._runtime.packages.module_name_to_conda_name import (
module_name_to_conda_name,
)
@@ -20,4 +18,4 @@ class PixiPackageManager(CondaPackageManager):
name = "pixi"
async def install(self, package: str) -> bool:
- return subprocess.run(["pixi", "add", package]).returncode == 0
+ return self.run(["pixi", "add", package])
diff --git a/marimo/_runtime/packages/package_manager.py b/marimo/_runtime/packages/package_manager.py
index 800dfe9a44..73c211c290 100644
--- a/marimo/_runtime/packages/package_manager.py
+++ b/marimo/_runtime/packages/package_manager.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import abc
import shutil
+import subprocess
class PackageManager(abc.ABC):
@@ -32,6 +33,10 @@ class PackageManager(abc.ABC):
"""
...
+ def run(self, command: list[str]) -> bool:
+ proc = subprocess.run(command) # noqa: ASYNC101
+ return proc.returncode == 0
+
class CanonicalizingPackageManager(PackageManager):
"""Base class for package managers.
diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.py
index 1e5f785994..5056484570 100644
--- a/marimo/_runtime/packages/pypi_package_manager.py
+++ b/marimo/_runtime/packages/pypi_package_manager.py
@@ -1,8 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import subprocess
-
from marimo._runtime.packages.module_name_to_pypi_name import (
module_name_to_pypi_name,
)
@@ -21,7 +19,7 @@ class PipPackageManager(PypiPackageManager):
name = "pip"
async def install(self, package: str) -> bool:
- return subprocess.run(["pip", "install", package]).returncode == 0
+ return self.run(["pip", "install", package])
class MicropipPackageManager(PypiPackageManager):
@@ -45,20 +43,18 @@ class UvPackageManager(PypiPackageManager):
name = "uv"
async def install(self, package: str) -> bool:
- return (
- subprocess.run(["uv", "pip", "install", package]).returncode == 0
- )
+ return self.run(["uv", "pip", "install", package])
class RyePackageManager(PypiPackageManager):
name = "rye"
async def install(self, package: str) -> bool:
- return subprocess.run(["rye", "add", package]).returncode == 0
+ return self.run(["rye", "add", package])
class PoetryPackageManager(PypiPackageManager):
name = "poetry"
async def install(self, package: str) -> bool:
- return subprocess.run(["poetry", "add", package]).returncode == 0
+ return self.run(["poetry", "add", package])
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index 5b4599c51c..66b040e78f 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -47,7 +47,7 @@ async def index(request: Request) -> HTMLResponse:
or app_state.session_manager.file_router.get_unique_file_key()
)
- with open(index_html, "r") as f:
+ with open(index_html, "r") as f: # noqa: ASYNC101
html = f.read()
# Shared configuration
diff --git a/marimo/_server/exceptions.py b/marimo/_server/exceptions.py
new file mode 100644
index 0000000000..96dff37a7c
--- /dev/null
+++ b/marimo/_server/exceptions.py
@@ -0,0 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
+class InvalidSessionException(Exception):
+ def __init__(self, message: str) -> None:
+ super().__init__(message)
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 71c3335392..754dd00642 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -42,6 +42,7 @@ from marimo._runtime.requests import (
SerializedQueryParams,
SetUIElementValueRequest,
)
+from marimo._server.exceptions import InvalidSessionException
from marimo._server.file_manager import (
AppFileManager,
)
@@ -500,7 +501,9 @@ class SessionManager:
if len(sessions_with_the_same_file) == 0:
return None
if len(sessions_with_the_same_file) > 1:
- raise Exception("Only one session should exist while editing")
+ raise InvalidSessionException(
+ "Only one session should exist while editing"
+ )
(session_id, session) = next(iter(sessions_with_the_same_file.items()))
connection_state = session.connection_state()
diff --git a/pyproject.toml b/pyproject.toml
index eec8689fa6..e2daf9f45c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -159,23 +159,7 @@ ignore = [
"TCH001", # Move application import into a type-checking block
"D301", # Use r""" if any backslashes in a docstring
# TODO: we should fix these, and enable this rule
- "TRY002", # Create your own exception
- # TODO: we should fix these, and enable this rule
- "TID252", # Prefer absolute imports over relative imports
- # TODO: we should fix these, and enable this rule
- "ISC003", # Explicitly concatenated string should be implicitly concatenated
- # TODO: we should fix these, and enable this rule
- "ASYNC101", # Async functions should not call `open`, `time.sleep`, or `subprocess` methods
- # TODO: we should fix these, and enable this rule
- "PGH004", # Use specific rule codes when using `noqa`
- # TODO: we should fix these, and enable this rule
"PT011", # `pytest.raises(ValueError)` is too broad, set the `match` parameter or use a more specific exception
- # TODO: we should fix these, and enable this rule
- "PT019", # Fixture without value is injected as parameter, use `@pytest.mark.usefixtures` instead
- # TODO: we should fix these, and enable this rule
- "PT017", # Found assertion on exception `e` in `except` block, use `pytest.raises()` instead
- # TODO: we should fix these, and enable this rule
- "PT012", # `pytest.raises()` block should contain a single simple statement
]
extend-select = [
# pyflakes
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index 618830f829..fcc2d34970 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -83,11 +83,11 @@ class TestApp:
@app.cell
def one():
- x = y # noqa
+ x = y # noqa: F841, F821
@app.cell
def two():
- y = x # noqa
+ y = x # noqa: F841, F821
with pytest.raises(CycleError):
app.run()
@@ -115,11 +115,11 @@ class TestApp:
@app.cell
def one():
- x = 0 # noqa
+ x = 0 # noqa: F841
@app.cell
def two():
- x = 0 # noqa
+ x = 0 # noqa: F841
with pytest.raises(MultipleDefinitionError):
app.run()
@@ -130,11 +130,11 @@ class TestApp:
@app.cell
def one():
- x = 0 # noqa
+ x = 0 # noqa: F841
@app.cell
def two():
- del x # noqa
+ del x # noqa: F841, F821
with pytest.raises(DeleteNonlocalError):
app.run()
diff --git a/tests/_plugins/stateless/status/test_progress.py b/tests/_plugins/stateless/status/test_progress.py
index 42111b24d1..3fd6c46f8a 100644
--- a/tests/_plugins/stateless/status/test_progress.py
+++ b/tests/_plugins/stateless/status/test_progress.py
@@ -35,7 +35,7 @@ def test_progress_init() -> None:
# Test update_progress method
@patch("marimo._runtime.output._output.flush")
-def test_update_progress(_mock_flush: Any) -> None:
+def test_update_progress(mock_flush: Any) -> None:
progress = _Progress(
title="Test",
subtitle="Running",
@@ -57,11 +57,13 @@ def test_update_progress(_mock_flush: Any) -> None:
eta = progress._get_eta()
assert eta is not None
assert eta > 0.0
+ mock_flush.assert_called_once()
# Test update_progress without arguments
@patch("marimo._runtime.output._output.flush")
-def test_update_progress_no_args(_mock_flush: Any) -> None:
+def test_update_progress_no_args(mock_flush: Any) -> None:
+ del mock_flush
progress = _Progress(
title="Test",
subtitle="Running",
@@ -83,7 +85,7 @@ def test_update_progress_no_args(_mock_flush: Any) -> None:
# Test update_progress with closed progress
@patch("marimo._runtime.output._output.flush")
-def test_update_progress_closed(_mock_flush: Any) -> None:
+def test_update_progress_closed(mock_flush: Any) -> None:
progress = _Progress(
title="Test",
subtitle="Running",
@@ -95,3 +97,4 @@ def test_update_progress_closed(_mock_flush: Any) -> None:
assert progress.closed is True
with pytest.raises(RuntimeError):
progress.update_progress()
+ mock_flush.assert_called_once()
diff --git a/tests/_plugins/stateless/test_image.py b/tests/_plugins/stateless/test_image.py
index c185755c57..5aa56919a1 100644
--- a/tests/_plugins/stateless/test_image.py
+++ b/tests/_plugins/stateless/test_image.py
@@ -111,7 +111,7 @@ async def test_image_numpy(k: Kernel, exec_req: ExecReqProvider) -> None:
async def test_image_local_file(k: Kernel, exec_req: ExecReqProvider) -> None:
# Just opens a file that exists, and make sure it gets registered
# in the virtual path registry
- with open(__file__, encoding="utf-8") as f:
+ with open(__file__, encoding="utf-8") as f: # noqa: ASYNC101
await k.run(
[
exec_req.get(
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index 0a0855af21..675923509e 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -3,6 +3,8 @@ from __future__ import annotations
from typing import Any
+import pytest
+
from marimo._plugins.ui._impl.tables.default_table import DefaultTableManager
from marimo._plugins.ui._impl.utils.dataframe import TableData
from marimo._runtime.runtime import Kernel
@@ -76,18 +78,15 @@ def test_normalize_data(executing_kernel: Kernel) -> None:
# Test with invalid data type
data2: Any = "invalid data type"
- try:
+ with pytest.raises(ValueError) as e:
_normalize_data(data2)
- except ValueError as e:
- assert str(e) == "data must be a list or tuple or a dict of lists."
+ assert str(e.value) == "data must be a list or tuple or a dict of lists."
# Test with invalid data structure
data3: Any = [set([1, 2, 3])]
- try:
+ with pytest.raises(ValueError) as e:
_normalize_data(data3)
- except ValueError as e:
- assert (
- str(e)
- == "data must be a sequence of JSON-serializable types, or a "
- + "sequence of dicts."
- )
+ assert (
+ str(e.value) == "data must be a sequence of JSON-serializable types, "
+ "or a sequence of dicts."
+ )
diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.py
index e80295438c..ee3eeb6fe4 100644
--- a/tests/_server/api/endpoints/test_files.py
+++ b/tests/_server/api/endpoints/test_files.py
@@ -200,9 +200,9 @@ def test_save_file_cannot_rename(client: TestClient) -> None:
],
},
)
- assert response.value.status_code == 400
- assert response.value.detail
- assert "cannot rename" in response.value.detail
+ assert response.value.status_code == 400
+ assert response.value.detail
+ assert "cannot rename" in response.value.detail
@with_session(SESSION_ID)
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index b481a05be3..b6de33f0bf 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -119,7 +119,7 @@ def test_fails_on_multiple_connections_with_other_sessions(
with client.websocket_connect("/ws?session_id=123") as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data)
- with pytest.raises(WebSocketDisconnect) as exc_info:
+ with pytest.raises(WebSocketDisconnect) as exc_info: # noqa: PT012
with client.websocket_connect(
"/ws?session_id=456"
) as other_websocket:
@@ -139,7 +139,7 @@ def test_fails_on_multiple_connections_with_same_file(
with client.websocket_connect(ws_1) as websocket:
data = websocket.receive_json()
assert_parse_ready_response(data)
- with pytest.raises(WebSocketDisconnect) as exc_info:
+ with pytest.raises(WebSocketDisconnect) as exc_info: # noqa: PT012
with client.websocket_connect(ws_2) as other_websocket:
other_websocket.receive_json()
raise AssertionError()
@@ -158,7 +158,7 @@ async def test_file_watcher_calls_reload(client: TestClient) -> None:
unsubscribe = session_manager.start_file_watcher()
filename = session_manager.file_router.get_unique_file_key()
assert filename
- with open(filename, "a") as f:
+ with open(filename, "a") as f: # noqa: ASYNC101
f.write("\n# test")
f.close()
assert session_manager.watcher
diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.py
index d9dcd6b646..10d8181ef4 100644
--- a/tests/_server/test_file_manager.py
+++ b/tests/_server/test_file_manager.py
@@ -63,7 +63,7 @@ def test_rename_to_existing_filename(app_file_manager: AppFileManager) -> None:
with open(existing_filename, "w") as f:
f.write("This is a test file.")
try:
- with pytest.raises(HTTPException) as e:
+ with pytest.raises(HTTPException) as e: # noqa: PT012
app_file_manager.rename(existing_filename)
assert e.value == HTTPStatus.BAD_REQUEST
finally:
@@ -86,7 +86,7 @@ def test_successful_rename(app_file_manager: AppFileManager) -> None:
def test_rename_exception(app_file_manager: AppFileManager) -> None:
new_filename = "/invalid/path/new_filename.py"
- with pytest.raises(HTTPException) as e:
+ with pytest.raises(HTTPException) as e: # noqa: PT012
app_file_manager.rename(new_filename)
assert e.value.status_code == HTTPStatus.SERVER_ERROR
@@ -116,7 +116,7 @@ def test_save_app_config_valid(app_file_manager: AppFileManager) -> None:
def test_save_app_config_exception(app_file_manager: AppFileManager) -> None:
app_file_manager.filename = "/invalid/path/app_config.py"
- with pytest.raises(HTTPException) as e:
+ with pytest.raises(HTTPException) as e: # noqa: PT012
app_file_manager.save_app_config({})
assert e.value.status_code == HTTPStatus.SERVER_ERROR
@@ -126,7 +126,7 @@ def test_save_filename_change_not_allowed(
) -> None:
app_file_manager.filename = "original.py"
save_request.filename = "new.py"
- with pytest.raises(HTTPException) as e:
+ with pytest.raises(HTTPException) as e: # noqa: PT012
app_file_manager.save(save_request)
assert e.value.status_code == HTTPStatus.BAD_REQUEST
@@ -137,7 +137,7 @@ def test_save_existing_filename(app_file_manager: AppFileManager) -> None:
f.write("This is a test file.")
save_request.filename = existing_filename
try:
- with pytest.raises(HTTPException) as e:
+ with pytest.raises(HTTPException) as e: # noqa: PT012
app_file_manager.save(save_request)
assert e.value.status_code == HTTPStatus.BAD_REQUEST
finally:
@@ -155,10 +155,9 @@ def test_save_successful(app_file_manager: AppFileManager) -> None:
def test_save_cannot_rename(app_file_manager: AppFileManager) -> None:
save_request.filename = "/invalid/path/save_exception.py"
- try:
+ with pytest.raises(HTTPException) as e:
app_file_manager.save(save_request)
- except HTTPException as e:
- assert e.status_code == HTTPStatus.BAD_REQUEST
+ assert e.value.status_code == HTTPStatus.BAD_REQUEST
def test_read_valid_filename(app_file_manager: AppFileManager) -> None:
@@ -177,7 +176,7 @@ def test_read_unnamed_notebook(app_file_manager: AppFileManager) -> None:
app_file_manager.filename = None
with pytest.raises(HTTPException) as e:
app_file_manager.read_file()
- assert e.value.status_code == HTTPStatus.BAD_REQUEST
+ assert e.value.status_code == HTTPStatus.BAD_REQUEST
def test_read_layout(app_file_manager: AppFileManager) -> None:
diff --git a/tests/_server/test_utils.py b/tests/_server/test_utils.py
index 3ab1f5a07c..b551c43f9a 100644
--- a/tests/_server/test_utils.py
+++ b/tests/_server/test_utils.py
@@ -1,4 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
+import pytest
+
from marimo._server.api.utils import parse_title, require_header
@@ -9,21 +11,18 @@ def test_require_header() -> None:
require_header(header) == "Content-Type"
), "The function should return the single header value"
- try:
+ with pytest.raises(ValueError) as e:
require_header(None)
- raise AssertionError()
- except ValueError as e:
- assert str(e) == "Expected exactly one value in header, got None"
+ assert str(e.value) == "Expected exactly one value in header, got None"
# Test case 3: ValueError is raised when an empty list is passed as the
# header
- try:
+ with pytest.raises(ValueError) as e:
require_header([])
- raise AssertionError()
- except ValueError as e:
- assert (
- str(e) == "Expected exactly one value in header, got 0 values: []"
- )
+ assert (
+ str(e.value)
+ == "Expected exactly one value in header, got 0 values: []"
+ )
# The function to be tested
diff --git a/tests/_utils/test_file_watcher.py b/tests/_utils/test_file_watcher.py
index 78e4e562a8..bebfed91f3 100644
--- a/tests/_utils/test_file_watcher.py
+++ b/tests/_utils/test_file_watcher.py
@@ -29,7 +29,7 @@ async def test_polling_file_watcher():
# Wait a bit and then modify the file
await asyncio.sleep(0.2)
- with open(tmp_path, "w") as f:
+ with open(tmp_path, "w") as f: # noqa: ASYNC101
f.write("modification")
# Wait for the watcher to detect the change
diff --git a/tests/_utils/test_parse_dataclass.py b/tests/_utils/test_parse_dataclass.py
index af70ecebb5..8c549c6e84 100644
--- a/tests/_utils/test_parse_dataclass.py
+++ b/tests/_utils/test_parse_dataclass.py
@@ -171,7 +171,7 @@ class TestParseRaw:
# handle error
with pytest.raises(ValueError) as e:
parsed = parse_raw(serialize({"config": "invalid"}), Nested)
- assert "invalid" in str(e.value)
+ assert "invalid" in str(e.value)
def test_enums(self) -> None:
@dataclass
@@ -187,7 +187,7 @@ class TestParseRaw:
# handle error
with pytest.raises(ValueError) as e:
parsed = parse_raw(serialize({"config": "invalid"}), Nested)
- assert "invalid" in str(e.value)
+ assert "invalid" in str(e.value)
def test_discriminated_union(self) -> None:
@dataclass
@@ -210,7 +210,7 @@ class TestParseRaw:
parsed = parse_raw(
serialize({"config": {"invalid": True}}), Nested
)
- assert "invalid" in str(e.value)
+ assert "invalid" in str(e.value)
def test_build_optional(self) -> None:
@dataclass