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: bump ruff, add more rules (#1115)
Myles Scolnicke9104a4bc7c8
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yamlindex 47b2313ed7..72c8edbf94 100644--- a/.github/workflows/test.yaml+++ b/.github/workflows/test.yaml@@ -134,7 +134,7 @@ jobs:elsesource marimo-dev-env/bin/activatefi- ruff marimo/+ ruff check marimo/- name: Typecheckif: ${{ matrix.python-version == '3.9' || matrix.python-version == '3.10' }}run: |diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 8f8247f913..570592f8e2 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -4,9 +4,9 @@ from __future__ import annotationsimport asyncioimport randomimport string-from collections.abc import Sequencefrom dataclasses import asdict, dataclassfrom typing import (+ TYPE_CHECKING,Any,Callable,Iterable,@@ -30,6 +30,9 @@ from marimo._output.rich_help import mddocfrom marimo._runtime import dataflowfrom marimo._runtime.patches import patch_main_module_context+if TYPE_CHECKING:+ from collections.abc import Sequence+LOGGER = _loggers.marimo_logger()diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex b1cec9aa23..c6252e457a 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -1,11 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import astimport dataclassesimport inspect-from collections.abc import Awaitable-from types import CodeTypefrom typing import TYPE_CHECKING, Any, Callable, Literal, Mapping, Optionalfrom marimo._ast.visitor import Name, VariableData@@ -14,6 +11,10 @@ from marimo._utils.deep_merge import deep_mergeCellId_t = strif TYPE_CHECKING:+ import ast+ from collections.abc import Awaitable+ from types import CodeType+from marimo._ast.app import InternalAppfrom marimo._output.hypertext import Htmldiff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex 4549fb70da..e468bcde28 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -6,8 +6,7 @@ import builtinsimport importlib.utilimport jsonimport os-from collections.abc import Sequence-from typing import Any, List, Optional, Union, cast+from typing import TYPE_CHECKING, Any, List, Optional, Union, castfrom marimo import __version__from marimo._ast.app import App, _AppConfig@@ -15,6 +14,9 @@ from marimo._ast.cell import CellConfig, CellImplfrom marimo._ast.compiler import compile_cellfrom marimo._ast.visitor import Name+if TYPE_CHECKING:+ from collections.abc import Sequence+INDENT = " "MAX_LINE_LENGTH = 80diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 240c217867..3ec4a84961 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -8,9 +8,8 @@ import reimport sysimport textwrapimport token as token_types-from collections.abc import Iteratorfrom tokenize import TokenInfo, tokenize-from typing import Any, Callable, Optional, Union+from typing import TYPE_CHECKING, Any, Callable, Optional, Unionfrom marimo._ast.cell import (Cell,@@ -20,6 +19,9 @@ from marimo._ast.cell import (from marimo._ast.visitor import ScopedVisitor, is_localfrom marimo._utils.tmpdir import get_tmpdir+if TYPE_CHECKING:+ from collections.abc import Iterator+def code_key(code: str) -> int:return hash(code)diff --git a/marimo/_config/utils.py b/marimo/_config/utils.pyindex 991e3d6adf..5b38a2184e 100644--- a/marimo/_config/utils.py+++ b/marimo/_config/utils.py@@ -92,7 +92,8 @@ def load_config() -> MarimoConfig:path = get_config_path()except OSError as e:path = None- LOGGER.warn("Encountered error when searching for config: %s", str(e))+ msg = "Encountered error when searching for config: %s"+ LOGGER.warning(msg, str(e))if path is not None:LOGGER.debug("Using config at %s", path)diff --git a/marimo/_loggers.py b/marimo/_loggers.pyindex ee2c09beac..750526aae5 100644--- a/marimo/_loggers.py+++ b/marimo/_loggers.py@@ -7,7 +7,7 @@ from typing import Optionalfrom marimo._utils.log_formatter import LogFormatter# Global log level for loggers-_LOG_LEVEL = logging.WARN+_LOG_LEVEL = logging.WARNING# Custom log formatter_LOG_FORMATTER = LogFormatter()@@ -16,7 +16,7 @@ _LOG_FORMATTER = LogFormatter()_LOGGERS: dict[str, logging.Logger] = {}-def set_level(level: str | int = logging.WARN) -> None:+def set_level(level: str | int = logging.WARNING) -> None:global _LOG_LEVELif isinstance(level, str):level = level.upper()@@ -25,7 +25,7 @@ def set_level(level: str | int = logging.WARN) -> None:elif level == "INFO":_LOG_LEVEL = logging.INFOelif level == "WARN":- _LOG_LEVEL = logging.WARN+ _LOG_LEVEL = logging.WARNINGelif level == "ERROR":_LOG_LEVEL = logging.ERRORelif level == "CRITICAL":@@ -35,7 +35,7 @@ def set_level(level: str | int = logging.WARN) -> None:elif level not in [logging.DEBUG,logging.INFO,- logging.WARN,+ logging.WARNING,logging.ERROR,logging.CRITICAL,]:diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.pyindex 9ad63400b5..39431b5fc3 100644--- a/marimo/_messaging/console_output_worker.py+++ b/marimo/_messaging/console_output_worker.py@@ -2,15 +2,15 @@from __future__ import annotationsimport time-from collections import dequefrom dataclasses import dataclass-from threading import Conditionfrom typing import TYPE_CHECKING, Literalfrom marimo._ast.cell import CellId_tfrom marimo._messaging.cell_output import CellChannel, CellOutputif TYPE_CHECKING:+ from collections import deque+ from threading import Conditionfrom typing import Optionalfrom marimo._messaging.types import Streamdiff --git a/marimo/_plugins/stateless/flex.py b/marimo/_plugins/stateless/flex.pyindex f0a65d16ac..b8d0ff283a 100644--- a/marimo/_plugins/stateless/flex.py+++ b/marimo/_plugins/stateless/flex.py@@ -1,8 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from collections.abc import Sequence-from typing import Literal, Optional+from typing import TYPE_CHECKING, Literal, Optionalfrom marimo._output.builder import hfrom marimo._output.formatting import as_html@@ -10,6 +9,9 @@ from marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._output.utils import create_style+if TYPE_CHECKING:+ from collections.abc import Sequence+def _flex(items: Sequence[object],diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pyindex bb7c27debf..1ff792e3d6 100644--- a/marimo/_plugins/stateless/mpl/_mpl.py+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -31,6 +31,8 @@ from marimo._utils.signals import get_signalsif TYPE_CHECKING:from starlette.applications import Starlette+ from starlette.requests import Request+ from starlette.websockets import WebSocketclass FigureManagers:@@ -73,11 +75,9 @@ def create_application(FigureManagerWebAgg,)from starlette.applications import Starlette- from starlette.requests import Requestfrom starlette.responses import HTMLResponse, Responsefrom starlette.routing import Mount, Route, WebSocketRoutefrom starlette.staticfiles import StaticFiles- from starlette.websockets import WebSocketasync def main_page(request: Request) -> HTMLResponse:figure_id = request.query_params.get("figure")diff --git a/marimo/_plugins/stateless/pdf.py b/marimo/_plugins/stateless/pdf.pyindex 8d6c7262d0..b06e81fc8a 100644--- a/marimo/_plugins/stateless/pdf.py+++ b/marimo/_plugins/stateless/pdf.py@@ -1,8 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import io-from typing import Any, Optional, Union+from typing import TYPE_CHECKING, Any, Optional, Unionimport marimo._output.data.data as mo_datafrom marimo._output.builder import h@@ -10,6 +9,9 @@ from marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._output.utils import create_style+if TYPE_CHECKING:+ import io+@mddocdef pdf(diff --git a/marimo/_plugins/stateless/status/_progress.py b/marimo/_plugins/stateless/status/_progress.pyindex efad09e267..fd98cfe3ed 100644--- a/marimo/_plugins/stateless/status/_progress.py+++ b/marimo/_plugins/stateless/status/_progress.py@@ -3,8 +3,7 @@ from __future__ import annotationsimport contextlibimport time-from collections.abc import Collection-from typing import Iterable, Iterator, Optional, TypeVar+from typing import TYPE_CHECKING, Iterable, Iterator, Optional, TypeVarimport marimo._runtime.output._output as outputfrom marimo._output.hypertext import Html@@ -12,6 +11,9 @@ from marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import build_stateless_pluginfrom marimo._utils.debounce import debounce+if TYPE_CHECKING:+ from collections.abc import Collection+S = TypeVar("S")T = TypeVar("T")diff --git a/marimo/_plugins/ui/_impl/batch.py b/marimo/_plugins/ui/_impl/batch.pyindex 3f2adc6487..500fe4ffe8 100644--- a/marimo/_plugins/ui/_impl/batch.py+++ b/marimo/_plugins/ui/_impl/batch.py@@ -6,15 +6,26 @@ import sysif sys.version_info < (3, 9):from typing import ItemsView, ValuesViewelse:- from collections.abc import ItemsView, ValuesView--from typing import Any, Callable, Dict, Final, Iterator, Optional+ pass++from typing import (+ TYPE_CHECKING,+ Any,+ Callable,+ Dict,+ Final,+ Iterator,+ Optional,+)from marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElement+if TYPE_CHECKING:+ from collections.abc import ItemsView, ValuesView+# - Frontend type is a dict {label => value update}# - Python type is a dict mapping label -> valuediff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex 08e8be706f..f6e84e3397 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -23,8 +23,7 @@ from typing import (from marimo import _loggersfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONType-from marimo._plugins.ui._core.ui_element import S as JSONTypeBound-from marimo._plugins.ui._core.ui_element import UIElement+from marimo._plugins.ui._core.ui_element import S as JSONTypeBound, UIElementfrom marimo._runtime.functions import FunctionLOGGER = _loggers.marimo_logger()diff --git a/marimo/_runtime/autoreload.py b/marimo/_runtime/autoreload.pyindex c56cdf5c3b..2e3f627c54 100644--- a/marimo/_runtime/autoreload.py+++ b/marimo/_runtime/autoreload.py@@ -130,10 +130,9 @@ class ModuleReloader:if py_filename in self.failed:del self.failed[py_filename]except Exception:+ msg = "[autoreload of {} failed: {}]"LOGGER.debug(- "[autoreload of {} failed: {}]".format(- modname, traceback.format_exc(10)- ),+ msg.format(modname, traceback.format_exc(10)),)self.failed[py_filename] = pymtimediff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/cell_runner.pyindex ab3eb837d4..97fd16d435 100644--- a/marimo/_runtime/cell_runner.py+++ b/marimo/_runtime/cell_runner.py@@ -7,7 +7,6 @@ import functoolsimport signalimport sysimport traceback-from collections.abc import Containerfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Iterator, Optional@@ -20,6 +19,8 @@ from marimo._runtime.marimo_pdb import MarimoPdbLOGGER = marimo_logger()if TYPE_CHECKING:+ from collections.abc import Container+from marimo._runtime.state import Statediff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.pyindex d6d91b878e..57c67ca8b3 100644--- a/marimo/_runtime/dataflow.py+++ b/marimo/_runtime/dataflow.py@@ -2,9 +2,8 @@from __future__ import annotationsimport threading-from collections.abc import Collectionfrom dataclasses import dataclass, field-from typing import Any, Optional, Tuple+from typing import TYPE_CHECKING, Any, Optional, Tuplefrom marimo import _loggersfrom marimo._ast.cell import (@@ -16,6 +15,9 @@ from marimo._ast.cell import (from marimo._ast.compiler import code_keyfrom marimo._ast.visitor import Name+if TYPE_CHECKING:+ from collections.abc import Collection+Edge = Tuple[CellId_t, CellId_t]LOGGER = _loggers.marimo_logger()diff --git a/marimo/_runtime/marimo_pdb.py b/marimo/_runtime/marimo_pdb.pyindex 43d37aa913..0b3ca5be85 100644--- a/marimo/_runtime/marimo_pdb.py+++ b/marimo/_runtime/marimo_pdb.py@@ -4,11 +4,14 @@ from __future__ import annotationsimport inspectimport sysfrom pdb import Pdb-from types import FrameType+from typing import TYPE_CHECKINGfrom marimo import _loggersfrom marimo._messaging.types import Stdin, Stdout+if TYPE_CHECKING:+ from types import FrameType+LOGGER = _loggers.marimo_logger()diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 659a07fb97..c2fbaf497e 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -13,9 +13,8 @@ import sysimport threadingimport timeimport traceback-from collections.abc import Iterable, Sequencefrom multiprocessing import connection-from typing import Any, Callable, Iterator, Optional+from typing import TYPE_CHECKING, Any, Callable, Iterator, Optionalfrom marimo import _loggersfrom marimo._ast.cell import CellConfig, CellId_t@@ -109,6 +108,9 @@ from marimo._utils.platform import is_pyodidefrom marimo._utils.signals import restore_signalsfrom marimo._utils.typed_connection import TypedConnection+if TYPE_CHECKING:+ from collections.abc import Iterable, Sequence+LOGGER = _loggers.marimo_logger()@@ -234,7 +236,6 @@ class Kernel:"""Kernel that manages the dependency graph and its execution.Args:-- cell_configs: initial configuration for each cell- app_metadata: metadata about the notebook- user_config: the initial user configurationdiff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.pyindex 6eb245fbc6..717774e429 100644--- a/marimo/_runtime/virtual_file.py+++ b/marimo/_runtime/virtual_file.py@@ -8,7 +8,6 @@ import randomimport stringimport sysimport threading-from collections.abc import Iterablefrom typing import TYPE_CHECKING, Optional, castfrom marimo import _loggers@@ -18,6 +17,8 @@ from marimo._runtime.cell_lifecycle_item import CellLifecycleItemfrom marimo._utils.platform import is_pyodideif TYPE_CHECKING:+ from collections.abc import Iterable+from marimo._runtime.context import RuntimeContextLOGGER = _loggers.marimo_logger()diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.pyindex 01ce815ac2..ef7c444637 100644--- a/marimo/_server/api/deps.py+++ b/marimo/_server/api/deps.py@@ -1,17 +1,18 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Optional, Union--from starlette.requests import Request-from starlette.websockets import WebSocket-from uvicorn import Server+from typing import TYPE_CHECKING, Optional, Unionfrom marimo._config.manager import UserConfigManagerfrom marimo._server.ids import SessionIdfrom marimo._server.model import SessionModefrom marimo._server.sessions import Session, SessionManager+if TYPE_CHECKING:+ from starlette.requests import Request+ from starlette.websockets import WebSocket+ from uvicorn import Server+def app_state(request: Request) -> AppState:"""Get the app state."""diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex 7e4c2c5d2b..7f4cfa9493 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -1,11 +1,10 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Generator, Optional+from typing import TYPE_CHECKING, Generator, Optionalfrom starlette.authentication import requiresfrom starlette.exceptions import HTTPException-from starlette.requests import Requestfrom starlette.responses import StreamingResponsefrom marimo import _loggers@@ -15,6 +14,9 @@ from marimo._server.api.utils import parse_requestfrom marimo._server.models.completion import AiCompletionRequestfrom marimo._server.router import APIRouter+if TYPE_CHECKING:+ from starlette.requests import Request+LOGGER = _loggers.marimo_logger()# Router for file aidiff --git a/marimo/_server/api/endpoints/config.py b/marimo/_server/api/endpoints/config.pyindex 7f235b6f50..4bb6652872 100644--- a/marimo/_server/api/endpoints/config.py+++ b/marimo/_server/api/endpoints/config.py@@ -1,8 +1,9 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from typing import TYPE_CHECKING+from starlette.authentication import requires-from starlette.requests import Requestfrom marimo import _loggersfrom marimo._runtime.requests import SetUserConfigRequest@@ -15,6 +16,9 @@ from marimo._server.models.models import ()from marimo._server.router import APIRouter+if TYPE_CHECKING:+ from starlette.requests import Request+LOGGER = _loggers.marimo_logger()# Router for config endpointsdiff --git a/marimo/_server/api/endpoints/documentation.py b/marimo/_server/api/endpoints/documentation.pyindex e9fab2a6a8..bac0e92f28 100644--- a/marimo/_server/api/endpoints/documentation.py+++ b/marimo/_server/api/endpoints/documentation.py@@ -1,12 +1,15 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from starlette.requests import Request+from typing import TYPE_CHECKINGfrom marimo import _loggersfrom marimo._server.router import APIRouterfrom marimo._snippets.snippets import Snippets, read_snippets+if TYPE_CHECKING:+ from starlette.requests import Request+LOGGER = _loggers.marimo_logger()# Router for documentationdiff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.pyindex 294d6ed50d..d31a269ae7 100644--- a/marimo/_server/api/endpoints/editing.py+++ b/marimo/_server/api/endpoints/editing.py@@ -1,8 +1,9 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from typing import TYPE_CHECKING+from starlette.authentication import requires-from starlette.requests import Requestfrom marimo._runtime.requests import (CompletionRequest,@@ -22,6 +23,9 @@ from marimo._server.models.models import (from marimo._server.router import APIRouterfrom marimo._utils.formatter import BlackFormatter+if TYPE_CHECKING:+ from starlette.requests import Request+# Router for editing endpointsrouter = APIRouter()diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.pyindex 403a33b90b..0d5acf9e8a 100644--- a/marimo/_server/api/endpoints/execution.py+++ b/marimo/_server/api/endpoints/execution.py@@ -1,8 +1,9 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from typing import TYPE_CHECKING+from starlette.authentication import requires-from starlette.requests import Requestfrom marimo import _loggersfrom marimo._runtime.requests import (@@ -21,6 +22,9 @@ from marimo._server.models.models import (from marimo._server.router import APIRouterfrom marimo._server.uvicorn_utils import close_uvicorn+if TYPE_CHECKING:+ from starlette.requests import Request+LOGGER = _loggers.marimo_logger()# Router for execution endpointsdiff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.pyindex d6b7363a8e..8aeb32225e 100644--- a/marimo/_server/api/endpoints/file_explorer.py+++ b/marimo/_server/api/endpoints/file_explorer.py@@ -2,9 +2,9 @@from __future__ import annotationsimport base64+from typing import TYPE_CHECKINGfrom starlette.authentication import requires-from starlette.requests import Requestfrom marimo import _loggersfrom marimo._server.api.utils import parse_request@@ -25,6 +25,9 @@ from marimo._server.models.files import ()from marimo._server.router import APIRouter+if TYPE_CHECKING:+ from starlette.requests import Request+LOGGER = _loggers.marimo_logger()# Router for file system endpointsdiff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.pyindex 16b04fd38c..727804c63e 100644--- a/marimo/_server/api/endpoints/files.py+++ b/marimo/_server/api/endpoints/files.py@@ -2,10 +2,10 @@from __future__ import annotationsimport os+from typing import TYPE_CHECKINGfrom starlette.authentication import requiresfrom starlette.exceptions import HTTPException-from starlette.requests import Requestfrom marimo import _loggersfrom marimo._ast import codegen@@ -23,6 +23,9 @@ from marimo._server.models.models import ()from marimo._server.router import APIRouter+if TYPE_CHECKING:+ from starlette.requests import Request+LOGGER = _loggers.marimo_logger()# Router for file endpointsdiff --git a/marimo/_server/api/endpoints/health.py b/marimo/_server/api/endpoints/health.pyindex 3d6049f25d..cc73ad84fc 100644--- a/marimo/_server/api/endpoints/health.py+++ b/marimo/_server/api/endpoints/health.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from starlette.requests import Request+from typing import TYPE_CHECKING+from starlette.responses import JSONResponsefrom marimo import __version__, _loggers@@ -9,6 +10,9 @@ from marimo._server.api.deps import AppStatefrom marimo._server.router import APIRouterfrom marimo._utils.health import get_node_version, get_required_modules_list+if TYPE_CHECKING:+ from starlette.requests import Request+LOGGER = _loggers.marimo_logger()# Router for health/status endpointsdiff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.pyindex 6551d055ad..861747a2b1 100644--- a/marimo/_server/api/endpoints/home.py+++ b/marimo/_server/api/endpoints/home.py@@ -2,10 +2,9 @@from __future__ import annotationsimport os-from typing import List+from typing import TYPE_CHECKING, Listfrom starlette.authentication import requires-from starlette.requests import Requestfrom marimo import _loggersfrom marimo._server.api.deps import AppState@@ -20,6 +19,9 @@ from marimo._server.models.home import (from marimo._server.router import APIRouterfrom marimo._utils.paths import pretty_path+if TYPE_CHECKING:+ from starlette.requests import Request+LOGGER = _loggers.marimo_logger()# Router for home endpointsdiff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.pyindex 23dadf7380..6c4c69255c 100644--- a/marimo/_server/api/lifespans.py+++ b/marimo/_server/api/lifespans.py@@ -9,8 +9,12 @@ import sysfrom marimo._server.sessions import SessionManagerif sys.version_info < (3, 9):- from typing import AsyncContextManager as AbstractAsyncContextManager- from typing import AsyncIterator, Callable, Sequence+ from typing import (+ AsyncContextManager as AbstractAsyncContextManager,+ AsyncIterator,+ Callable,+ Sequence,+ )else:from collections.abc import AsyncIterator, Callable, Sequencefrom contextlib import AbstractAsyncContextManagerdiff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex a5eef99fd7..18277bba65 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Optional+from typing import TYPE_CHECKING, Optionalfrom starlette.authentication import (AuthCredentials,@@ -11,10 +11,12 @@ from starlette.authentication import ()from starlette.requests import HTTPConnection, Requestfrom starlette.responses import JSONResponse-from starlette.types import ASGIApp, Receive, Scope, Sendfrom marimo._server.model import SessionMode+if TYPE_CHECKING:+ from starlette.types import ASGIApp, Receive, Scope, Send+class AuthBackend(AuthenticationBackend):async def authenticate(diff --git a/marimo/_server/api/utils.py b/marimo/_server/api/utils.pyindex 7866e3fa0b..727b9dc8c0 100644--- a/marimo/_server/api/utils.py+++ b/marimo/_server/api/utils.py@@ -6,12 +6,13 @@ import subprocessimport sysimport webbrowserfrom shutil import which-from typing import Optional, Type, TypeVar--from starlette.requests import Request+from typing import TYPE_CHECKING, Optional, Type, TypeVarfrom marimo._utils.parse_dataclass import parse_raw+if TYPE_CHECKING:+ from starlette.requests import Request+# TODO still needed?def require_header(header: list[str] | None) -> str:diff --git a/marimo/_server/router.py b/marimo/_server/router.pyindex aea9728a56..76a640ebcb 100644--- a/marimo/_server/router.py+++ b/marimo/_server/router.py@@ -5,9 +5,8 @@ import dataclassesimport jsonfrom asyncio import iscoroutinefrom dataclasses import dataclass-from typing import Any, Callable, Optional, TypeVar+from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar-from starlette.requests import Requestfrom starlette.responses import (FileResponse,JSONResponse,@@ -19,6 +18,9 @@ from starlette.routing import Mount, Routerfrom marimo import _loggersfrom marimo._server.models.base import deep_to_camel_case+if TYPE_CHECKING:+ from starlette.requests import Request+LOGGER = _loggers.marimo_logger()DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any])diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 0f1446cfd4..f06abf935d 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -538,7 +538,7 @@ class SessionManager:Doesn't start in run mode."""if self.mode == SessionMode.RUN:- LOGGER.warn("Cannot start LSP server in run mode")+ LOGGER.warning("Cannot start LSP server in run mode")returnalert = self.lsp_server.start()@@ -583,7 +583,7 @@ class SessionManager:# - what to do if the file is deleted, or is renamed# - do we re-run the app or just show the changed code# - we don't properly handle saving from the frontend- LOGGER.warn("Cannot start file watcher in edit mode")+ LOGGER.warning("Cannot start file watcher in edit mode")return Disposable.empty()file = self.file_router.maybe_get_single_file()if not file:diff --git a/marimo/_server/types.py b/marimo/_server/types.pyindex 79c7e7fedc..7e49020018 100644--- a/marimo/_server/types.py+++ b/marimo/_server/types.py@@ -1,9 +1,11 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import multiprocessing as mp-from queue import Queue-from typing import TypeVar, Union+from typing import TYPE_CHECKING, TypeVar, Union++if TYPE_CHECKING:+ import multiprocessing as mp+ from queue import QueueT = TypeVar("T")# strings for python 3.8 compatibilitydiff --git a/marimo/_smoke_tests/bugs/1072.py b/marimo/_smoke_tests/bugs/1072.pyindex 1e4212140d..f32fd198a2 100644--- a/marimo/_smoke_tests/bugs/1072.py+++ b/marimo/_smoke_tests/bugs/1072.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.3.9"diff --git a/marimo/_smoke_tests/bugs/1107.py b/marimo/_smoke_tests/bugs/1107.pyindex f3e657f2b3..c44505eed4 100644--- a/marimo/_smoke_tests/bugs/1107.py+++ b/marimo/_smoke_tests/bugs/1107.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.3.12"diff --git a/marimo/_utils/distributor.py b/marimo/_utils/distributor.pyindex 77ab5e2c1d..6cb4af8f40 100644--- a/marimo/_utils/distributor.py+++ b/marimo/_utils/distributor.py@@ -2,13 +2,15 @@from __future__ import annotationsimport asyncio-from threading import Thread-from typing import Callable, Generic, TypeVar+from typing import TYPE_CHECKING, Callable, Generic, TypeVarfrom marimo import _loggersfrom marimo._utils.disposable import Disposablefrom marimo._utils.typed_connection import TypedConnection+if TYPE_CHECKING:+ from threading import Thread+LOGGER = _loggers.marimo_logger()T = TypeVar("T")diff --git a/marimo/_utils/formatter.py b/marimo/_utils/formatter.pyindex fbb5e55a89..77b35cf111 100644--- a/marimo/_utils/formatter.py+++ b/marimo/_utils/formatter.py@@ -23,7 +23,7 @@ class BlackFormatter(Formatter):try:import blackexcept ModuleNotFoundError:- LOGGER.warn(+ LOGGER.warning("To enable code formatting, install black (pip install black)")return {}diff --git a/marimo/_utils/url.py b/marimo/_utils/url.pyindex 9439901c4b..b9ed13bc10 100644--- a/marimo/_utils/url.py+++ b/marimo/_utils/url.py@@ -26,7 +26,7 @@ regex = re.compile( # noqa: W605r"(?:172\.(?:1[6-9]|2\d|3[0-1])" + ip_middle_octet + ip_last_octet + r"))"r"|"# private & local hosts- r"(?P<private_host>" r"(?:localhost))" r"|"+ r"(?P<private_host>(?:localhost))|"# IP address dotted notation octets# excludes loopback network 0.0.0.0# excludes reserved space >= 224.0.0.0@@ -69,7 +69,7 @@ regex = re.compile( # noqa: W605r"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}"# 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33# (IPv4-Embedded IPv6 Address)- r"(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])" r")\]|"+ r"(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\]|"# host namer"(?:(?:(?:xn--[-]{0,2})|[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]-?)*"r"[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]+)"@@ -87,7 +87,7 @@ regex = re.compile( # noqa: W605# query stringr"(?:\?\S*)?"# fragment- r"(?:#\S*)?" r"$",+ r"(?:#\S*)?$",re.UNICODE | re.IGNORECASE,)diff --git a/pyproject.toml b/pyproject.tomlindex 14c90120ee..848eb6385c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -85,7 +85,7 @@ dev = ["pytest-codecov~=0.5.1","pytest-asyncio~=0.23.4","mypy~=1.7.0",- "ruff~=0.0.275",+ "ruff~=0.3.6","typos~=1.17.1",# For docs"pypandoc~=1.11",@@ -152,8 +152,32 @@ exclude = ["docs","build",]-ignore = []-select = [++[tool.ruff.lint]+ignore = [+ "G004", # Logging statement uses f-string+ "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"F",# pycodestyle@@ -172,13 +196,60 @@ select = ["FA102",# isort"I001",+ # Enable entire ruff rule section+ "ASYNC", # subset of flake8-async rules+ "ISC", # Checks for implicit literal string concatenation (auto-fixable)+ "TCH", # Rules around TYPE_CHECKING blocks+ "G", # flake8-logging-format rules+ "LOG", # flake8-logging rules, most of them autofixable+ "PT", # flake8-pytest-style rules+ "TID25", # flake8-tidy-imports rules+ # Per rule enables+ # "RUF100", # Unused noqa (auto-fixable)+ # We ignore more pydocstyle than we enable, so be more selective at what we enable+ # "D101", # Missing docstring in public class+ "D106",+ # "D2",+ "D3",+ # "D400", # First line should end with a period+ # "D401", # First line of docstring should be in imperative mood+ "D402",+ "D403",+ "D412",+ "D419",+ "PGH004", # Use specific rule codes when using noqa+ "PGH005", # Invalid unittest.mock.Mock methods/attributes/properties+ # "S101", # Checks use `assert` outside the test cases, test cases should be added into the exclusions+ "B004", # Checks for use of hasattr(x, "__call__") and replaces it with callable(x)+ "B006", # Checks for uses of mutable objects as function argument defaults.+ "B017", # Checks for pytest.raises context managers that catch Exception or BaseException.+ "B019", # Use of functools.lru_cache or functools.cache on methods can lead to memory leaks+ "TRY002", # Prohibit use of `raise Exception`, use specific exceptions instead.]# Never try to fix `F401` (unused imports).unfixable = ["F401"]-[tool.ruff.isort]+[tool.ruff.lint.isort]required-imports = ["from __future__ import annotations"]+combine-as-imports = true++[tool.ruff.lint.flake8-type-checking]+exempt-modules = ["typing", "typing_extensions"]++[tool.ruff.format]+docstring-code-format = true++[tool.ruff.lint.flake8-tidy-imports]+# Disallow all relative imports.+ban-relative-imports = "all"+# Ban certain modules from being imported at module level, instead requiring+# that they're imported lazily (e.g., within a function definition).+banned-module-level-imports = ["numpy", "pandas"]++[tool.ruff.lint.flake8-pytest-style]+mark-parentheses = false+fixture-parentheses = false[tool.black]line-length = 79diff --git a/scripts/pycheck.sh b/scripts/pycheck.shindex e50a15afd6..5b11bb1427 100755--- a/scripts/pycheck.sh+++ b/scripts/pycheck.sh@@ -1,6 +1,6 @@#!/bin/shecho "[check: lint]"-ruff marimo/+ruff check marimo/echo "[check: typecheck]"mypy marimo/diff --git a/scripts/pyfix.sh b/scripts/pyfix.shindex 5dba8976fe..af8b9c8b6c 100755--- a/scripts/pyfix.sh+++ b/scripts/pyfix.sh@@ -3,8 +3,8 @@echo "[fix: copyright]"./scripts/pycopyright.shecho "[fix: ruff]"-ruff marimo/ --fix-ruff tests/ --fix+ruff check marimo/ --fix+ruff check tests/ --fixecho "[fix: black]"black marimo/black tests/diff --git a/tests/_ast/test_compiler.py b/tests/_ast/test_compiler.pyindex 2ae9700519..ee883a17ff 100644--- a/tests/_ast/test_compiler.py+++ b/tests/_ast/test_compiler.py@@ -78,7 +78,7 @@ class TestParseCell:class TestCellFactory:@staticmethoddef test_defs() -> None:- """defs inferred from function code, not returns"""+ """Defs inferred from function code, not returns"""def f() -> None:x = 10 # noqa: F841@@ -90,7 +90,7 @@ class TestCellFactory:@staticmethoddef test_refs() -> None:- """refs inferred from function code, not args"""+ """Refs inferred from function code, not args"""def f() -> None:x = y # noqa: F841 F821diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.pyindex c0f8d85952..7432d21db0 100644--- a/tests/_ast/test_visitor.py+++ b/tests/_ast/test_visitor.py@@ -34,7 +34,7 @@ def test_multiple_assign() -> None:def test_assign_multiple_statements() -> None:- code = "x = 0\n" "y = 0"+ code = "x = 0\ny = 0"v = visitor.ScopedVisitor()mod = ast.parse(code)v.visit(mod)diff --git a/tests/_cli/test_envinfo.py b/tests/_cli/test_envinfo.pyindex 1da24332e0..06231b3987 100644--- a/tests/_cli/test_envinfo.py+++ b/tests/_cli/test_envinfo.py@@ -21,10 +21,8 @@ def test_get_package_versions() -> None:assert isinstance(package_versions, dict)assert "click" in package_versionsassert "starlette" in package_versions- assert (- "pymdown-extensions" in package_versions- and package_versions["pymdown-extensions"] != "missing"- )+ assert "pymdown-extensions" in package_versions+ assert package_versions["pymdown-extensions"] != "missing"def test_get_system_info() -> None:diff --git a/tests/_cli/test_ipynb_to_marimo.py b/tests/_cli/test_ipynb_to_marimo.pyindex b011c141e9..fbb96131e9 100644--- a/tests/_cli/test_ipynb_to_marimo.py+++ b/tests/_cli/test_ipynb_to_marimo.py@@ -4,11 +4,14 @@ from __future__ import annotationsimport osimport tempfileimport textwrap-from collections.abc import Sequence+from typing import TYPE_CHECKINGfrom marimo._ast import codegenfrom marimo._cli.ipynb_to_marimo import convert_from_path+if TYPE_CHECKING:+ from collections.abc import Sequence+DIR_PATH = os.path.dirname(os.path.realpath(__file__))diff --git a/tests/_plugins/stateless/status/test_progress.py b/tests/_plugins/stateless/status/test_progress.pyindex 255d40e781..42111b24d1 100644--- a/tests/_plugins/stateless/status/test_progress.py+++ b/tests/_plugins/stateless/status/test_progress.py@@ -52,9 +52,11 @@ def test_update_progress(_mock_flush: Any) -> None:assert progress.title == "Updated"assert progress.subtitle == "Still Running"rate = progress._get_rate()- assert rate is not None and rate > 0.0+ assert rate is not None+ assert rate > 0.0eta = progress._get_eta()- assert eta is not None and eta > 0.0+ assert eta is not None+ assert eta > 0.0# Test update_progress without argumentsdiff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.pyindex 13cda3c38d..68207d7ccb 100644--- a/tests/_plugins/ui/_impl/tables/test_default_table.py+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py@@ -20,19 +20,19 @@ class TestDefaultTable(unittest.TestCase):{"A": 1, "B": "a"},{"A": 3, "B": "c"},]- self.assertEqual(selected_manager.data, expected_data)+ assert selected_manager.data == expected_datadef test_select_rows_empty(self) -> None:selected_manager = self.manager.select_rows([])- self.assertEqual(selected_manager.data, [])+ assert selected_manager.data == []def test_get_row_headers(self) -> None:expected_headers = []- self.assertEqual(self.manager.get_row_headers(), expected_headers)+ assert self.manager.get_row_headers() == expected_headersdef test_is_type(self) -> None:- self.assertTrue(self.manager.is_type(self.data))- self.assertFalse(self.manager.is_type("not a dataframe"))+ assert self.manager.is_type(self.data)+ assert not self.manager.is_type("not a dataframe")class TestColumnarDefaultTable(unittest.TestCase):@@ -50,22 +50,16 @@ class TestColumnarDefaultTable(unittest.TestCase):"A": [1, 3],"B": ["a", "c"],}- self.assertEqual(selected_manager.data, expected_data)+ assert selected_manager.data == expected_datadef test_select_rows_empty(self) -> None:selected_manager = self.manager.select_rows([])- self.assertEqual(- selected_manager.data,- {- "A": [],- "B": [],- },- )+ assert selected_manager.data == {"A": [], "B": []}def test_get_row_headers(self) -> None:expected_headers = []- self.assertEqual(self.manager.get_row_headers(), expected_headers)+ assert self.manager.get_row_headers() == expected_headersdef test_is_type(self) -> None:- self.assertTrue(self.manager.is_type(self.data))- self.assertFalse(self.manager.is_type("not a dataframe"))+ assert self.manager.is_type(self.data)+ assert not self.manager.is_type("not a dataframe")diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.pyindex 11c4f545f4..a11fdb9624 100644--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py@@ -20,15 +20,15 @@ class TestPandasTableManager(unittest.TestCase):self.manager = self.factory.create()(self.data)def test_package_name(self) -> None:- self.assertEqual(self.factory.package_name(), "pandas")+ assert self.factory.package_name() == "pandas"def test_to_csv(self) -> None:expected_csv = self.data.to_csv(index=False).encode("utf-8")- self.assertEqual(self.manager.to_csv(), expected_csv)+ assert self.manager.to_csv() == expected_csvdef test_to_json(self) -> None:expected_json = self.data.to_json(orient="records").encode("utf-8")- self.assertEqual(self.manager.to_json(), expected_json)+ assert self.manager.to_json() == expected_jsondef test_select_rows(self) -> None:import pandas as pd@@ -40,12 +40,12 @@ class TestPandasTableManager(unittest.TestCase):def test_select_rows_empty(self) -> None:selected_manager = self.manager.select_rows([])- self.assertEqual(selected_manager.data.shape, (0, 2))+ assert selected_manager.data.shape == (0, 2)def test_get_row_headers(self) -> None:expected_headers = []- self.assertEqual(self.manager.get_row_headers(), expected_headers)+ assert self.manager.get_row_headers() == expected_headersdef test_is_type(self) -> None:- self.assertTrue(self.manager.is_type(self.data))- self.assertFalse(self.manager.is_type("not a dataframe"))+ assert self.manager.is_type(self.data)+ assert not self.manager.is_type("not a dataframe")diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.pyindex 94fdb34f0f..0d3733c9c5 100644--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py@@ -20,13 +20,13 @@ class TestPolarsTableManagerFactory(unittest.TestCase):self.manager = self.factory.create()(self.data)def test_package_name(self) -> None:- self.assertEqual(self.factory.package_name(), "polars")+ assert self.factory.package_name() == "polars"def test_to_csv(self) -> None:- self.assertIsInstance(self.manager.to_csv(), bytes)+ assert isinstance(self.manager.to_csv(), bytes)def test_to_json(self) -> None:- self.assertIsInstance(self.manager.to_json(), bytes)+ assert isinstance(self.manager.to_json(), bytes)def test_select_rows(self) -> None:indices = [0, 2]@@ -41,8 +41,8 @@ class TestPolarsTableManagerFactory(unittest.TestCase):def test_get_row_headers(self) -> None:expected_headers = []- self.assertEqual(self.manager.get_row_headers(), expected_headers)+ assert self.manager.get_row_headers() == expected_headersdef test_is_type(self) -> None:- self.assertTrue(self.manager.is_type(self.data))- self.assertFalse(self.manager.is_type("not a dataframe"))+ assert self.manager.is_type(self.data)+ assert not self.manager.is_type("not a dataframe")diff --git a/tests/_plugins/ui/_impl/tables/test_pyarrow.py b/tests/_plugins/ui/_impl/tables/test_pyarrow.pyindex 7af6d0f738..3675daaa39 100644--- a/tests/_plugins/ui/_impl/tables/test_pyarrow.py+++ b/tests/_plugins/ui/_impl/tables/test_pyarrow.py@@ -20,13 +20,13 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):self.manager = self.factory.create()(self.data)def test_package_name(self) -> None:- self.assertEqual(self.factory.package_name(), "pyarrow")+ assert self.factory.package_name() == "pyarrow"def test_to_csv(self) -> None:- self.assertIsInstance(self.manager.to_csv(), bytes)+ assert isinstance(self.manager.to_csv(), bytes)def test_to_json(self) -> None:- self.assertIsInstance(self.manager.to_json(), bytes)+ assert isinstance(self.manager.to_json(), bytes)def test_select_rows(self) -> None:indices = [0, 2]@@ -40,8 +40,8 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):def test_get_row_headers(self) -> None:expected_headers = []- self.assertEqual(self.manager.get_row_headers(), expected_headers)+ assert self.manager.get_row_headers() == expected_headersdef test_is_type(self) -> None:- self.assertTrue(self.manager.is_type(self.data))- self.assertFalse(self.manager.is_type("not a dataframe"))+ assert self.manager.is_type(self.data)+ assert not self.manager.is_type("not a dataframe")diff --git a/tests/_plugins/ui/_impl/test_array.py b/tests/_plugins/ui/_impl/test_array.pyindex 178b8f3d2b..157adebe8f 100644--- a/tests/_plugins/ui/_impl/test_array.py+++ b/tests/_plugins/ui/_impl/test_array.py@@ -73,7 +73,8 @@ def test_update_checks_against_frontend_value() -> None:array = ui.array([ui.dropdown({"option": v})])# smoke test: don't check against backend value, which will raisearray._update({"0": ["option"]})- assert len(array.value) == 1 and isinstance(array.value[0], NoEquality)+ assert len(array.value) == 1+ assert isinstance(array.value[0], NoEquality)def test_container_emulation() -> None:diff --git a/tests/_plugins/ui/_impl/test_input.py b/tests/_plugins/ui/_impl/test_input.pyindex e927210ef6..4b8364d17d 100644--- a/tests/_plugins/ui/_impl/test_input.py+++ b/tests/_plugins/ui/_impl/test_input.py@@ -56,13 +56,16 @@ def test_slider_init() -> None:assert slider.start == 1assert slider.stop == 10assert slider.step is None- assert slider.value == 5 and isinstance(slider.value, int)+ assert slider.value == 5+ assert isinstance(slider.value, int)slider = ui.slider(1, 10, value=5.0)- assert slider.value == 5.0 and isinstance(slider.value, float)+ assert slider.value == 5.0+ assert isinstance(slider.value, float)slider._update(6)- assert slider.value == 6.0 and isinstance(slider.value, float)+ assert slider.value == 6.0+ assert isinstance(slider.value, float)def test_slider_invalid_bounds() -> None:diff --git a/tests/_runtime/test_validate_graph.py b/tests/_runtime/test_validate_graph.pyindex 1fdd084532..e73a10bd2e 100644--- a/tests/_runtime/test_validate_graph.py+++ b/tests/_runtime/test_validate_graph.py@@ -121,13 +121,12 @@ def test_cycle_and_multiple_def() -> None:)edges = cycle_error.edgesassert len(edges) == 2- assert ("0", "1") in edges and ("1", "0") in edges+ assert ("0", "1") in edges+ assert ("1", "0") in edgesmultiple_definition_error = cast(MultipleDefinitionError,t[0] if isinstance(t[0], MultipleDefinitionError) else t[1],)- assert (- multiple_definition_error.name == "z"- and multiple_definition_error.cells == (str((int(cell) + 1) % 2),)- )+ assert multiple_definition_error.name == "z"+ assert multiple_definition_error.cells == (str((int(cell) + 1) % 2),)diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex d7eb4b6d50..e80295438c 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -201,9 +201,8 @@ def test_save_file_cannot_rename(client: TestClient) -> None:},)assert response.value.status_code == 400- assert (- response.value.detail and "cannot rename" in response.value.detail- )+ assert response.value.detail+ assert "cannot rename" in response.value.detail@with_session(SESSION_ID)diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pyindex d94b7fe72e..6d17af489d 100644--- a/tests/_server/api/endpoints/test_resume_session.py+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -1,15 +1,16 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Optional--from starlette.testclient import TestClient+from typing import TYPE_CHECKING, Any, Optionalfrom marimo._messaging.ops import KernelReadyfrom marimo._server.sessions import Sessionfrom marimo._utils.parse_dataclass import parse_rawfrom tests._server.conftest import get_session_manager+if TYPE_CHECKING:+ from starlette.testclient import TestClient+def create_response(partial_response: dict[str, Any],diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 875e5542ad..b481a05be3 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -2,10 +2,9 @@from __future__ import annotationsfrom pathlib import Path-from typing import Any, Optional+from typing import TYPE_CHECKING, Any, Optionalimport pytest-from starlette.testclient import TestClientfrom starlette.websockets import WebSocketDisconnectfrom marimo._messaging.ops import KernelReady@@ -14,6 +13,9 @@ from marimo._server.sessions import SessionManagerfrom marimo._utils.parse_dataclass import parse_rawfrom tests._server.conftest import get_session_manager+if TYPE_CHECKING:+ from starlette.testclient import TestClient+def create_response(partial_response: dict[str, Any],diff --git a/tests/_server/conftest.py b/tests/_server/conftest.pyindex b6b1ed2609..2badfe5d25 100644--- a/tests/_server/conftest.py+++ b/tests/_server/conftest.py@@ -16,8 +16,9 @@ app = create_starlette_app(base_url="")@pytest.fixture(scope="session", autouse=True)-def init() -> None:+def init() -> bool:initialize_asyncio()+ return True@pytest.fixture(scope="module")@@ -26,7 +27,7 @@ def client_with_lifespans() -> Generator[TestClient, None, None]:yield c[email protected](scope="function")def client() -> Iterator[TestClient]:main = sys.modules["__main__"]app.state.session_manager = get_mock_session_manager()diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.pyindex 283ccf61df..2618ed8886 100644--- a/tests/_server/files/test_os_file_system.py+++ b/tests/_server/files/test_os_file_system.py@@ -2,6 +2,8 @@ import osimport unittestfrom tempfile import TemporaryDirectory+import pytest+from marimo._server.files.os_file_system import OSFileSystemfrom marimo._server.models.files import FileDetailsResponse@@ -47,11 +49,11 @@ class TestOSFileSystem(unittest.TestCase):assert os.path.isdir(expected_path)def test_create_with_empty_name(self):- with self.assertRaises(ValueError):+ with pytest.raises(ValueError):self.fs.create_file_or_directory(self.test_dir, "file", "", None)def test_create_with_disallowed_name(self):- with self.assertRaises(ValueError):+ with pytest.raises(ValueError):self.fs.create_file_or_directory(self.test_dir, "file", ".", None)def test_list_files(self):@@ -142,7 +144,7 @@ class TestOSFileSystem(unittest.TestCase):new_path = os.path.join(self.test_dir, new_file_name)with open(original_path, "w"):pass- with self.assertRaises(ValueError):+ with pytest.raises(ValueError):self.fs.move_file_or_directory(original_path, new_path)def test_update_file(self):diff --git a/tests/conftest.py b/tests/conftest.pyindex 4243bb0bcc..366c7d37b9 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -179,5 +179,5 @@ class ExecReqProvider:# fixture that provides an ExecReqProvider@pytest.fixture-def exec_req() -> Generator[ExecReqProvider, None, None]:- yield ExecReqProvider()+def exec_req() -> ExecReqProvider:+ return ExecReqProvider()