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: ruff UP rules (#3911)
Myles Scolnick451981485d4c
diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revsnew file mode 100644index 0000000000..b92e372a44--- /dev/null+++ b/.git-blame-ignore-revs@@ -0,0 +1 @@+# Adding ruff UP rulesdiff --git a/build_hook.py b/build_hook.pyindex c4279a65bc..9e1475a8ff 100644--- a/build_hook.py+++ b/build_hook.py@@ -2,13 +2,13 @@ from __future__ import annotationsimport osimport subprocess-from typing import Any, Dict+from typing import Anyfrom hatchling.builders.hooks.plugin.interface import BuildHookInterfaceclass FrontendBuildHook(BuildHookInterface[Any]):- def initialize(self, version: str, build_data: Dict[str, Any]) -> None:+ def initialize(self, version: str, build_data: dict[str, Any]) -> None:# Only build frontend if MARIMO_BUILD_FRONTEND variable existsMARIMO_BUILD_FRONTEND = os.getenv("MARIMO_BUILD_FRONTEND")if not MARIMO_BUILD_FRONTEND:diff --git a/marimo/_ai/_convert.py b/marimo/_ai/_convert.pyindex 0ed2211d01..d07a778e2c 100644--- a/marimo/_ai/_convert.py+++ b/marimo/_ai/_convert.py@@ -2,15 +2,15 @@from __future__ import annotationsimport base64-from typing import Any, Dict, List, TypedDict+from typing import Any, TypedDictfrom marimo._ai._types import ChatMessagedef convert_to_openai_messages(- messages: List[ChatMessage],-) -> List[Dict[Any, Any]]:- openai_messages: List[Dict[Any, Any]] = []+ messages: list[ChatMessage],+) -> list[dict[Any, Any]]:+ openai_messages: list[dict[Any, Any]] = []for message in messages:if not message.attachments:@@ -20,7 +20,7 @@ def convert_to_openai_messages(continue# Handle attachments- parts: List[Dict[Any, Any]] = []+ parts: list[dict[Any, Any]] = []parts.append({"type": "text", "text": message.content})for attachment in message.attachments:content_type = attachment.content_type or "text/plain"@@ -45,9 +45,9 @@ def convert_to_openai_messages(def convert_to_anthropic_messages(- messages: List[ChatMessage],-) -> List[Dict[Any, Any]]:- anthropic_messages: List[Dict[Any, Any]] = []+ messages: list[ChatMessage],+) -> list[dict[Any, Any]]:+ anthropic_messages: list[dict[Any, Any]] = []for message in messages:if not message.attachments:@@ -57,7 +57,7 @@ def convert_to_anthropic_messages(continue# Handle attachments- parts: List[Dict[Any, Any]] = []+ parts: list[dict[Any, Any]] = []parts.append({"type": "text", "text": message.content})for attachment in message.attachments:content_type = attachment.content_type or "text/plain"@@ -87,9 +87,9 @@ def convert_to_anthropic_messages(def convert_to_groq_messages(- messages: List[ChatMessage],-) -> List[Dict[Any, Any]]:- groq_messages: List[Dict[Any, Any]] = []+ messages: list[ChatMessage],+) -> list[dict[Any, Any]]:+ groq_messages: list[dict[Any, Any]] = []for message in messages:# Currently only supports text content (Llava is deprecated now)@@ -125,12 +125,12 @@ class BlobDict(TypedDict):def convert_to_google_messages(- messages: List[ChatMessage],-) -> List[Dict[Any, Any]]:- google_messages: List[Dict[Any, Any]] = []+ messages: list[ChatMessage],+) -> list[dict[Any, Any]]:+ google_messages: list[dict[Any, Any]] = []for message in messages:- parts: List[str | BlobDict] = [str(message.content)]+ parts: list[str | BlobDict] = [str(message.content)]if message.attachments:for attachment in message.attachments:content_type = attachment.content_type or "text/plain"diff --git a/marimo/_ai/_types.py b/marimo/_ai/_types.pyindex d825f52441..f977141266 100644--- a/marimo/_ai/_types.py+++ b/marimo/_ai/_types.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport abcimport mimetypesfrom dataclasses import dataclass-from typing import List, Literal, Optional, TypedDict+from typing import Literal, Optional, TypedDictclass ChatAttachmentDict(TypedDict):@@ -16,7 +16,7 @@ class ChatAttachmentDict(TypedDict):class ChatMessageDict(TypedDict):role: Literal["user", "assistant", "system"]content: str- attachments: Optional[List[ChatAttachmentDict]]+ attachments: Optional[list[ChatAttachmentDict]]class ChatModelConfigDict(TypedDict, total=False):@@ -63,7 +63,7 @@ class ChatMessage:content: object# Optional attachments to the message.- attachments: Optional[List[ChatAttachment]] = None+ attachments: Optional[list[ChatAttachment]] = None@dataclass@@ -79,6 +79,6 @@ class ChatModelConfig:class ChatModel(abc.ABC):@abc.abstractmethoddef __call__(- self, messages: List[ChatMessage], config: ChatModelConfig+ self, messages: list[ChatMessage], config: ChatModelConfig) -> object:passdiff --git a/marimo/_ai/llm/_impl.py b/marimo/_ai/llm/_impl.pyindex a3b4eeb5c0..70d411a58a 100644--- a/marimo/_ai/llm/_impl.py+++ b/marimo/_ai/llm/_impl.py@@ -2,7 +2,7 @@from __future__ import annotationsimport os-from typing import Callable, List, Optional, cast+from typing import Callable, Optional, castfrom marimo._ai._convert import (convert_to_anthropic_messages,@@ -37,7 +37,7 @@ class simple(ChatModel):self.delegate = delegatedef __call__(- self, messages: List[ChatMessage], config: ChatModelConfig+ self, messages: list[ChatMessage], config: ChatModelConfig) -> object:del configprompt = str(messages[-1].content)@@ -99,7 +99,7 @@ class openai(ChatModel):)def __call__(- self, messages: List[ChatMessage], config: ChatModelConfig+ self, messages: list[ChatMessage], config: ChatModelConfig) -> object:DependencyManager.openai.require("chat model requires openai. `pip install openai`"@@ -142,7 +142,7 @@ class openai(ChatModel):)response = client.chat.completions.create(model=self.model,- messages=cast(List[ChatCompletionMessageParam], openai_messages),+ messages=cast(list[ChatCompletionMessageParam], openai_messages),max_tokens=config.max_tokens,temperature=config.temperature,top_p=config.top_p,@@ -213,7 +213,7 @@ class anthropic(ChatModel):)def __call__(- self, messages: List[ChatMessage], config: ChatModelConfig+ self, messages: list[ChatMessage], config: ChatModelConfig) -> object:DependencyManager.anthropic.require("chat model requires anthropic. `pip install anthropic`"@@ -236,7 +236,7 @@ class anthropic(ChatModel):model=self.model,system=self.system_message,max_tokens=config.max_tokens or 1000,- messages=cast(List[MessageParam], anthropic_messages),+ messages=cast(list[MessageParam], anthropic_messages),top_p=config.top_p if config.top_p is not None else NOT_GIVEN,top_k=config.top_k if config.top_k is not None else NOT_GIVEN,stream=False,@@ -307,7 +307,7 @@ class google(ChatModel):)def __call__(- self, messages: List[ChatMessage], config: ChatModelConfig+ self, messages: list[ChatMessage], config: ChatModelConfig) -> object:DependencyManager.google_ai.require("chat model requires google. `pip install google-generativeai`"@@ -390,7 +390,7 @@ class groq(ChatModel):)def __call__(- self, messages: List[ChatMessage], config: ChatModelConfig+ self, messages: list[ChatMessage], config: ChatModelConfig) -> object:DependencyManager.groq.require("chat model requires groq. `pip install groq`"diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 7ed6b9fa47..2ae82bb2e7 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -6,6 +6,7 @@ import base64import inspectimport sysimport threading+from collections.abc import Iterable, Iterator, Mappingfrom dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom textwrap import dedent@@ -13,11 +14,7 @@ from typing import (TYPE_CHECKING,Any,Callable,- Iterable,- Iterator,- List,Literal,- Mapping,Optional,TypeVar,Union,@@ -33,6 +30,8 @@ if sys.version_info < (3, 10):else:from typing import ParamSpec, TypeAlias+from collections.abc import Sequence # noqa: TC003+from marimo import _loggersfrom marimo._ast.cell import Cell, CellConfig, CellImplfrom marimo._ast.cell_manager import CellManager@@ -94,7 +93,7 @@ class _AppConfig:html_head_file: Optional[str] = None# Whether to automatically download the app as HTML and Markdown- auto_download: List[Literal["html", "markdown"]] = field(+ auto_download: list[Literal["html", "markdown"]] = field(default_factory=list)diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 266b4cf8c4..01ea148ecf 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -5,8 +5,8 @@ import astimport dataclassesimport inspectimport os-from collections.abc import Awaitable-from typing import TYPE_CHECKING, Any, Literal, Mapping, Optional+from collections.abc import Awaitable, Mapping+from typing import TYPE_CHECKING, Any, Literal, Optionalfrom marimo._ast.sql_visitor import SQLVisitorfrom marimo._ast.visitor import ImportData, Language, Name, VariableDatadiff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex b0d5bc58ce..d3e5d4ea2a 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -8,7 +8,6 @@ import sysfrom typing import (TYPE_CHECKING,Callable,- Iterable,Optional,TypeVar,)@@ -26,6 +25,8 @@ from marimo._ast.pytest import process_for_pytestfrom marimo._types.ids import CellId_tif TYPE_CHECKING:+ from collections.abc import Iterable+from marimo._ast.app import InternalAppP = ParamSpec("P")diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex d9edfe0774..4c03ebd0a6 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -8,7 +8,7 @@ import jsonimport osimport reimport textwrap-from typing import Any, List, Literal, Optional, cast+from typing import Any, Literal, Optional, castfrom marimo import __version__from marimo._ast.app import App, _AppConfig@@ -352,7 +352,7 @@ def generate_filecontents()assert all(isinstance(d, str) for d in definitions)- cell_blocks: List[str] = cast(List[str], definitions)+ cell_blocks: list[str] = cast(list[str], definitions)if not toplevel_fn:return _classic_export(cell_blocks, header_comments, config)@@ -402,7 +402,7 @@ def get_app(filename: Optional[str]) -> Optional[App]:if filename is None:return None- with open(filename, "r", encoding="utf-8") as f:+ with open(filename, encoding="utf-8") as f:contents = f.read().strip()if not contents:@@ -442,7 +442,7 @@ def get_app(filename: Optional[str]) -> Optional[App]:def recover(filename: str) -> str:"""Generate a module for code recovered from a disconnected frontend"""- with open(filename, "r", encoding="utf-8") as f:+ with open(filename, encoding="utf-8") as f:contents = f.read()cells = json.loads(contents)["cells"]codes, names, configs = tuple(@@ -458,9 +458,9 @@ def recover(filename: str) -> str:))return generate_filecontents(- cast(List[str], codes),- cast(List[str], names),- cast(List[CellConfig], configs),+ cast(list[str], codes),+ cast(list[str], names),+ cast(list[CellConfig], configs),)@@ -484,7 +484,7 @@ def get_header_comments(filename: str) -> Optional[str]:if not os.path.exists(filename):return None- with open(filename, "r", encoding="utf-8") as f:+ with open(filename, encoding="utf-8") as f:contents = f.read()if "import marimo" not in contents:diff --git a/marimo/_ast/pytest.py b/marimo/_ast/pytest.pyindex 4d3c65c5c2..84b5683717 100644--- a/marimo/_ast/pytest.py+++ b/marimo/_ast/pytest.py@@ -7,10 +7,13 @@ import functoolsimport inspectimport itertoolsfrom pathlib import Path-from typing import Any, Awaitable, Callable, Mapping, NoReturn, TypeVar, cast+from typing import TYPE_CHECKING, Any, Callable, NoReturn, TypeVar, castfrom marimo._ast.cell import Cell+if TYPE_CHECKING:+ from collections.abc import Awaitable, Mapping+Fn = TypeVar("Fn", bound=Callable[..., Any])@@ -168,10 +171,8 @@ def build_test_class(def fails(*args: Any, **kwargs: Any) -> NoReturn:del args, kwargsraise ValueError(- (- f"Could not find test {var}, please report to"- "marimo-team/marimo/issues."- )+ f"Could not find test {var}, please report to"+ "marimo-team/marimo/issues.")return fails@@ -203,11 +204,9 @@ def build_test_class(def fails(*args: Any, **kwargs: Any) -> NoReturn:del args, kwargsraise ValueError(- (- f"Failed to evaluate decorator for {var}."- "Consider adjusting the test to enable "- "static analysis."- )+ f"Failed to evaluate decorator for {var}."+ "Consider adjusting the test to enable "+ "static analysis.") from efunctools.wraps(stub_fn)(fails)@@ -233,10 +232,8 @@ def build_test_class(return build_test_class(test.body, _run, file, var, defs, True)raise ValueError(- (- "Improperly compiled as a test. Please report to"- "marimo-team/marimo/issues."- )+ "Improperly compiled as a test. Please report to"+ "marimo-team/marimo/issues.")return type(name, (MarimoTest,), {var: hook(var) for var in defs})diff --git a/marimo/_ast/sql_visitor.py b/marimo/_ast/sql_visitor.pyindex 0c5f58368f..027cc6dd6b 100644--- a/marimo/_ast/sql_visitor.py+++ b/marimo/_ast/sql_visitor.py@@ -5,7 +5,7 @@ import astimport refrom dataclasses import dataclass, fieldfrom textwrap import dedent-from typing import Any, List, Optional+from typing import Any, Optionalfrom marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager@@ -217,7 +217,7 @@ def find_sql_defs(sql_statement: str) -> SQLDefs:# - catalog.table (this is shorthand for catalog.main.table)# - table- parts: List[str] = []+ parts: list[str] = []while i < len(tokens):part = token_extractor.strip_quotes(token_extractor.token_str(i)diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex 91f4b439d1..074d55a08f 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -6,7 +6,7 @@ import itertoolsimport sysfrom collections import defaultdictfrom dataclasses import dataclass, field-from typing import Callable, Literal, Optional, Set, Union+from typing import Callable, Literal, Optional, Unionfrom uuid import uuid4from marimo import _loggers@@ -490,7 +490,7 @@ class ScopedVisitor(ast.NodeVisitor):return nodefor statement in statements:- tables: Set[str] = set()+ tables: set[str] = set()from_targets: list[str] = []# Parse the refs and defs of each statementtry:diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex ba272e8b5a..390383cc0e 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -44,7 +44,7 @@ def helpful_usage_error(self: Any, file: Any = None) -> None:file = click.get_text_stream("stderr")color = Noneclick.echo(- red("Error") + ": %s\n" % self.format_message(),+ red("Error") + f": {self.format_message()}\n",file=file,color=color,)diff --git a/marimo/_cli/convert/utils.py b/marimo/_cli/convert/utils.pyindex 9ca802f597..abbc631e5d 100644--- a/marimo/_cli/convert/utils.py+++ b/marimo/_cli/convert/utils.py@@ -15,7 +15,7 @@ def load_external_file(file_path: str, ext: str) -> str:.decode("utf-8"))else:- with open(file_path, "r", encoding="utf-8") as f:+ with open(file_path, encoding="utf-8") as f:notebook = f.read()return notebookdiff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 3fca5565bc..1c5b291116 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -5,7 +5,7 @@ import astimport osimport subprocessimport sys-from typing import TYPE_CHECKING, Any, Dict+from typing import TYPE_CHECKING, Anyimport click@@ -183,10 +183,10 @@ def _generate_server_api_schema() -> dict[str, Any]:requests.StopRequest,]- processed_classes: Dict[Any, str] = {+ processed_classes: dict[Any, str] = {JSONType: "JSONType",}- component_schemas: Dict[str, Any] = {+ component_schemas: dict[str, Any] = {# Hand-written schema to avoid circular dependencies"JSONType": {"oneOf": [@@ -202,7 +202,7 @@ def _generate_server_api_schema() -> dict[str, Any]:}# We must override the names of some Union Types,# otherwise, their __name__ is "Union"- name_overrides: Dict[Any, str] = {+ name_overrides: dict[Any, str] = {JSONType: "JSONType",errors.Error: "Error",KnownMimeType: "MimeType",@@ -278,7 +278,7 @@ def ps() -> None:pass-def get_marimo_processes() -> list["psutil.Process"]:+def get_marimo_processes() -> list[psutil.Process]:import psutildef is_marimo_process(proc: psutil.Process) -> bool:@@ -390,7 +390,7 @@ def inline_packages(name: str) -> None:package_names = module_name_to_pypi_name()def get_pypi_package_names() -> list[str]:- with open(name, "r") as file:+ with open(name) as file:tree = ast.parse(file.read(), filename=name)imported_modules = set[str]()diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.pyindex f46c43d3c9..1973c83ba2 100644--- a/marimo/_cli/file_path.py+++ b/marimo/_cli/file_path.py@@ -8,7 +8,7 @@ import pathlibimport urllib.parseimport urllib.requestfrom tempfile import TemporaryDirectory-from typing import Optional, Tuple+from typing import Optionalfrom urllib.error import HTTPErrorfrom marimo import _loggers@@ -45,7 +45,7 @@ class FileReader(abc.ABC):pass@abc.abstractmethod- def read(self, name: str) -> Tuple[str, str]:+ def read(self, name: str) -> tuple[str, str]:"""Read the file and return its content and filename."""pass@@ -54,11 +54,11 @@ class LocalFileReader(FileReader):def can_read(self, name: str) -> bool:return not is_url(name)- def read(self, name: str) -> Tuple[str, str]:+ def read(self, name: str) -> tuple[str, str]:# Is directoryif os.path.isdir(name):return "", os.path.basename(name)- with open(name, "r", encoding="utf-8") as f:+ with open(name, encoding="utf-8") as f:content = f.read()return content, os.path.basename(name)@@ -69,7 +69,7 @@ class GitHubIssueReader(FileReader):"https://github.com/marimo-team/marimo/issues/")- def read(self, name: str) -> Tuple[str, str]:+ def read(self, name: str) -> tuple[str, str]:issue_number = name.split("/")[-1]api_url = f"https://api.github.com/repos/marimo-team/marimo/issues/{issue_number}"issue_response = urllib.request.urlopen(api_url).read().decode("utf-8")@@ -92,7 +92,7 @@ class StaticNotebookReader(FileReader):def can_read(self, name: str) -> bool:return self._is_static_marimo_notebook_url(name)[0]- def read(self, name: str) -> Tuple[str, str]:+ def read(self, name: str) -> tuple[str, str]:_, file_contents = self._is_static_marimo_notebook_url(name)code = self._extract_code_from_static_notebook(file_contents)filename = self._extract_filename_from_static_notebook(file_contents)@@ -150,7 +150,7 @@ class GitHubSourceReader(FileReader):def can_read(self, name: str) -> bool:return is_github_src(name, ext=".py") or is_github_src(name, ext=".md")- def read(self, name: str) -> Tuple[str, str]:+ def read(self, name: str) -> tuple[str, str]:url = get_github_src_url(name)content = urllib.request.urlopen(url).read().decode("utf-8")return content, os.path.basename(url)@@ -160,7 +160,7 @@ class GenericURLReader(FileReader):def can_read(self, name: str) -> bool:return is_url(name)- def read(self, name: str) -> Tuple[str, str]:+ def read(self, name: str) -> tuple[str, str]:content = urllib.request.urlopen(name).read().decode("utf-8")# Remove query parameters from the URLurl_without_query = name.split("?")[0]@@ -177,7 +177,7 @@ class FileContentReader:GenericURLReader(),]- def read_file(self, name: str) -> Tuple[str, str]:+ def read_file(self, name: str) -> tuple[str, str]:"""Read the file and return its content and filename@@ -204,7 +204,7 @@ class FileHandler(abc.ABC):@abc.abstractmethoddef handle(self, name: str, temp_dir: TemporaryDirectory[str]- ) -> Tuple[str, Optional[TemporaryDirectory[str]]]:+ ) -> tuple[str, Optional[TemporaryDirectory[str]]]:pass@@ -218,7 +218,7 @@ class LocalFileHandler(FileHandler):def handle(self, name: str, temp_dir: TemporaryDirectory[str]- ) -> Tuple[str, Optional[TemporaryDirectory[str]]]:+ ) -> tuple[str, Optional[TemporaryDirectory[str]]]:del temp_dirimport click@@ -264,7 +264,7 @@ class RemoteFileHandler(FileHandler):def handle(self, name: str, temp_dir: TemporaryDirectory[str]- ) -> Tuple[str, Optional[TemporaryDirectory[str]]]:+ ) -> tuple[str, Optional[TemporaryDirectory[str]]]:try:content, filename = self.reader.read_file(name)except HTTPError as e:@@ -293,7 +293,7 @@ class RemoteFileHandler(FileHandler):def validate_name(name: str, allow_new_file: bool, allow_directory: bool-) -> Tuple[str, Optional[TemporaryDirectory[str]]]:+) -> tuple[str, Optional[TemporaryDirectory[str]]]:"""Validate the file name and return the path to the file.diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex 4f892171c8..8d54abb6e9 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -29,11 +29,11 @@ class PyProjectReader:self.project = project@staticmethod- def from_filename(name: str) -> "PyProjectReader":+ def from_filename(name: str) -> PyProjectReader:return PyProjectReader(_get_pyproject_from_filename(name) or {})@staticmethod- def from_script(script: str) -> "PyProjectReader":+ def from_script(script: str) -> PyProjectReader:return PyProjectReader(read_pyproject_from_script(script) or {})@propertydiff --git a/marimo/_cli/upgrade.py b/marimo/_cli/upgrade.pyindex f1f7cf3eb4..ce737db816 100644--- a/marimo/_cli/upgrade.py+++ b/marimo/_cli/upgrade.py@@ -7,7 +7,7 @@ import urllib.errorimport urllib.requestfrom dataclasses import dataclassfrom datetime import datetime-from typing import Any, Callable, Dict, Optional+from typing import Any, Callable, Optionalfrom marimo import __version__ as current_version, _loggersfrom marimo._cli.print import echo, green, orange@@ -114,7 +114,7 @@ def _update_with_latest_version(state: MarimoCLIState) -> MarimoCLIState:return state-def _fetch_data_from_url(url: str) -> Dict[str, Any]:+def _fetch_data_from_url(url: str) -> dict[str, Any]:try:with urllib.request.urlopen(url, timeout=FETCH_TIMEOUT) as response:status = response.statusdiff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 879f39f2fb..013fc441d6 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -15,8 +15,6 @@ else:from typing import (Any,- Dict,- List,Literal,Optional,TypedDict,@@ -77,7 +75,7 @@ class KeymapConfig(TypedDict):"""preset: Literal["default", "vim"]- overrides: NotRequired[Dict[str, str]]+ overrides: NotRequired[dict[str, str]]OnCellChangeType = Literal["lazy", "autorun"]@@ -255,7 +253,7 @@ class SnippetsConfig(TypedDict):- `custom_path`: the path to the custom snippets directory"""- custom_paths: NotRequired[List[str]]+ custom_paths: NotRequired[list[str]]include_default_snippets: NotRequired[bool]@@ -273,7 +271,7 @@ class MarimoConfig(TypedDict):server: ServerConfigpackage_management: PackageManagementConfigai: NotRequired[AiConfig]- experimental: NotRequired[Dict[str, Any]]+ experimental: NotRequired[dict[str, Any]]snippets: NotRequired[SnippetsConfig]@@ -291,7 +289,7 @@ class PartialMarimoConfig(TypedDict, total=False):server: ServerConfigpackage_management: PackageManagementConfigai: NotRequired[AiConfig]- experimental: NotRequired[Dict[str, Any]]+ experimental: NotRequired[dict[str, Any]]snippets: SnippetsConfig@@ -356,7 +354,7 @@ def merge_config(merged = cast(MarimoConfig,deep_merge(- cast(Dict[Any, Any], config), cast(Dict[Any, Any], new_config)+ cast(dict[Any, Any], config), cast(dict[Any, Any], new_config)),)diff --git a/marimo/_config/secrets.py b/marimo/_config/secrets.pyindex 2fae03f564..2a7163a0a4 100644--- a/marimo/_config/secrets.py+++ b/marimo/_config/secrets.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Dict, TypeVar, cast+from typing import Any, TypeVar, castfrom marimo._config.config import MarimoConfig, PartialMarimoConfigfrom marimo._config.utils import deep_copy@@ -16,7 +16,7 @@ def mask_secrets_partial(config: PartialMarimoConfig) -> PartialMarimoConfig:def mask_secrets(config: MarimoConfig) -> MarimoConfig:- def deep_remove_from_path(path: list[str], obj: Dict[str, Any]) -> None:+ def deep_remove_from_path(path: list[str], obj: dict[str, Any]) -> None:key = path[0]if key not in obj:return@@ -24,7 +24,7 @@ def mask_secrets(config: MarimoConfig) -> MarimoConfig:if obj[key]:obj[key] = SECRET_PLACEHOLDERelse:- deep_remove_from_path(path[1:], cast(Dict[str, Any], obj[key]))+ deep_remove_from_path(path[1:], cast(dict[str, Any], obj[key]))secrets = [["ai", "open_ai", "api_key"],@@ -34,7 +34,7 @@ def mask_secrets(config: MarimoConfig) -> MarimoConfig:new_config = deep_copy(config)for secret in secrets:- deep_remove_from_path(secret, cast(Dict[str, Any], new_config))+ deep_remove_from_path(secret, cast(dict[str, Any], new_config))return new_config # type: ignorediff --git a/marimo/_convert/ipynb.py b/marimo/_convert/ipynb.pyindex fc2e0a8306..9ee088e5ef 100644--- a/marimo/_convert/ipynb.py+++ b/marimo/_convert/ipynb.py@@ -6,7 +6,7 @@ import jsonimport reimport sysfrom collections import defaultdict-from typing import Any, Callable, Dict, List, Union+from typing import Any, Callable, Unionfrom marimo._ast.cell import CellConfigfrom marimo._ast.compiler import compile_cell@@ -18,10 +18,10 @@ from marimo._runtime.dataflow import DirectedGraphfrom marimo._types.ids import CellId_t# Define a type for our transform functions-Transform = Callable[[List[str]], List[str]]+Transform = Callable[[list[str]], list[str]]-def transform_fixup_multiple_definitions(sources: List[str]) -> List[str]:+def transform_fixup_multiple_definitions(sources: list[str]) -> list[str]:"""Fixup multiple definitions of the same name in different cells,by making the name private (underscore) to each cell.@@ -45,7 +45,7 @@ def transform_fixup_multiple_definitions(sources: List[str]) -> List[str]:if not multiply_defined_names:return sources- name_transformations: Dict[str, str] = {}+ name_transformations: dict[str, str] = {}for name in multiply_defined_names:if not graph.get_referring_cells(name, language="python"):name_transformations[name] = (@@ -68,7 +68,7 @@ def transform_fixup_multiple_definitions(sources: List[str]) -> List[str]:return [transform(source) for source in sources]-def transform_add_marimo_import(sources: List[str]) -> List[str]:+def transform_add_marimo_import(sources: list[str]) -> list[str]:"""Add an import statement for marimo if any cell usesthe `mo.md` or `mo.sql` functions.@@ -83,7 +83,7 @@ def transform_add_marimo_import(sources: List[str]) -> List[str]:return sources-def transform_magic_commands(sources: List[str]) -> List[str]:+def transform_magic_commands(sources: list[str]) -> list[str]:"""Transform Jupyter magic commands to their marimo equivalentsor comment them out.@@ -251,7 +251,7 @@ def transform_magic_commands(sources: List[str]) -> List[str]:return "\n".join(f"# {line}" for line in source.split("\n"))return source- magics: Dict[str, Callable[[str, str], str]] = {+ magics: dict[str, Callable[[str, str], str]] = {"sql": magic_sql,"mkdir": magic_mkdir,"cd": magic_cd,@@ -307,7 +307,7 @@ def transform_magic_commands(sources: List[str]) -> List[str]:return [transform(cell) for cell in sources]-def transform_exclamation_mark(sources: List[str]) -> List[str]:+def transform_exclamation_mark(sources: list[str]) -> list[str]:"""Handle exclamation mark commands."""@@ -386,7 +386,7 @@ class Renamer:self.made_changes = name != new_name-def _transform_aug_assign(sources: List[str]) -> List[str]:+def _transform_aug_assign(sources: list[str]) -> list[str]:new_sources = sources.copy()for i, source in enumerate(sources):try:@@ -416,7 +416,7 @@ def _transform_aug_assign(sources: List[str]) -> List[str]:return new_sources-def transform_duplicate_definitions(sources: List[str]) -> List[str]:+def transform_duplicate_definitions(sources: list[str]) -> list[str]:"""Rename variables with duplicate definitions across multiple cells,even when the variables are declared in one cell and used in another.@@ -463,7 +463,7 @@ def transform_duplicate_definitions(sources: List[str]) -> List[str]:"""# Find all definitions in the AST- def find_definitions(node: ast.AST) -> List[str]:+ def find_definitions(node: ast.AST) -> list[str]:visitor = ScopedVisitor("", ignore_local=True)visitor.visit(node)# Remove local variables@@ -471,8 +471,8 @@ def transform_duplicate_definitions(sources: List[str]) -> List[str]:return [def_ for def_ in defs if not is_local(def_)]# Collect all definitions for each cell- def get_definitions(sources: List[str]) -> Dict[str, List[int]]:- definitions: Dict[str, List[int]] = defaultdict(list)+ def get_definitions(sources: list[str]) -> dict[str, list[int]]:+ definitions: dict[str, list[int]] = defaultdict(list)for i, source in enumerate(sources):try:tree = ast.parse(source)@@ -484,8 +484,8 @@ def transform_duplicate_definitions(sources: List[str]) -> List[str]:# Collect all definitions that are duplicatesdef get_duplicates(- definitions: Dict[str, List[int]],- ) -> Dict[str, List[int]]:+ definitions: dict[str, list[int]],+ ) -> dict[str, list[int]]:return {name: cellsfor name, cells in definitions.items()@@ -494,10 +494,10 @@ def transform_duplicate_definitions(sources: List[str]) -> List[str]:# Create mappings for renaming duplicatesdef create_name_mappings(- duplicates: Dict[str, List[int]], definitions: set[str]- ) -> Dict[int, Dict[str, str]]:+ duplicates: dict[str, list[int]], definitions: set[str]+ ) -> dict[int, dict[str, str]]:new_definitions: set[str] = set()- name_mappings: Dict[int, Dict[str, str]] = defaultdict(dict)+ name_mappings: dict[int, dict[str, str]] = defaultdict(dict)for name, cells in duplicates.items():for i, cell in enumerate(cells[1:], start=1):counter = i@@ -520,7 +520,7 @@ def transform_duplicate_definitions(sources: List[str]) -> List[str]:sources = _transform_aug_assign(sources)- new_sources: List[str] = sources.copy()+ new_sources: list[str] = sources.copy()name_mappings = create_name_mappings(duplicates, set(definitions.keys()))for cell_idx, source in enumerate(sources):@@ -579,12 +579,12 @@ def transform_duplicate_definitions(sources: List[str]) -> List[str]:def transform_cell_metadata(- sources: List[str], metadata: List[Dict[str, Any]]-) -> List[str]:+ sources: list[str], metadata: list[dict[str, Any]]+) -> list[str]:"""Handle cell metadata, such as tags or cell IDs."""- transformed_sources: List[str] = []+ transformed_sources: list[str] = []for source, meta in zip(sources, metadata):if "tags" in meta:tags = meta["tags"]@@ -596,14 +596,14 @@ def transform_cell_metadata(return transformed_sources-def transform_remove_duplicate_imports(sources: List[str]) -> List[str]:+def transform_remove_duplicate_imports(sources: list[str]) -> list[str]:"""Remove duplicate imports appearing in any cell."""imports: set[str] = set()- new_sources: List[str] = []+ new_sources: list[str] = []for source in sources:- new_lines: List[str] = []+ new_lines: list[str] = []for line in source.split("\n"):stripped_line = line.strip()if stripped_line.startswith("import ") or stripped_line.startswith(@@ -621,7 +621,7 @@ def transform_remove_duplicate_imports(sources: List[str]) -> List[str]:return new_sources-def transform_remove_empty_cells(sources: List[str]) -> List[str]:+def transform_remove_empty_cells(sources: list[str]) -> list[str]:"""Remove empty cells."""@@ -632,7 +632,7 @@ def transform_remove_empty_cells(sources: List[str]) -> List[str]:return sources-def transform_strip_whitespace(sources: List[str]) -> List[str]:+def transform_strip_whitespace(sources: list[str]) -> list[str]:"""Strip whitespace from the beginning and end of each cell."""@@ -657,7 +657,7 @@ def extract_inline_meta(script: str) -> tuple[str | None, str]:def _transform_sources(sources: list[str], metadata: list[dict[str, Any]]) -> list[str]:- transforms: List[Transform] = [+ transforms: list[Transform] = [transform_strip_whitespace,transform_magic_commands,transform_remove_duplicate_imports,@@ -677,7 +677,7 @@ def _transform_sources(def convert_from_ipynb(raw_notebook: str) -> str:notebook = json.loads(raw_notebook)sources: list[str] = []- metadata: list[Dict[str, Any]] = []+ metadata: list[dict[str, Any]] = []cell_configs: list[CellConfig] = []inline_meta: Union[str, None] = Nonemd_cells: set[str] = set()diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.pyindex b9f98ada8a..f08ea60d18 100644--- a/marimo/_data/get_datasets.py+++ b/marimo/_data/get_datasets.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, List, Optional, cast+from typing import TYPE_CHECKING, Optional, castfrom marimo import _loggersfrom marimo._data.models import (@@ -21,9 +21,9 @@ if TYPE_CHECKING:def get_datasets_from_variables(- variables: List[tuple[VariableName, object]],-) -> List[DataTable]:- tables: List[DataTable] = []+ variables: list[tuple[VariableName, object]],+) -> list[DataTable]:+ tables: list[DataTable] = []for variable_name, value in variables:table = _get_data_table(value, variable_name)if table is not None:@@ -89,7 +89,7 @@ def has_updates_to_datasource(query: str) -> bool:def get_databases_from_duckdb(connection: Optional[duckdb.DuckDBPyConnection],engine_name: Optional[VariableName] = None,-) -> List[Database]:+) -> list[Database]:try:return _get_databases_from_duckdb_internal(connection, engine_name)except Exception:@@ -100,7 +100,7 @@ def get_databases_from_duckdb(def _get_databases_from_duckdb_internal(connection: Optional[duckdb.DuckDBPyConnection],engine_name: Optional[VariableName] = None,-) -> List[Database]:+) -> list[Database]:"""Get database information from DuckDB."""# Columns# 0:"database"diff --git a/marimo/_data/models.py b/marimo/_data/models.pyindex 9e40be02fe..112ded7878 100644--- a/marimo/_data/models.py+++ b/marimo/_data/models.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom datetime import date, datetime, time, timedelta # noqa: TCH003from decimal import Decimal-from typing import Any, List, Literal, Optional, Union+from typing import Any, Literal, Optional, Unionfrom marimo._types.ids import VariableName@@ -38,7 +38,7 @@ class DataTableColumn:name: strtype: DataTypeexternal_type: ExternalDataType- sample_values: List[Any]+ sample_values: list[Any]DataTableSource = Literal["local", "duckdb", "connection"]@@ -70,17 +70,17 @@ class DataTable:num_rows: Optional[int]num_columns: Optional[int]variable_name: Optional[VariableName]- columns: List[DataTableColumn]+ columns: list[DataTableColumn]engine: Optional[VariableName] = Nonetype: DataTableType = "table"- primary_keys: Optional[List[str]] = None- indexes: Optional[List[str]] = None+ primary_keys: Optional[list[str]] = None+ indexes: Optional[list[str]] = None@dataclassclass Schema:name: str- tables: List[DataTable] = field(default_factory=list)+ tables: list[DataTable] = field(default_factory=list)@dataclass@@ -97,7 +97,7 @@ class Database:name: strdialect: str- schemas: List[Schema] = field(default_factory=list)+ schemas: list[Schema] = field(default_factory=list)engine: Optional[VariableName] = None@@ -147,4 +147,4 @@ class DataSourceConnection:dialect: strname: strdisplay_name: str- databases: List[Database] = field(default_factory=list)+ databases: list[Database] = field(default_factory=list)diff --git a/marimo/_data/sql_summaries.py b/marimo/_data/sql_summaries.pyindex 4de7c60f74..74721570f2 100644--- a/marimo/_data/sql_summaries.py+++ b/marimo/_data/sql_summaries.py@@ -1,8 +1,6 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import List, Tuple-from marimo._data.get_datasets import _db_type_to_data_typefrom marimo._data.models import ColumnSummary, DataTypefrom marimo._sql.utils import wrapped_sql@@ -66,7 +64,7 @@ def get_sql_summary(FROM {table_name}""" # noqa: E501- stats_result: Tuple[int, ...] | None = wrapped_sql(+ stats_result: tuple[int, ...] | None = wrapped_sql(stats_query, connection=None).fetchone()if stats_result is None:@@ -143,7 +141,7 @@ def get_column_type(table_name: str, column_name: str) -> DataType:AND column_name = '{column_name}'"""- column_info_result: Tuple[str] | None = wrapped_sql(+ column_info_result: tuple[str] | None = wrapped_sql(column_info_query, connection=None).fetchone()if column_info_result is None:@@ -157,7 +155,7 @@ def get_column_type(table_name: str, column_name: str) -> DataType:def get_histogram_data(table_name: str, column_name: str-) -> List[Tuple[str, int]]:+) -> list[tuple[str, int]]:"""Get the histogram data for a column in a SQL table."""diff --git a/marimo/_islands/_island_generator.py b/marimo/_islands/_island_generator.pyindex acd17317b9..238a050328 100644--- a/marimo/_islands/_island_generator.py+++ b/marimo/_islands/_island_generator.py@@ -5,7 +5,7 @@ import asyncioimport jsonimport sysfrom textwrap import dedent-from typing import TYPE_CHECKING, List, Optional, Union, cast+from typing import TYPE_CHECKING, Optional, Union, castfrom marimo import __version__, _loggersfrom marimo._ast.app import App, InternalApp, _AppConfig@@ -220,7 +220,7 @@ class MarimoIslandGenerator:self.has_run = Falseself._app_id = app_idself._app = InternalApp(App())- self._stubs: List[MarimoIslandStub] = []+ self._stubs: list[MarimoIslandStub] = []self._config = _AppConfig()@staticmethoddiff --git a/marimo/_loggers.py b/marimo/_loggers.pyindex 2622b015e3..4204dba0df 100644--- a/marimo/_loggers.py+++ b/marimo/_loggers.py@@ -31,7 +31,7 @@ def log_level_string_to_int(level: str) -> int:elif level == "CRITICAL":return logging.CRITICALelse:- raise ValueError("Unrecognized log level %s" % level)+ raise ValueError(f"Unrecognized log level {level}")def set_level(level: str | int = logging.WARNING) -> None:@@ -45,7 +45,7 @@ def set_level(level: str | int = logging.WARNING) -> None:logging.ERROR,logging.CRITICAL,]:- raise ValueError("Unrecognized log level %s" % level)+ raise ValueError(f"Unrecognized log level {level}")else:_LOG_LEVEL = leveldiff --git a/marimo/_messaging/cell_output.py b/marimo/_messaging/cell_output.pyindex ab46f44ba0..0ef7167499 100644--- a/marimo/_messaging/cell_output.py+++ b/marimo/_messaging/cell_output.py@@ -4,9 +4,10 @@from __future__ import annotationsimport time+from collections.abc import Sequence # noqa: TC003from dataclasses import asdict, dataclass, fieldfrom enum import Enum-from typing import Any, Dict, Sequence, Union+from typing import Any, Unionfrom marimo._messaging.errors import Errorfrom marimo._messaging.mimetypes import KnownMimeType@@ -32,7 +33,7 @@ class CellOutput:# descriptive name about the kind of output: e.g., stdout, stderr, ...channel: CellChannelmimetype: KnownMimeType- data: Union[str, Sequence[Error], Dict[str, Any]]+ data: Union[str, Sequence[Error], dict[str, Any]]timestamp: float = field(default_factory=lambda: time.time())def __repr__(self) -> str:diff --git a/marimo/_messaging/mimetypes.py b/marimo/_messaging/mimetypes.pyindex 01eb31f9e1..7500d660b0 100644--- a/marimo/_messaging/mimetypes.py+++ b/marimo/_messaging/mimetypes.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Dict, Literal, Tuple, Union+from typing import Any, Literal, Union# It is convenient to write mimetypes as strings,# but can lead to typos. This literal type@@ -29,5 +29,5 @@ KnownMimeType = Literal["text/csv",]-MimeBundle = Dict[KnownMimeType, Any]-MimeBundleOrTuple = Union[MimeBundle, Tuple[MimeBundle, Any]]+MimeBundle = dict[KnownMimeType, Any]+MimeBundleOrTuple = Union[MimeBundle, tuple[MimeBundle, Any]]diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex ae299258d3..7e1ce7ec33 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -9,17 +9,14 @@ from __future__ import annotationsimport jsonimport sysimport time+from collections.abc import Sequence # noqa: TC003from dataclasses import asdict, dataclass, fieldfrom types import ModuleTypefrom typing import (Any,ClassVar,- Dict,- List,Literal,Optional,- Sequence,- Tuple,Union,cast,)@@ -61,20 +58,20 @@ from marimo._utils.platform import is_pyodide, is_windowsLOGGER = loggers.marimo_logger()-def serialize(datacls: Any) -> Dict[str, JSONType]:+def serialize(datacls: Any) -> dict[str, JSONType]:# TODO(akshayka): maybe serialize as bytes (JSON), not objects ...,# then `send_bytes` over connection ... to try to avoid pickling# issuestry:# Try to serialize as a dataclassreturn cast(- Dict[str, JSONType],+ dict[str, JSONType],asdict(datacls),)except Exception:# If that fails, try to serialize using the WebComponentEncoderreturn cast(- Dict[str, JSONType],+ dict[str, JSONType],json.loads(WebComponentEncoder.json_dumps(datacls)),)@@ -131,7 +128,7 @@ class CellOp(Op):name: ClassVar[str] = "cell-op"cell_id: CellId_toutput: Optional[CellOutput] = None- console: Optional[Union[CellOutput, List[CellOutput]]] = None+ console: Optional[Union[CellOutput, list[CellOutput]]] = Nonestatus: Optional[RuntimeStateType] = Nonestale_inputs: Optional[bool] = Nonerun_id: Optional[RunId_t] = None@@ -393,7 +390,7 @@ class SendUIElementMessage(Op):name: ClassVar[str] = "send-ui-element-message"ui_element: str- message: Dict[str, object]+ message: dict[str, object]buffers: Optional[Sequence[str]]@@ -427,19 +424,19 @@ class KernelReady(Op):"""Kernel is ready for execution."""name: ClassVar[str] = "kernel-ready"- cell_ids: Tuple[CellId_t, ...]- codes: Tuple[str, ...]- names: Tuple[str, ...]+ cell_ids: tuple[CellId_t, ...]+ codes: tuple[str, ...]+ names: tuple[str, ...]layout: Optional[LayoutConfig]- configs: Tuple[CellConfig, ...]+ configs: tuple[CellConfig, ...]# Whether the kernel was resumed from a previous sessionresumed: bool# If the kernel was resumed, the values of the UI elements- ui_values: Optional[Dict[str, JSONType]]+ ui_values: Optional[dict[str, JSONType]]# If the kernel was resumed, the last executed code for each cell- last_executed_code: Optional[Dict[CellId_t, str]]+ last_executed_code: Optional[dict[CellId_t, str]]# If the kernel was resumed, the last execution time for each cell- last_execution_time: Optional[Dict[CellId_t, float]]+ last_execution_time: Optional[dict[CellId_t, float]]# App configapp_config: _AppConfig# Whether the kernel is kiosk mode@@ -455,7 +452,7 @@ class CompletionResult(Op):name: ClassVar[str] = "completion-result"completion_id: strprefix_length: int- options: List[CompletionOption]+ options: list[CompletionOption]@dataclass@@ -470,12 +467,12 @@ class Alert(Op):@dataclassclass MissingPackageAlert(Op):name: ClassVar[str] = "missing-package-alert"- packages: List[str]+ packages: list[str]isolated: bool# package name => installation status-PackageStatusType = Dict[+PackageStatusType = dict[str, Literal["queued", "installing", "installed", "failed"]]@@ -509,8 +506,8 @@ class Reload(Op):@dataclassclass VariableDeclaration:name: str- declared_by: List[CellId_t]- used_by: List[CellId_t]+ declared_by: list[CellId_t]+ used_by: list[CellId_t]@dataclass@@ -575,7 +572,7 @@ class Variables(Op):"""List of variable declarations."""name: ClassVar[str] = "variables"- variables: List[VariableDeclaration]+ variables: list[VariableDeclaration]@dataclass@@ -583,7 +580,7 @@ class VariableValues(Op):"""List of variables and their types/values."""name: ClassVar[str] = "variable-values"- variables: List[VariableValue]+ variables: list[VariableValue]@dataclass@@ -591,7 +588,7 @@ class Datasets(Op):"""List of datasets."""name: ClassVar[str] = "datasets"- tables: List[DataTable]+ tables: list[DataTable]clear_channel: Optional[DataTableSource] = None@@ -622,7 +619,7 @@ class DataColumnPreview(Op):@dataclassclass DataSourceConnections(Op):name: ClassVar[str] = "data-source-connections"- connections: List[DataSourceConnection]+ connections: list[DataSourceConnection]@dataclass@@ -631,7 +628,7 @@ class QueryParamsSet(Op):name: ClassVar[str] = "query-params-set"key: str- value: Union[str, List[str]]+ value: Union[str, list[str]]@dataclass@@ -665,8 +662,8 @@ class FocusCell(Op):@dataclassclass UpdateCellCodes(Op):name: ClassVar[str] = "update-cell-codes"- cell_ids: List[CellId_t]- codes: List[str]+ cell_ids: list[CellId_t]+ codes: list[str]# If true, this means the code was not run on the backend when updating# the cell codes.code_is_stale: bool@@ -682,7 +679,7 @@ class UpdateCellIdsRequest(Op):"""name: ClassVar[str] = "update-cell-ids"- cell_ids: List[CellId_t]+ cell_ids: list[CellId_t]MessageOperation = Union[diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex 6d4595eff5..90c4b745df 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -10,8 +10,6 @@ from collections import dequefrom typing import (TYPE_CHECKING,Any,- Iterable,- Iterator,Optional,Protocol,)@@ -32,6 +30,7 @@ from marimo._types.ids import CellId_tif TYPE_CHECKING:import queue+ from collections.abc import Iterable, IteratorLOGGER = _loggers.marimo_logger()@@ -241,7 +240,7 @@ class ThreadSafeStdout(Stdout):assert self._stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(- "write() argument must be a str, not %s" % type(data).__name__+ f"write() argument must be a str, not {type(data).__name__}")max_bytes = std_stream_max_bytes()if sys.getsizeof(data) > max_bytes:@@ -305,7 +304,7 @@ class ThreadSafeStderr(Stderr):assert self._stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(- "write() argument must be a str, not %s" % type(data).__name__+ f"write() argument must be a str, not {type(data).__name__}")max_bytes = std_stream_max_bytes()if sys.getsizeof(data) > max_bytes:@@ -357,7 +356,7 @@ class ThreadSafeStdin(Stdin):assert self._stream.cell_id is not Noneif not isinstance(prompt, str):raise TypeError(- "prompt must be a str, not %s" % type(prompt).__name__+ f"prompt must be a str, not {type(prompt).__name__}")max_bytes = std_stream_max_bytes()diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.pyindex 6ee3c78f32..dd5b18ccc7 100644--- a/marimo/_messaging/types.py+++ b/marimo/_messaging/types.py@@ -3,14 +3,14 @@ from __future__ import annotationsimport abcimport io-from typing import Any, Dict, Optional, Tuple+from typing import Any, Optionalfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._types.ids import CellId_t# The message from the kernel is a tuple of message type# and a json representation of the message-KernelMessage = Tuple[str, Any]+KernelMessage = tuple[str, Any]class Stream(abc.ABC):@@ -23,7 +23,7 @@ class Stream(abc.ABC):cell_id: Optional[CellId_t] = None@abc.abstractmethod- def write(self, op: str, data: Dict[Any, Any]) -> None:+ def write(self, op: str, data: dict[Any, Any]) -> None:passdef stop(self) -> None:@@ -32,7 +32,7 @@ class Stream(abc.ABC):class NoopStream(Stream):- def write(self, op: str, data: Dict[Any, Any]) -> None:+ def write(self, op: str, data: dict[Any, Any]) -> None:passdiff --git a/marimo/_messaging/variables.py b/marimo/_messaging/variables.pyindex f0373ea55a..c554793c44 100644--- a/marimo/_messaging/variables.py+++ b/marimo/_messaging/variables.py@@ -1,10 +1,13 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Mapping, Sequence, Union+from typing import TYPE_CHECKING, Any, Unionfrom marimo._plugins.ui._impl.tables.utils import get_table_manager_or_none+if TYPE_CHECKING:+ from collections.abc import Mapping, Sequence+def get_variable_preview(obj: Any,diff --git a/marimo/_output/builder.py b/marimo/_output/builder.pyindex 6ac965a322..4c40d42503 100644--- a/marimo/_output/builder.py+++ b/marimo/_output/builder.py@@ -1,19 +1,19 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import List, Optional, Tuple, Union+from typing import Optional, Unionclass _HTMLBuilder:@staticmethoddef div(- children: Union[str, List[str]], *, style: Optional[str] = None+ children: Union[str, list[str]], *, style: Optional[str] = None) -> str:resolved_children = ([children] if isinstance(children, str) else children)- params: List[Tuple[str, Union[str, None]]] = []+ params: list[tuple[str, Union[str, None]]] = []if style:params.append(("style", style))@@ -31,7 +31,7 @@ class _HTMLBuilder:alt: Optional[str] = None,style: Optional[str] = None,) -> str:- params: List[Tuple[str, Union[str, None]]] = []+ params: list[tuple[str, Union[str, None]]] = []if src:params.append(("src", src))if alt:@@ -54,7 +54,7 @@ class _HTMLBuilder:loop: bool = False,style: Optional[str] = None,) -> str:- params: List[Tuple[str, Union[str, None]]] = []+ params: list[tuple[str, Union[str, None]]] = []if src:params.append(("src", src))if controls:@@ -79,7 +79,7 @@ class _HTMLBuilder:src: Optional[str] = None,controls: bool = True,) -> str:- params: List[Tuple[str, Union[str, None]]] = []+ params: list[tuple[str, Union[str, None]]] = []if src:params.append(("src", src))if controls:@@ -103,7 +103,7 @@ class _HTMLBuilder:frameborder: Optional[str] = "0",**kwargs: str,) -> str:- params: List[Tuple[str, Union[str, None]]] = []+ params: list[tuple[str, Union[str, None]]] = []if src:params.append(("src", src))if srcdoc:@@ -128,7 +128,7 @@ class _HTMLBuilder:@staticmethoddef pre(child: str, style: Optional[str] = None) -> str:- params: List[Tuple[str, Union[str, None]]] = []+ params: list[tuple[str, Union[str, None]]] = []if style is not None:params.append(("style", style))@@ -140,7 +140,7 @@ class _HTMLBuilder:@staticmethoddef component(component_name: str,- params: List[Tuple[str, Union[str, None]]],+ params: list[tuple[str, Union[str, None]]],) -> str:if len(params) == 0:return f"<{component_name}></{component_name}>"@@ -151,13 +151,13 @@ class _HTMLBuilder:@staticmethoddef figure(- children: Union[str, List[str]], *, style: Optional[str] = None+ children: Union[str, list[str]], *, style: Optional[str] = None) -> str:resolved_children = ([children] if isinstance(children, str) else children)- params: List[Tuple[str, Union[str, None]]] = []+ params: list[tuple[str, Union[str, None]]] = []if style:params.append(("style", style))@@ -170,13 +170,13 @@ class _HTMLBuilder:@staticmethoddef figcaption(- children: Union[str, List[str]], *, style: Optional[str] = None+ children: Union[str, list[str]], *, style: Optional[str] = None) -> str:resolved_children = ([children] if isinstance(children, str) else children)- params: List[Tuple[str, Union[str, None]]] = []+ params: list[tuple[str, Union[str, None]]] = []if style:params.append(("style", style))@@ -188,7 +188,7 @@ class _HTMLBuilder:return f"<figcaption {_join_params(params)}>{children_html}</figcaption>"-def _join_params(params: List[Tuple[str, Union[str, None]]]) -> str:+def _join_params(params: list[tuple[str, Union[str, None]]]) -> str:# Filter Noneparams = [(k, v) for k, v in params if v is not None]diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.pyindex 38d6b4e076..6575d58692 100644--- a/marimo/_output/formatters/formatters.py+++ b/marimo/_output/formatters/formatters.py@@ -2,7 +2,7 @@from __future__ import annotationsimport sys-from typing import Any, Callable, Sequence+from typing import TYPE_CHECKING, Any, Callablefrom marimo._config.config import Themefrom marimo._output.formatters.ai_formatters import (@@ -35,6 +35,9 @@ from marimo._output.formatters.structures import StructuresFormatterfrom marimo._output.formatters.sympy_formatters import SympyFormatterfrom marimo._output.formatters.tqdm_formatters import TqdmFormatter+if TYPE_CHECKING:+ from collections.abc import Sequence+# Map from formatter factory's package name to formatter, for third-party# modules. These formatters will be registered if and when their associated# packages are imported.diff --git a/marimo/_output/formatters/repr_formatters.py b/marimo/_output/formatters/repr_formatters.pyindex 9e970de46a..0085470640 100644--- a/marimo/_output/formatters/repr_formatters.py+++ b/marimo/_output/formatters/repr_formatters.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Callable, Optional, Tuple+from typing import Any, Callable, Optionalfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.iframe import maybe_wrap_in_iframe@@ -22,7 +22,7 @@ def maybe_get_repr_formatter(# Check for the misc _repr_ methods# Order dictates preference- reprs: list[Tuple[str, KnownMimeType]] = [+ reprs: list[tuple[str, KnownMimeType]] = [("_repr_html_", "text/html"), # text/html is preferred first("_repr_mimebundle_", "application/vnd.marimo+mimebundle"),("_repr_svg_", "image/svg+xml"),diff --git a/marimo/_output/formatters/utils.py b/marimo/_output/formatters/utils.pyindex f36121ec0a..1e1f9f5aa1 100644--- a/marimo/_output/formatters/utils.py+++ b/marimo/_output/formatters/utils.py@@ -2,7 +2,6 @@from __future__ import annotationsimport html-from typing import Dictimport marimo._output.data.data as mo_datafrom marimo._runtime.context.types import (@@ -11,7 +10,7 @@ from marimo._runtime.context.types import ()-def src_or_src_doc(html_content: str) -> Dict[str, str]:+def src_or_src_doc(html_content: str) -> dict[str, str]:"""Depending if virtual files are supported,return the appropriate src or srcdoc attribute for an iframe.diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.pyindex 199bba68d2..d3cd429b64 100644--- a/marimo/_output/formatting.py+++ b/marimo/_output/formatting.py@@ -21,7 +21,7 @@ import jsonimport tracebackfrom dataclasses import dataclassfrom html import escape-from typing import Any, Callable, Optional, Tuple, Type, TypeVar, cast+from typing import Any, Callable, Optional, TypeVar, castfrom marimo import _loggers as loggersfrom marimo._messaging.mimetypes import KnownMimeType@@ -40,13 +40,13 @@ from marimo._utils.methods import is_callable_methodT = TypeVar("T")# we use Tuple instead of the builtin tuple for py3.8 compatibility-Formatter = Callable[[T], Tuple[KnownMimeType, str]]-FORMATTERS: dict[Type[Any], Formatter[Any]] = {}-OPINIONATED_FORMATTERS: dict[Type[Any], Formatter[Any]] = {}+Formatter = Callable[[T], tuple[KnownMimeType, str]]+FORMATTERS: dict[type[Any], Formatter[Any]] = {}+OPINIONATED_FORMATTERS: dict[type[Any], Formatter[Any]] = {}LOGGER = loggers.marimo_logger()-def formatter(t: Type[Any]) -> Callable[[Formatter[T]], Formatter[T]]:+def formatter(t: type[Any]) -> Callable[[Formatter[T]], Formatter[T]]:"""Register a formatter function for a typeDecorator to register a custom formatter for a given type.@@ -69,7 +69,7 @@ def formatter(t: Type[Any]) -> Callable[[Formatter[T]], Formatter[T]]:def opinionated_formatter(- t: Type[Any],+ t: type[Any],) -> Callable[[Formatter[T]], Formatter[T]]:"""Register an opinionated formatter function for a typediff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.pyindex d1802606b3..f2b3388140 100644--- a/marimo/_output/hypertext.py+++ b/marimo/_output/hypertext.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport osimport weakreffrom contextlib import contextmanager-from typing import TYPE_CHECKING, Any, Iterator, Literal, Optional, cast, final+from typing import TYPE_CHECKING, Any, Literal, Optional, cast, finalfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.mime import MIME@@ -12,6 +12,8 @@ from marimo._output.rich_help import mddocfrom marimo._output.utils import flatten_stringif TYPE_CHECKING:+ from collections.abc import Iterator+from marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._plugins.ui._impl.batch import batch as batch_plugindiff --git a/marimo/_plugins/core/media.py b/marimo/_plugins/core/media.pyindex 046487e2e5..e46c34c9cd 100644--- a/marimo/_plugins/core/media.py+++ b/marimo/_plugins/core/media.py@@ -53,7 +53,7 @@ def io_to_data_url(io.BufferedReader,pathlib.Path,PILImage,- "npt.NDArray[Any]",+ npt.NDArray[Any],DataFrame,None,],@@ -125,7 +125,7 @@ def io_to_data_url(try:with open(src, "rb") as f:return io_to_data_url(f, fallback_mime_type)- except (FileNotFoundError, IOError):+ except (OSError, FileNotFoundError):return src# Handle Pandas DataFrames (convert to CSV)diff --git a/marimo/_plugins/core/web_component.py b/marimo/_plugins/core/web_component.pyindex 49fa56b8b3..f396dc1ee0 100644--- a/marimo/_plugins/core/web_component.py+++ b/marimo/_plugins/core/web_component.py@@ -3,11 +3,10 @@ from __future__ import annotationsimport jsonimport re+from collections.abc import Mapping, Sequencefrom html import escape, unescapefrom typing import (TYPE_CHECKING,- Mapping,- Sequence,TypeVar,Union,cast,diff --git a/marimo/_plugins/stateless/carousel.py b/marimo/_plugins/stateless/carousel.pyindex 9c30351c3b..11e46e2860 100644--- a/marimo/_plugins/stateless/carousel.py+++ b/marimo/_plugins/stateless/carousel.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Sequence+from typing import TYPE_CHECKINGfrom marimo._output.formatting import as_htmlfrom marimo._output.hypertext import Html@@ -9,6 +9,9 @@ from marimo._output.md import mdfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import build_stateless_plugin+if TYPE_CHECKING:+ from collections.abc import Sequence+@mddocdef carousel(diff --git a/marimo/_plugins/stateless/download.py b/marimo/_plugins/stateless/download.pyindex 6a126bcc39..e5086f087c 100644--- a/marimo/_plugins/stateless/download.py+++ b/marimo/_plugins/stateless/download.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport asyncioimport iofrom dataclasses import dataclass-from typing import Any, Callable, Coroutine, Final, Optional, Union, cast+from typing import TYPE_CHECKING, Any, Callable, Final, Optional, Union, castimport marimo._output.data.data as mo_datafrom marimo._output.rich_help import mddoc@@ -17,6 +17,9 @@ from marimo._plugins.core.media import (from marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.functions import EmptyArgs, Function+if TYPE_CHECKING:+ from collections.abc import Coroutine+DataType = Union[str, bytes, io.BytesIO, io.BufferedReader]diff --git a/marimo/_plugins/stateless/lazy.py b/marimo/_plugins/stateless/lazy.pyindex b3a2120d27..fc844a897e 100644--- a/marimo/_plugins/stateless/lazy.py+++ b/marimo/_plugins/stateless/lazy.py@@ -3,13 +3,16 @@ from __future__ import annotationsimport asynciofrom dataclasses import dataclass-from typing import Callable, Coroutine, Final, Union+from typing import TYPE_CHECKING, Callable, Final, Unionfrom marimo._output.formatting import as_htmlfrom marimo._output.rich_help import mddocfrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.functions import EmptyArgs, Function+if TYPE_CHECKING:+ from collections.abc import Coroutine+@dataclassclass LoadResponse:diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pyindex 3d762caf43..060fb2075a 100644--- a/marimo/_plugins/stateless/mpl/_mpl.py+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -16,7 +16,7 @@ import signalimport threadingimport timefrom pathlib import Path-from typing import TYPE_CHECKING, Any, Optional, Tuple, Union+from typing import TYPE_CHECKING, Any, Optional, Unionfrom marimo import _loggersfrom marimo._output.builder import h@@ -158,7 +158,7 @@ def create_application() -> Starlette:async def websocket_endpoint(websocket: WebSocket) -> None:await websocket.accept()- queue: asyncio.Queue[Tuple[Any, str]] = asyncio.Queue()+ queue: asyncio.Queue[tuple[Any, str]] = asyncio.Queue()class SyncWebSocket:def send_json(self, content: str) -> None:diff --git a/marimo/_plugins/stateless/nav_menu.py b/marimo/_plugins/stateless/nav_menu.pyindex 58025b44ea..9f11ba9726 100644--- a/marimo/_plugins/stateless/nav_menu.py+++ b/marimo/_plugins/stateless/nav_menu.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom dataclasses import asdict, dataclass-from typing import List, Literal, Optional, Union, cast+from typing import Literal, Optional, Union, castfrom marimo._output.hypertext import Htmlfrom marimo._output.md import md@@ -78,7 +78,7 @@ def nav_menu(@dataclassclass NavMenu:- items: List[Union[NavMenuItemLink, NavMenuItemGroup]]+ items: list[Union[NavMenuItemLink, NavMenuItemGroup]]@dataclass@@ -91,7 +91,7 @@ class NavMenuItemLink:@dataclassclass NavMenuItemGroup:label: str- items: List[NavMenuItemLink]+ items: list[NavMenuItemLink]def _build_and_validate_menu(menu: dict[str, JSONType]) -> NavMenu:@@ -106,14 +106,14 @@ def _build_and_validate_menu(menu: dict[str, JSONType]) -> NavMenu:return hrefraise ValueError(f"Invalid href: {href}, must start with / or #")- items: List[Union[NavMenuItemLink, NavMenuItemGroup]] = []+ items: list[Union[NavMenuItemLink, NavMenuItemGroup]] = []for k, v in menu.items():if isinstance(v, str):items.append(NavMenuItemLink(label=md(v).text, href=validate_href(k)))elif isinstance(v, dict):- subitems: List[NavMenuItemLink] = []+ subitems: list[NavMenuItemLink] = []for kk, vv in v.items():if isinstance(vv, str):subitems.append(diff --git a/marimo/_plugins/stateless/routes.py b/marimo/_plugins/stateless/routes.pyindex 64e73c6286..eb6c194b1f 100644--- a/marimo/_plugins/stateless/routes.py+++ b/marimo/_plugins/stateless/routes.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Callable, Coroutine, Final, Union+from typing import TYPE_CHECKING, Any, Callable, Final, Unionfrom marimo._output.formatting import as_htmlfrom marimo._output.hypertext import Html@@ -9,6 +9,9 @@ from marimo._output.rich_help import mddocfrom marimo._plugins.stateless import lazyfrom marimo._plugins.ui._core.ui_element import UIElement+if TYPE_CHECKING:+ from collections.abc import Coroutine+@mddocclass routes(UIElement[str, str]):diff --git a/marimo/_plugins/stateless/status/_progress.py b/marimo/_plugins/stateless/status/_progress.pyindex 5613e464a4..e741bb918d 100644--- a/marimo/_plugins/stateless/status/_progress.py+++ b/marimo/_plugins/stateless/status/_progress.py@@ -5,7 +5,6 @@ import timefrom typing import (TYPE_CHECKING,Any,- Iterable,Literal,Optional,TypeVar,@@ -20,7 +19,7 @@ from marimo._plugins.core.web_component import build_stateless_pluginfrom marimo._utils.debounce import debounceif TYPE_CHECKING:- from collections.abc import Collection+ from collections.abc import Collection, IterableS = TypeVar("S")T = TypeVar("T")diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.pyindex e26858a759..bf3b20b305 100644--- a/marimo/_plugins/ui/_core/registry.py+++ b/marimo/_plugins/ui/_core/registry.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport sysimport weakref-from typing import Any, Dict, Iterable, Mapping, Optional, TypeVar, Union+from typing import TYPE_CHECKING, Any, Optional, TypeVar, Unionfrom marimo._runtime.context.types import ContextNotInitializedError@@ -17,10 +17,13 @@ from marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.context import get_contextfrom marimo._types.ids import CellId_t, UIElementId+if TYPE_CHECKING:+ from collections.abc import Iterable, Mapping+T = TypeVar("T")# Recursive types don't support | or dict[] in py3.8/3.9-LensValue: TypeAlias = Union[T, Dict[str, "LensValue[T]"]]+LensValue: TypeAlias = Union[T, dict[str, "LensValue[T]"]]class UIElementRegistry:diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex 27010b41dc..0deb8f6999 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -15,10 +15,8 @@ from typing import (TYPE_CHECKING,Any,Callable,- Dict,Generic,Optional,- Sequence,TypeVar,cast,)@@ -37,6 +35,8 @@ from marimo._runtime.functions import Functionfrom marimo._types.ids import UIElementIdif TYPE_CHECKING:+ from collections.abc import Sequence+from marimo._plugins.ui._impl.input import form as form_plugin# S: Type of frontend value@@ -428,7 +428,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):)def send_message(- self, message: Dict[str, object], buffers: Optional[Sequence[bytes]]+ self, message: dict[str, object], buffers: Optional[Sequence[bytes]]) -> None:"""Send a message to the element rendered on the frontenddiff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex 150b12fecf..d5f88658e2 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -7,9 +7,7 @@ from typing import (TYPE_CHECKING,Any,Callable,- Dict,Final,- List,Literal,Optional,Union,@@ -44,11 +42,11 @@ if TYPE_CHECKING:# "field": ["value1", "value2", ...]# }# }-ChartSelectionField = Dict[str, Union[List[int], List[float], List[str]]]-ChartSelection = Dict[str, ChartSelectionField]-VegaSpec = Dict[str, Any]-RowOrientedData = List[Dict[str, Any]]-ColumnOrientedData = Dict[str, List[Any]]+ChartSelectionField = dict[str, Union[list[int], list[float], list[str]]]+ChartSelection = dict[str, ChartSelectionField]+VegaSpec = dict[str, Any]+RowOrientedData = list[dict[str, Any]]+ColumnOrientedData = dict[str, list[Any]]ChartDataType = Union[IntoDataFrame, RowOrientedData, ColumnOrientedData]@@ -155,7 +153,7 @@ def _filter_dataframe(return nw.to_native(df)-def _resolve_values(values: Any, dtype: Any) -> List[Any]:+def _resolve_values(values: Any, dtype: Any) -> list[Any]:def _coerce_value(value: Any, dtype: Any) -> Any:import zoneinfodiff --git a/marimo/_plugins/ui/_impl/anywidget/init.py b/marimo/_plugins/ui/_impl/anywidget/init.pyindex 16dd2e2266..ab78acf990 100644--- a/marimo/_plugins/ui/_impl/anywidget/init.py+++ b/marimo/_plugins/ui/_impl/anywidget/init.py@@ -16,7 +16,7 @@ from marimo._plugins.ui._impl.comm import ( # pyright: ignore[reportMissingType# Initialize ipywidgets using a MarimoComm-def init_marimo_widget(w: "ipywidgets.Widget") -> None:+def init_marimo_widget(w: ipywidgets.Widget) -> None:DependencyManager.ipywidgets.require("for anywidget support.")import ipywidgets # type: ignorediff --git a/marimo/_plugins/ui/_impl/array.py b/marimo/_plugins/ui/_impl/array.pyindex db6c4c0616..6638436f56 100644--- a/marimo/_plugins/ui/_impl/array.py+++ b/marimo/_plugins/ui/_impl/array.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Callable, Dict, Final, Iterator, Optional, Sequence+from collections.abc import Iterator, Sequence+from typing import Any, Callable, Final, Optionalfrom marimo._output.formatters.structures import format_structurefrom marimo._output.hypertext import Html@@ -15,7 +16,7 @@ from marimo._plugins.ui._core.ui_element import UIElement# Frontend type is a tuple (index, value update)# Python type is a sequence of values, one for each UI element@mddoc-class array(UIElement[Dict[str, JSONType], Sequence[object]]):+class array(UIElement[dict[str, JSONType], Sequence[object]]):"""An array of UI elements.Use an array to:diff --git a/marimo/_plugins/ui/_impl/batch.py b/marimo/_plugins/ui/_impl/batch.pyindex ed99d10672..13e29817c0 100644--- a/marimo/_plugins/ui/_impl/batch.py+++ b/marimo/_plugins/ui/_impl/batch.py@@ -5,9 +5,7 @@ from typing import (TYPE_CHECKING,Any,Callable,- Dict,Final,- Iterator,Optional,)@@ -17,12 +15,12 @@ from marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElementif TYPE_CHECKING:- from collections.abc import ItemsView, ValuesView+ from collections.abc import ItemsView, Iterator, ValuesView# - Frontend type is a dict {label => value update}# - Python type is a dict mapping label -> value-class _batch_base(UIElement[Dict[str, JSONType], Dict[str, object]]):+class _batch_base(UIElement[dict[str, JSONType], dict[str, object]]):"""A batch of named UI elements represented by HTML text."""_name: Final[str] = "marimo-dict"@@ -32,7 +30,7 @@ class _batch_base(UIElement[Dict[str, JSONType], Dict[str, object]]):html: Html,elements: dict[str, UIElement[JSONType, object]],label: str = "",- on_change: Optional[Callable[[Dict[str, object]], None]] = None,+ on_change: Optional[Callable[[dict[str, object]], None]] = None,) -> None:self._elements = elementssuper().__init__(@@ -187,7 +185,7 @@ class batch(_batch_base):self,html: Html,elements: dict[str, UIElement[Any, Any]],- on_change: Optional[Callable[[Dict[str, object]], None]] = None,+ on_change: Optional[Callable[[dict[str, object]], None]] = None,) -> None:self._html = htmlelements = {key: element._clone() for key, element in elements.items()}diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.pyindex 06fa76b20a..b5afefdc6d 100644--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py@@ -2,7 +2,7 @@from __future__ import annotationsimport base64-from typing import Any, Dict, Literal, TypedDict, Union+from typing import Any, Literal, TypedDict, Unionimport narwhals.stable.v1 as nwfrom narwhals.typing import IntoDataFrame@@ -15,8 +15,8 @@ from marimo._plugins.ui._impl.tables.utils import ()from marimo._utils.data_uri import build_data_url-Data = Union[Dict[Any, Any], IntoDataFrame, nw.DataFrame[Any]]-_DataType = Union[Dict[Any, Any], IntoDataFrame, nw.DataFrame[Any]]+Data = Union[dict[Any, Any], IntoDataFrame, nw.DataFrame[Any]]+_DataType = Union[dict[Any, Any], IntoDataFrame, nw.DataFrame[Any]]class _JsonFormatDict(TypedDict):@@ -117,7 +117,7 @@ def _data_to_json_string(data: _DataType) -> str:raise NotImplementedError("to_marimo_json only works with data expressed as a DataFrame "- + " or as a dict. Got %s" % type(data)+ + f" or as a dict. Got {type(data)}")diff --git a/marimo/_plugins/ui/_impl/chat/chat.py b/marimo/_plugins/ui/_impl/chat/chat.pyindex 6578d96045..9e6aa40211 100644--- a/marimo/_plugins/ui/_impl/chat/chat.py+++ b/marimo/_plugins/ui/_impl/chat/chat.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport inspectfrom dataclasses import dataclass-from typing import Any, Callable, Dict, Final, List, Optional, Union, cast+from typing import Any, Callable, Final, Optional, Union, castfrom marimo._ai._types import (ChatMessage,@@ -16,7 +16,6 @@ from marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._plugins.ui._impl.chat.utils import from_chat_message_dict-from marimo._runtime.context.kernel_context import KernelRuntimeContextfrom marimo._runtime.context.types import ContextNotInitializedErrorfrom marimo._runtime.functions import EmptyArgs, Functionfrom marimo._runtime.requests import SetUIElementValueRequest@@ -24,13 +23,13 @@ from marimo._runtime.requests import SetUIElementValueRequest@dataclassclass SendMessageRequest:- messages: List[ChatMessage]+ messages: list[ChatMessage]config: ChatModelConfig@dataclassclass GetChatHistoryResponse:- messages: List[ChatMessage]+ messages: list[ChatMessage]@dataclass@@ -39,7 +38,7 @@ class DeleteChatMessageRequest:@mddoc-class chat(UIElement[Dict[str, Any], List[ChatMessage]]):+class chat(UIElement[dict[str, Any], list[ChatMessage]]):"""A chatbot UI element for interactive conversations.Define a chatbot by implementing a function that takes a list of ChatMessages and@@ -132,17 +131,17 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):def __init__(self,- model: Callable[[List[ChatMessage], ChatModelConfig], object],+ model: Callable[[list[ChatMessage], ChatModelConfig], object],*,- prompts: Optional[List[str]] = None,- on_message: Optional[Callable[[List[ChatMessage]], None]] = None,+ prompts: Optional[list[str]] = None,+ on_message: Optional[Callable[[list[ChatMessage]], None]] = None,show_configuration_controls: bool = False,config: Optional[ChatModelConfigDict] = None,- allow_attachments: Union[bool, List[str]] = False,+ allow_attachments: Union[bool, list[str]] = False,max_height: Optional[int] = None,) -> None:self._model = model- self._chat_history: List[ChatMessage] = []+ self._chat_history: list[ChatMessage] = []super().__init__(component_name=chat._name,@@ -241,6 +240,10 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):if self._on_change is not None:self._on_change(self._value)else:+ from marimo._runtime.context.kernel_context import (+ KernelRuntimeContext,+ )+if isinstance(ctx, KernelRuntimeContext):ctx._kernel.enqueue_control_request(SetUIElementValueRequest(@@ -256,7 +259,7 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):return md(response).textreturn as_html(response).text- def _convert_value(self, value: Dict[str, Any]) -> List[ChatMessage]:+ def _convert_value(self, value: dict[str, Any]) -> list[ChatMessage]:if not isinstance(value, dict) or "messages" not in value:raise ValueError("Invalid chat history format")diff --git a/marimo/_plugins/ui/_impl/chat/utils.py b/marimo/_plugins/ui/_impl/chat/utils.pyindex a0e3a844a5..b42249b316 100644--- a/marimo/_plugins/ui/_impl/chat/utils.py+++ b/marimo/_plugins/ui/_impl/chat/utils.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import List, Optional+from typing import Optionalfrom marimo._ai._types import (ChatAttachment,@@ -15,7 +15,7 @@ def from_chat_message_dict(d: ChatMessageDict) -> ChatMessage:return dattachments_dict = d.get("attachments", None)- attachments: Optional[List[ChatAttachment]] = None+ attachments: Optional[list[ChatAttachment]] = Noneif attachments_dict is not None:attachments = [ChatAttachment(diff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.pyindex 88a3bc7688..1a0570ab04 100644--- a/marimo/_plugins/ui/_impl/comm.py+++ b/marimo/_plugins/ui/_impl/comm.py@@ -2,25 +2,25 @@from __future__ import annotationsimport base64-from typing import Any, Callable, Dict, List, Optional+from typing import Any, Callable, Optionalclass MarimoCommManager:- comms: Dict[str, "MarimoComm"] = {}+ comms: dict[str, MarimoComm] = {}- def register_comm(self, comm: "MarimoComm") -> str:+ def register_comm(self, comm: MarimoComm) -> str:comm_id = comm.comm_idself.comms[comm_id] = commreturn comm_id- def unregister_comm(self, comm: "MarimoComm") -> "MarimoComm":+ def unregister_comm(self, comm: MarimoComm) -> MarimoComm:return self.comms.pop(comm.comm_id)-MsgCallback = Callable[[Dict[str, object]], None]-DataType = Optional[Dict[str, object]]-MetadataType = Optional[Dict[str, object]]-BufferType = Optional[List[bytes]]+MsgCallback = Callable[[dict[str, object]], None]+DataType = Optional[dict[str, object]]+MetadataType = Optional[dict[str, object]]+BufferType = Optional[list[bytes]]COMM_MESSAGE_NAME = "marimo_comm_msg"COMM_OPEN_NAME = "marimo_comm_open"@@ -39,7 +39,7 @@ class MarimoComm:_msg_callback: Optional[MsgCallback]_close_callback: Optional[MsgCallback]_closed: bool = False- _closed_data: Dict[str, object] = {}+ _closed_data: dict[str, object] = {}def __init__(self,@@ -172,10 +172,10 @@ class MarimoComm:def on_close(self, callback: MsgCallback) -> None:self._close_callback = callback- def handle_msg(self, msg: Dict[str, object]) -> None:+ def handle_msg(self, msg: dict[str, object]) -> None:if self._msg_callback is not None:self._msg_callback(msg)- def handle_close(self, msg: Dict[str, object]) -> None:+ def handle_close(self, msg: dict[str, object]) -> None:if self._close_callback is not None:self._close_callback(msg)diff --git a/marimo/_plugins/ui/_impl/data_editor.py b/marimo/_plugins/ui/_impl/data_editor.pyindex eca1ed2b43..fec96b2178 100644--- a/marimo/_plugins/ui/_impl/data_editor.py+++ b/marimo/_plugins/ui/_impl/data_editor.py@@ -8,9 +8,7 @@ from typing import (TYPE_CHECKING,Any,Callable,- Dict,Final,- List,Optional,TypedDict,Union,@@ -41,7 +39,7 @@ class DataEditorValue:data (List[Dict[str, Any]]): Row-oriented data as a list of dictionaries."""- data: List[Dict[str, Any]]+ data: list[dict[str, Any]]class PositionalEdit(TypedDict):@@ -65,11 +63,11 @@ class DataEdits(TypedDict):edits (List[PositionalEdit]): List of individual cell edits."""- edits: List[PositionalEdit]+ edits: list[PositionalEdit]-RowOrientedData = List[Dict[str, Any]]-ColumnOrientedData = Dict[str, List[Any]]+RowOrientedData = list[dict[str, Any]]+ColumnOrientedData = dict[str, list[Any]]@mddocdiff --git a/marimo/_plugins/ui/_impl/data_explorer.py b/marimo/_plugins/ui/_impl/data_explorer.pyindex 1465e52141..0c9244b0e4 100644--- a/marimo/_plugins/ui/_impl/data_explorer.py+++ b/marimo/_plugins/ui/_impl/data_explorer.py@@ -1,7 +1,7 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, Any, Callable, Dict, Final, Optional+from typing import TYPE_CHECKING, Any, Callable, Final, Optionalimport marimo._output.data.data as mo_datafrom marimo._dependencies.dependencies import DependencyManager@@ -14,7 +14,7 @@ if TYPE_CHECKING:@mddoc-class data_explorer(UIElement[Dict[str, Any], Dict[str, Any]]):+class data_explorer(UIElement[dict[str, Any], dict[str, Any]]):"""Quickly explore a DataFrame with automatically suggested visualizations.Examples:@@ -34,7 +34,7 @@ class data_explorer(UIElement[Dict[str, Any], Dict[str, Any]]):def __init__(self,df: IntoDataFrame,- on_change: Optional[Callable[[Dict[str, Any]], None]] = None,+ on_change: Optional[Callable[[dict[str, Any]], None]] = None,) -> None:# Drop the index since empty column names break the data explorerdf = _drop_index(df)@@ -52,7 +52,7 @@ class data_explorer(UIElement[Dict[str, Any], Dict[str, Any]]):},)- def _convert_value(self, value: Dict[str, Any]) -> Dict[str, Any]:+ def _convert_value(self, value: dict[str, Any]) -> dict[str, Any]:return valuediff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pyindex b39dba96f7..9d20e976de 100644--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -7,9 +7,7 @@ from dataclasses import dataclassfrom typing import (Any,Callable,- Dict,Final,- List,Optional,Union,)@@ -51,7 +49,7 @@ class GetDataFrameResponse:total_rows: int# List of column names that are actually row headers# This really only applies to Pandas, that has special index columns- row_headers: List[str]+ row_headers: list[str]field_types: FieldTypespython_code: Optional[str] = Nonesql_code: Optional[str] = None@@ -64,7 +62,7 @@ class GetColumnValuesArgs:@dataclassclass GetColumnValuesResponse:- values: List[str | int | float]+ values: list[str | int | float]too_many_values: bool@@ -81,7 +79,7 @@ class GetDataFrameError(Exception):@mddoc-class dataframe(UIElement[Dict[str, Any], DataFrameType]):+class dataframe(UIElement[dict[str, Any], DataFrameType]):"""Run transformations on a DataFrame or series.Currently only Pandas or Polars DataFrames are supported.@@ -178,7 +176,7 @@ class dataframe(UIElement[Dict[str, Any], DataFrameType]):),)- def _get_column_types(self) -> List[List[Union[str, int]]]:+ def _get_column_types(self) -> list[list[Union[str, int]]]:return [[name, dtype[0], dtype[1]]for name, dtype in self._manager.get_field_types()@@ -229,7 +227,7 @@ class dataframe(UIElement[Dict[str, Any], DataFrameType]):too_many_values=True,)- def _convert_value(self, value: Dict[str, Any]) -> DataFrameType:+ def _convert_value(self, value: dict[str, Any]) -> DataFrameType:if value is None:self._error = Nonereturn self._data@@ -241,7 +239,7 @@ class dataframe(UIElement[Dict[str, Any], DataFrameType]):self._last_transforms = transformationsreturn resultexcept Exception as e:- error = "Error applying dataframe transform: %s\n\n" % str(e)+ error = f"Error applying dataframe transform: {str(e)}\n\n"sys.stderr.write(error)self._error = errorreturn self._datadiff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/apply.py b/marimo/_plugins/ui/_impl/dataframes/transforms/apply.pyindex e08c557caa..26c2d697c7 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/apply.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/apply.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Generic, List, TypeVar+from typing import Any, Generic, TypeVarfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.ui._impl.dataframes.transforms.handlers import (@@ -105,7 +105,7 @@ class TransformsContainer(Generic[T]):# The dataframe for the given transform.self._snapshot_df = dfself._handler = handler- self._transforms: List[Transform] = []+ self._transforms: list[Transform] = []def apply(self, transform: Transformations) -> T:"""diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.pyindex 3032cc49da..f16035c14f 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py@@ -2,7 +2,8 @@from __future__ import annotationsimport datetime-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, cast+from collections.abc import Sequence+from typing import TYPE_CHECKING, Any, Optional, castfrom marimo._plugins.ui._impl.dataframes.transforms.print_code import (python_print_pandas,@@ -36,8 +37,8 @@ if TYPE_CHECKING:class PandasTransformHandler(TransformHandler["pd.DataFrame"]):@staticmethoddef handle_column_conversion(- df: "pd.DataFrame", transform: ColumnConversionTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: ColumnConversionTransform+ ) -> pd.DataFrame:df[transform.column_id] = df[transform.column_id].astype(transform.data_type,errors=transform.errors,@@ -46,16 +47,16 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):@staticmethoddef handle_rename_column(- df: "pd.DataFrame", transform: RenameColumnTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: RenameColumnTransform+ ) -> pd.DataFrame:return df.rename(columns={transform.column_id: transform.new_column_id})@staticmethoddef handle_sort_column(- df: "pd.DataFrame", transform: SortColumnTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: SortColumnTransform+ ) -> pd.DataFrame:return df.sort_values(by=cast(str, transform.column_id),ascending=transform.ascending,@@ -64,14 +65,14 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):@staticmethoddef handle_filter_rows(- df: "pd.DataFrame", transform: FilterRowsTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: FilterRowsTransform+ ) -> pd.DataFrame:if not transform.where:return dfimport pandas as pd- clauses: List[pd.Series[Any]] = []+ clauses: list[pd.Series[Any]] = []for condition in transform.where:column: pd.Series[Any] = df[condition.column_id]@@ -142,8 +143,8 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):@staticmethoddef handle_group_by(- df: "pd.DataFrame", transform: GroupByTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: GroupByTransform+ ) -> pd.DataFrame:group = df.groupby(transform.column_ids, dropna=transform.drop_na)if transform.aggregation == "count":return group.count()@@ -162,8 +163,8 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):@staticmethoddef handle_aggregate(- df: "pd.DataFrame", transform: AggregateTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: AggregateTransform+ ) -> pd.DataFrame:dict_of_aggs = {column_id: transform.aggregationsfor column_id in transform.column_ids@@ -176,20 +177,20 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):@staticmethoddef handle_select_columns(- df: "pd.DataFrame", transform: SelectColumnsTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: SelectColumnsTransform+ ) -> pd.DataFrame:return df[transform.column_ids]@staticmethoddef handle_shuffle_rows(- df: "pd.DataFrame", transform: ShuffleRowsTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: ShuffleRowsTransform+ ) -> pd.DataFrame:return df.sample(frac=1, random_state=transform.seed)@staticmethoddef handle_sample_rows(- df: "pd.DataFrame", transform: SampleRowsTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: SampleRowsTransform+ ) -> pd.DataFrame:return df.sample(n=transform.n,random_state=transform.seed,@@ -198,14 +199,14 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):@staticmethoddef handle_explode_columns(- df: "pd.DataFrame", transform: ExplodeColumnsTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: ExplodeColumnsTransform+ ) -> pd.DataFrame:return df.explode(transform.column_ids)@staticmethoddef handle_expand_dict(- df: "pd.DataFrame", transform: ExpandDictTransform- ) -> "pd.DataFrame":+ df: pd.DataFrame, transform: ExpandDictTransform+ ) -> pd.DataFrame:import pandas as pdcolumn_id = transform.column_id@@ -215,7 +216,7 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):@staticmethoddef as_python_code(- df_name: str, columns: List[str], transforms: List[Transform]+ df_name: str, columns: list[str], transforms: list[Transform]) -> str:return python_print_transforms(df_name, columns, transforms, python_print_pandas@@ -225,8 +226,8 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):@staticmethoddef handle_column_conversion(- df: "pl.DataFrame", transform: ColumnConversionTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: ColumnConversionTransform+ ) -> pl.DataFrame:import polars.datatypes as pl_datatypesreturn df.cast(@@ -240,16 +241,16 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):@staticmethoddef handle_rename_column(- df: "pl.DataFrame", transform: RenameColumnTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: RenameColumnTransform+ ) -> pl.DataFrame:return df.rename({str(transform.column_id): str(transform.new_column_id)})@staticmethoddef handle_sort_column(- df: "pl.DataFrame", transform: SortColumnTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: SortColumnTransform+ ) -> pl.DataFrame:return df.sort(by=transform.column_id,descending=not transform.ascending,@@ -258,8 +259,8 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):@staticmethoddef handle_filter_rows(- df: "pl.DataFrame", transform: FilterRowsTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: FilterRowsTransform+ ) -> pl.DataFrame:import polars as plfrom polars import col@@ -342,8 +343,8 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):@staticmethoddef handle_group_by(- df: "pl.DataFrame", transform: GroupByTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: GroupByTransform+ ) -> pl.DataFrame:aggs: list[pl.Expr] = []from polars import col@@ -376,8 +377,8 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):@staticmethoddef handle_aggregate(- df: "pl.DataFrame", transform: AggregateTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: AggregateTransform+ ) -> pl.DataFrame:import polars as plselected_df = df.select(transform.column_ids)@@ -409,20 +410,20 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):@staticmethoddef handle_select_columns(- df: "pl.DataFrame", transform: SelectColumnsTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: SelectColumnsTransform+ ) -> pl.DataFrame:return df.select(transform.column_ids)@staticmethoddef handle_shuffle_rows(- df: "pl.DataFrame", transform: ShuffleRowsTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: ShuffleRowsTransform+ ) -> pl.DataFrame:return df.sample(fraction=1, shuffle=True, seed=transform.seed)@staticmethoddef handle_sample_rows(- df: "pl.DataFrame", transform: SampleRowsTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: SampleRowsTransform+ ) -> pl.DataFrame:return df.sample(n=transform.n,shuffle=True,@@ -432,14 +433,14 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):@staticmethoddef handle_explode_columns(- df: "pl.DataFrame", transform: ExplodeColumnsTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: ExplodeColumnsTransform+ ) -> pl.DataFrame:return df.explode(cast(Sequence[str], transform.column_ids))@staticmethoddef handle_expand_dict(- df: "pl.DataFrame", transform: ExpandDictTransform- ) -> "pl.DataFrame":+ df: pl.DataFrame, transform: ExpandDictTransform+ ) -> pl.DataFrame:import polars as plcolumn_id = transform.column_id@@ -449,7 +450,7 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):@staticmethoddef as_python_code(- df_name: str, columns: List[str], transforms: List[Transform]+ df_name: str, columns: list[str], transforms: list[Transform]) -> str:return python_print_transforms(df_name, columns, transforms, python_print_polars@@ -459,8 +460,8 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):class IbisTransformHandler(TransformHandler["ibis.Table"]):@staticmethoddef handle_column_conversion(- df: "ibis.Table", transform: ColumnConversionTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: ColumnConversionTransform+ ) -> ibis.Table:import ibisif transform.errors == "ignore":@@ -486,14 +487,14 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):@staticmethoddef handle_rename_column(- df: "ibis.Table", transform: RenameColumnTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: RenameColumnTransform+ ) -> ibis.Table:return df.rename({transform.new_column_id: transform.column_id})@staticmethoddef handle_sort_column(- df: "ibis.Table", transform: SortColumnTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: SortColumnTransform+ ) -> ibis.Table:return df.order_by([(@@ -506,8 +507,8 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):@staticmethoddef handle_filter_rows(- df: "ibis.Table", transform: FilterRowsTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: FilterRowsTransform+ ) -> ibis.Table:import ibisfilter_conditions: list[ir.BooleanValue] = []@@ -562,8 +563,8 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):@staticmethoddef handle_group_by(- df: "ibis.Table", transform: GroupByTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: GroupByTransform+ ) -> ibis.Table:aggs: list[ir.Expr] = []group_by_column_id_set = set(transform.column_ids)@@ -593,9 +594,9 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):@staticmethoddef handle_aggregate(- df: "ibis.Table", transform: AggregateTransform- ) -> "ibis.Table":- agg_dict: Dict[str, Any] = {}+ df: ibis.Table, transform: AggregateTransform+ ) -> ibis.Table:+ agg_dict: dict[str, Any] = {}for agg_func in transform.aggregations:for column_id in transform.column_ids:name = f"{column_id}_{agg_func}"@@ -604,14 +605,14 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):@staticmethoddef handle_select_columns(- df: "ibis.Table", transform: SelectColumnsTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: SelectColumnsTransform+ ) -> ibis.Table:return df.select(transform.column_ids)@staticmethoddef handle_shuffle_rows(- df: "ibis.Table", transform: ShuffleRowsTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: ShuffleRowsTransform+ ) -> ibis.Table:del transformimport ibis@@ -619,8 +620,8 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):@staticmethoddef handle_sample_rows(- df: "ibis.Table", transform: SampleRowsTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: SampleRowsTransform+ ) -> ibis.Table:return df.sample(transform.n / df.count().execute(),method="row",@@ -629,16 +630,16 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):@staticmethoddef handle_explode_columns(- df: "ibis.Table", transform: ExplodeColumnsTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: ExplodeColumnsTransform+ ) -> ibis.Table:for column_id in transform.column_ids:df = df.unnest(column_id)return df@staticmethoddef handle_expand_dict(- df: "ibis.Table", transform: ExpandDictTransform- ) -> "ibis.Table":+ df: ibis.Table, transform: ExpandDictTransform+ ) -> ibis.Table:return df.unpack(transform.column_id)# TODO: support as_python_code for Ibis@@ -651,7 +652,7 @@ class IbisTransformHandler(TransformHandler["ibis.Table"]):# )@staticmethod- def as_sql_code(transformed_df: "ibis.Table") -> str | None:+ def as_sql_code(transformed_df: ibis.Table) -> str | None:import ibistry:diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.py b/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.pyindex a1e1e040ef..c0ee9d5cfa 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/print_code.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Callable, List, Union+from typing import Any, Callable, Unionfrom marimo._plugins.ui._impl.dataframes.transforms.types import (Condition,@@ -13,12 +13,12 @@ from marimo._utils.assert_never import assert_neverdef python_print_transforms(df_name: str,- all_columns: List[str],- transforms: List[Transform],- print_transform: Callable[[str, List[str], Transform], str],+ all_columns: list[str],+ transforms: list[Transform],+ print_transform: Callable[[str, list[str], Transform], str],) -> str:df_next_name = f"{df_name}_next"- strs: List[str] = []+ strs: list[str] = []for transform in transforms:strs.append(f"{df_next_name} = {print_transform(df_next_name, all_columns, transform)}" # noqa: E501@@ -27,7 +27,7 @@ def python_print_transforms(def python_print_pandas(- df_name: str, all_columns: List[str], transform: Transform+ df_name: str, all_columns: list[str], transform: Transform) -> str:del all_columns@@ -182,7 +182,7 @@ def python_print_pandas(def python_print_polars(- df_name: str, all_columns: List[str], transform: Transform+ df_name: str, all_columns: list[str], transform: Transform) -> str:def generate_where_clause_polars(where: Condition) -> str:column_id, operator, value = (@@ -329,7 +329,7 @@ def python_print_polars(def python_print_ibis(- df_name: str, all_columns: List[str], transform: Transform+ df_name: str, all_columns: list[str], transform: Transform) -> str:del df_name, all_columns, transform# TODO: this does not fully work yet, but we can output the SQL for Ibis so@@ -478,7 +478,7 @@ def _as_literal(value: Any) -> str:return f"{value}"-def _list_of_strings(value: Union[List[Any], Any]) -> str:+def _list_of_strings(value: Union[list[Any], Any]) -> str:if isinstance(value, list):return f"[{', '.join(_as_literal(v) for v in value)}]"return _as_literal(value)diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/types.py b/marimo/_plugins/ui/_impl/dataframes/transforms/types.pyindex 1cf52d3e43..d2b6164e96 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/types.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/types.py@@ -7,7 +7,6 @@ from enum import Enumfrom typing import (Any,Generic,- List,Literal,Optional,TypeVar,@@ -18,7 +17,7 @@ from typing import (DataFrameType = TypeVar("DataFrameType")ColumnId = Union[str, int]-ColumnIds = List[ColumnId]+ColumnIds = list[ColumnId]NumpyDataType = strOperator = Literal["==",@@ -107,7 +106,7 @@ class SortColumnTransform:class FilterRowsTransform:type: Literal[TransformType.FILTER_ROWS]operation: Literal["keep_rows", "remove_rows"]- where: List[Condition]+ where: list[Condition]@dataclass@@ -122,7 +121,7 @@ class GroupByTransform:class AggregateTransform:type: Literal[TransformType.AGGREGATE]column_ids: ColumnIds- aggregations: List[Aggregation]+ aggregations: list[Aggregation]@dataclass@@ -174,7 +173,7 @@ Transform = Union[@dataclassclass Transformations:- transforms: List[Transform]+ transforms: list[Transform]T = TypeVar("T")@@ -240,7 +239,7 @@ class TransformHandler(abc.ABC, Generic[T]):@staticmethoddef as_python_code(- df_name: str, columns: List[str], transforms: List[Transform]+ df_name: str, columns: list[str], transforms: list[Transform]) -> str | None:del df_name, transforms, columnsreturn Nonediff --git a/marimo/_plugins/ui/_impl/dates.py b/marimo/_plugins/ui/_impl/dates.pyindex 01357a8d19..cfc5ee5abd 100644--- a/marimo/_plugins/ui/_impl/dates.py+++ b/marimo/_plugins/ui/_impl/dates.py@@ -7,7 +7,6 @@ from typing import (Callable,Final,Optional,- Tuple,Union,cast,)@@ -131,7 +130,7 @@ class date(UIElement[str, dt.date]):)@staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "date":+ def from_series(series: DataFrameSeries, **kwargs: Any) -> date:"""Create a date picker from a dataframe series.Args:@@ -267,7 +266,7 @@ class datetime(UIElement[Optional[str], Optional[dt.datetime]]):)@staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "datetime":+ def from_series(series: DataFrameSeries, **kwargs: Any) -> datetime:"""Create a datetime picker from a dataframe series.Args:@@ -324,7 +323,7 @@ class datetime(UIElement[Optional[str], Optional[dt.datetime]]):@mddoc-class date_range(UIElement[Tuple[str, str], Tuple[dt.date, dt.date]]):+class date_range(UIElement[tuple[str, str], tuple[dt.date, dt.date]]):"""A date range picker over an interval.Examples:@@ -362,10 +361,10 @@ class date_range(UIElement[Tuple[str, str], Tuple[dt.date, dt.date]]):self,start: Optional[dt.date | str] = None,stop: Optional[dt.date | str] = None,- value: Optional[Tuple[dt.date, dt.date] | Tuple[str, str]] = None,+ value: Optional[tuple[dt.date, dt.date] | tuple[str, str]] = None,*,label: Optional[str] = None,- on_change: Optional[Callable[[Tuple[dt.date, dt.date]], None]] = None,+ on_change: Optional[Callable[[tuple[dt.date, dt.date]], None]] = None,full_width: bool = False,):if isinstance(start, str):@@ -413,7 +412,7 @@ class date_range(UIElement[Tuple[str, str], Tuple[dt.date, dt.date]]):)@staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "date_range":+ def from_series(series: DataFrameSeries, **kwargs: Any) -> date_range:"""Create a date range picker from a dataframe series.Args:@@ -431,8 +430,8 @@ class date_range(UIElement[Tuple[str, str], Tuple[dt.date, dt.date]]):return date_range(start=start, stop=stop, label=label, **kwargs)def _convert_value(- self, value: Tuple[str, str] | Tuple[dt.date, dt.date]- ) -> Tuple[dt.date, dt.date]:+ self, value: tuple[str, str] | tuple[dt.date, dt.date]+ ) -> tuple[dt.date, dt.date]:return (self._convert_single_value(value[0]),self._convert_single_value(value[1]),diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.pyindex 1df4b74459..df866bc3e2 100644--- a/marimo/_plugins/ui/_impl/from_anywidget.py+++ b/marimo/_plugins/ui/_impl/from_anywidget.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport hashlibimport weakreffrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Dict, Optional+from typing import TYPE_CHECKING, Any, Optionalimport marimo._output.data.data as mo_datafrom marimo import _loggers@@ -24,17 +24,17 @@ LOGGER = _loggers.marimo_logger()# Weak dictionary# When the widget is deleted, the UIElement will be deleted as well-cache: Dict[Any, UIElement[Any, Any]] = weakref.WeakKeyDictionary() # type: ignore[no-untyped-call, unused-ignore, assignment] # noqa: E501+cache: dict[Any, UIElement[Any, Any]] = weakref.WeakKeyDictionary() # type: ignore[no-untyped-call, unused-ignore, assignment] # noqa: E501-def from_anywidget(widget: "AnyWidget") -> UIElement[Any, Any]:+def from_anywidget(widget: AnyWidget) -> UIElement[Any, Any]:"""Create a UIElement from an AnyWidget."""if widget not in cache:cache[widget] = anywidget(widget) # type: ignore[no-untyped-call, unused-ignore, assignment] # noqa: E501return cache[widget]-T = Dict[str, Any]+T = dict[str, Any]@dataclass@@ -75,7 +75,7 @@ class anywidget(UIElement[T, T]):widget (AnyWidget): The widget to wrap."""- def __init__(self, widget: "AnyWidget"):+ def __init__(self, widget: AnyWidget):self.widget = widget# This gets set to True in super().__init__()self._initialized = False@@ -163,7 +163,7 @@ class anywidget(UIElement[T, T]):def _initialize(self,initialization_args: InitializationArgs[- Dict[str, Any], Dict[str, Any]+ dict[str, Any], dict[str, Any]],) -> None:super()._initialize(initialization_args)diff --git a/marimo/_plugins/ui/_impl/from_panel.py b/marimo/_plugins/ui/_impl/from_panel.pyindex 405d1ca838..320d708cae 100644--- a/marimo/_plugins/ui/_impl/from_panel.py+++ b/marimo/_plugins/ui/_impl/from_panel.py@@ -7,11 +7,7 @@ from dataclasses import dataclassfrom typing import (TYPE_CHECKING,Any,- Dict,- List,Optional,- Tuple,- Type,TypeVar,cast,)@@ -29,21 +25,21 @@ LOGGER = _loggers.marimo_logger()COMM_MANAGER = MarimoCommManager()-comm_class: Optional[Type[Any]] = None+comm_class: Optional[type[Any]] = Noneloaded_extension: int = 0loaded_extensions: list[str] = []-T = TypeVar("T", bound=Dict[str, Any])+T = TypeVar("T", bound=dict[str, Any])@dataclassclass SendToWidgetArgs:message: Any- buffers: Optional[List[Any]] = None+ buffers: Optional[list[Any]] = None# Singleton, we only create one instance of this class-def _get_comm_class() -> Type[Any]:+def _get_comm_class() -> type[Any]:global comm_classif comm_class:return comm_class@@ -65,7 +61,7 @@ def _get_comm_class() -> Type[Any]:@classmethoddef decode(cls, msg: SendToWidgetArgs) -> dict[str, Any]:- buffers: Dict[int, Any] = {+ buffers: dict[int, Any] = {i: memoryview(base64.b64decode(v))for i, v in enumerate(msg.buffers or [])}@@ -148,7 +144,7 @@ def render_extension(load_timeout: int = 500, loaded: bool = False) -> str:def render_component(obj: Viewable,-) -> Tuple[str, dict[str, Any], dict[str, Any]]:+) -> tuple[str, dict[str, Any], dict[str, Any]]:"""Render a Panel component.diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex 7dbb91f32f..dae0ab0075 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -7,17 +7,14 @@ import osimport pathlibimport sysimport traceback+from collections.abc import Sequencefrom dataclasses import dataclassfrom typing import (Any,Callable,- Dict,Final,- List,Literal,Optional,- Sequence,- Tuple,TypeVar,Union,cast,@@ -137,7 +134,7 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):)@staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "number":+ def from_series(series: DataFrameSeries, **kwargs: Any) -> number:"""Create a number picker from a dataframe series."""info = get_number_series_info(series)start = kwargs.pop("start", info.min)@@ -209,7 +206,7 @@ class slider(UIElement[Numeric, Numeric]):"""_name: Final[str] = "marimo-slider"- _mapping: Optional[Dict[int, Numeric]] = None+ _mapping: Optional[dict[int, Numeric]] = Nonedef __init__(self,@@ -337,7 +334,7 @@ class slider(UIElement[Numeric, Numeric]):)@staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "slider":+ def from_series(series: DataFrameSeries, **kwargs: Any) -> slider:"""Create a slider from a dataframe series."""info = get_number_series_info(series)start = kwargs.pop("start", info.min)@@ -352,7 +349,7 @@ class slider(UIElement[Numeric, Numeric]):@mddoc-class range_slider(UIElement[List[Numeric], Sequence[Numeric]]):+class range_slider(UIElement[list[Numeric], Sequence[Numeric]]):"""A numeric slider for specifying a range over an interval.@@ -536,7 +533,7 @@ class range_slider(UIElement[List[Numeric], Sequence[Numeric]]):)@staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "range_slider":+ def from_series(series: DataFrameSeries, **kwargs: Any) -> range_slider:"""Create a range slider from a dataframe series."""info = get_number_series_info(series)start = kwargs.pop("start", info.min)@@ -544,7 +541,7 @@ class range_slider(UIElement[List[Numeric], Sequence[Numeric]]):label = kwargs.pop("label", info.label)return range_slider(start=start, stop=stop, label=label, **kwargs)- def _convert_value(self, value: List[Numeric]) -> Sequence[Numeric]:+ def _convert_value(self, value: list[Numeric]) -> Sequence[Numeric]:if self._mapping is not None:return cast(Sequence[Numeric],@@ -673,7 +670,7 @@ class radio(UIElement[Optional[str], Any]):)@staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "radio":+ def from_series(series: DataFrameSeries, **kwargs: Any) -> radio:"""Create a radio group from a dataframe series."""info = get_category_series_info(series)options = kwargs.pop("options", info.categories)@@ -887,7 +884,7 @@ class code_editor(UIElement[str, str]):@mddoc-class dropdown(UIElement[List[str], Any]):+class dropdown(UIElement[list[str], Any]):"""A dropdown selector.Examples:@@ -998,7 +995,7 @@ class dropdown(UIElement[List[str], Any]):)@staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "dropdown":+ def from_series(series: DataFrameSeries, **kwargs: Any) -> dropdown:"""Create a dropdown from a dataframe series."""info = get_category_series_info(series)options = kwargs.pop("options", info.categories)@@ -1021,7 +1018,7 @@ class dropdown(UIElement[List[str], Any]):@mddoc-class multiselect(UIElement[List[str], List[object]]):+class multiselect(UIElement[list[str], list[object]]):"""A multiselect input.Examples:@@ -1063,7 +1060,7 @@ class multiselect(UIElement[List[str], List[object]]):value: Optional[Sequence[str]] = None,*,label: str = "",- on_change: Optional[Callable[[List[object]], None]] = None,+ on_change: Optional[Callable[[list[object]], None]] = None,full_width: bool = False,max_selections: Optional[int] = None,) -> None:@@ -1105,7 +1102,7 @@ class multiselect(UIElement[List[str], List[object]]):)@staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "multiselect":+ def from_series(series: DataFrameSeries, **kwargs: Any) -> multiselect:"""Create a multiselect from a dataframe series."""info = get_category_series_info(series)options = kwargs.pop("options", info.categories)@@ -1203,8 +1200,7 @@ class button(UIElement[Any, Any]):return self._on_click(self._value)except Exception:sys.stderr.write(- "on_click handler for button (%s) raised an Exception:\n %s\n"- % (str(self), traceback.format_exc())+ f"on_click handler for button ({str(self)}) raised an Exception:\n {traceback.format_exc()}\n")return None@@ -1222,7 +1218,7 @@ class FileUploadResults:@mddoc-class file(UIElement[List[Tuple[str, str]], Sequence[FileUploadResults]]):+class file(UIElement[list[tuple[str, str]], Sequence[FileUploadResults]]):"""A button or drag-and-drop area to upload a file.Once a file is uploaded, the UI element's value is a list of namedtuples@@ -1377,11 +1373,11 @@ class ListDirectoryArgs:@dataclassclass ListDirectoryResponse:- files: List[FileInfo]+ files: list[FileInfo]@mddoc-class file_browser(UIElement[List[Dict[str, Any]], Sequence[FileInfo]]):+class file_browser(UIElement[list[dict[str, Any]], Sequence[FileInfo]]):"""File browser for browsing and selecting server-side files.Examples:@@ -1513,7 +1509,7 @@ class file_browser(UIElement[List[Dict[str, Any]], Sequence[FileInfo]]):return ListDirectoryResponse(files)def _convert_value(- self, value: list[Dict[str, Any]]+ self, value: list[dict[str, Any]]) -> Sequence[FileInfo]:return tuple(FileInfo(diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.pyindex 7c9af46009..5db55d44e9 100644--- a/marimo/_plugins/ui/_impl/plotly.py+++ b/marimo/_plugins/ui/_impl/plotly.py@@ -6,9 +6,7 @@ from typing import (TYPE_CHECKING,Any,Callable,- Dict,Final,- List,Optional,cast,)@@ -36,11 +34,11 @@ if TYPE_CHECKING:# },# "indices": int[],# }-PlotlySelection = Dict[str, JSONType]+PlotlySelection = dict[str, JSONType]@mddoc-class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):+class plotly(UIElement[PlotlySelection, list[dict[str, Any]]]):"""Make reactive plots with Plotly.Use `mo.ui.plotly` to make plotly plots reactive: select data with your@@ -104,7 +102,7 @@ class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):def __init__(self,figure: go.Figure,- config: Optional[Dict[str, Any]] = None,+ config: Optional[dict[str, Any]] = None,renderer_name: Optional[str] = None,*,label: str = "",@@ -116,7 +114,7 @@ class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):json_str = pio.to_json(figure)- resolved_config: Dict[str, Any] = {}+ resolved_config: dict[str, Any] = {}if config is not None:resolved_config = configelse:@@ -149,7 +147,7 @@ class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):)@property- def ranges(self) -> Dict[str, List[float]]:+ def ranges(self) -> dict[str, list[float]]:"""Get the range selection of the plot.Returns:@@ -164,7 +162,7 @@ class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):return self._selection_data["range"] # type:ignore@property- def points(self) -> List[Dict[str, Any]]:+ def points(self) -> list[dict[str, Any]]:"""Get the selected points data from the plot.Returns:@@ -178,7 +176,7 @@ class plotly(UIElement[PlotlySelection, List[Dict[str, Any]]]):return self._selection_data["points"] # type:ignore@property- def indices(self) -> List[int]:+ def indices(self) -> list[int]:"""Get the indices of selected points in the plot.Returns:diff --git a/marimo/_plugins/ui/_impl/refresh.py b/marimo/_plugins/ui/_impl/refresh.pyindex 2c3f09cb9a..3e2387a175 100644--- a/marimo/_plugins/ui/_impl/refresh.py+++ b/marimo/_plugins/ui/_impl/refresh.py@@ -63,7 +63,7 @@ class refresh(UIElement[int, int]):):raise ValueError("Invalid type: `default_interval` must be "- + "an int, float or str, not %s" % type(default_interval)+ + f"an int, float or str, not {type(default_interval)}")# If no options are provided and default_interval is provided,@@ -74,8 +74,7 @@ class refresh(UIElement[int, int]):if not isinstance(resolved_options, list):raise ValueError(- "Invalid type: `options` must be a list, not %s"- % type(resolved_options)+ f"Invalid type: `options` must be a list, not {type(resolved_options)}")# If has options and default_interval is provided,@@ -87,7 +86,7 @@ class refresh(UIElement[int, int]):):raise ValueError("Invalid value: `default_interval` must be "- + "one of the options, not %s" % default_interval+ + f"one of the options, not {default_interval}")super().__init__(diff --git a/marimo/_plugins/ui/_impl/switch.py b/marimo/_plugins/ui/_impl/switch.pyindex 461766c75f..c845988fdb 100644--- a/marimo/_plugins/ui/_impl/switch.py+++ b/marimo/_plugins/ui/_impl/switch.py@@ -37,12 +37,11 @@ class switch(UIElement[bool, bool]):) -> None:if not isinstance(value, bool):raise ValueError(- "Invalid type: `value` must be a bool, but got %s"- % type(value)+ f"Invalid type: `value` must be a bool, but got {type(value)}")if not isinstance(label, str):raise ValueError(- "Invalid type: `label` must be a str, but got %s" % type(label)+ f"Invalid type: `label` must be a str, but got {type(label)}")super().__init__(diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex d5b8a16c89..946b87b030 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -4,15 +4,12 @@ from __future__ import annotationsimport functoolsfrom dataclasses import dataclassfrom typing import (+ TYPE_CHECKING,Any,Callable,- Dict,Final,- List,Literal,Optional,- Sequence,- Set,Union,)@@ -50,6 +47,9 @@ from marimo._plugins.validators import (from marimo._runtime.functions import EmptyArgs, Functionfrom marimo._utils.narwhals_utils import unwrap_narwhals_dataframe+if TYPE_CHECKING:+ from collections.abc import Sequence+LOGGER = _loggers.marimo_logger()@@ -75,7 +75,7 @@ class ColumnSummary:@dataclassclass ColumnSummaries:data: Union[JSONType, str]- summaries: List[ColumnSummary]+ summaries: list[ColumnSummary]# Disabled because of too many columns/rows# This will show a banner in the frontendis_disabled: Optional[bool] = None@@ -87,7 +87,7 @@ class SearchTableArgs:page_number: intquery: Optional[str] = Nonesort: Optional[SortArgs] = None- filters: Optional[List[Condition]] = None+ filters: Optional[list[Condition]] = Nonelimit: Optional[int] = None@@ -106,7 +106,7 @@ class SortArgs:@mddocclass table(UIElement[- Union[List[str], List[int]], Union[List[JSONType], IntoDataFrame]+ Union[list[str], list[int]], Union[list[JSONType], IntoDataFrame]]):"""A table component with selectable rows.@@ -225,26 +225,26 @@ class table(self,data: Union[ListOrTuple[Union[str, int, float, bool, MIME, None]],- ListOrTuple[Dict[str, JSONType]],- Dict[str, ListOrTuple[JSONType]],- "IntoDataFrame",+ ListOrTuple[dict[str, JSONType]],+ dict[str, ListOrTuple[JSONType]],+ IntoDataFrame,],pagination: Optional[bool] = None,selection: Optional[Literal["single", "multi"]] = "multi",- initial_selection: Optional[List[int]] = None,+ initial_selection: Optional[list[int]] = None,page_size: int = 10,show_column_summaries: Optional[Union[bool, Literal["stats", "chart"]]] = None,format_mapping: Optional[- Dict[str, Union[str, Callable[..., Any]]]+ dict[str, Union[str, Callable[..., Any]]]] = None,freeze_columns_left: Optional[Sequence[str]] = None,freeze_columns_right: Optional[Sequence[str]] = None,text_justify_columns: Optional[- Dict[str, Literal["left", "center", "right"]]+ dict[str, Literal["left", "center", "right"]]] = None,- wrapped_columns: Optional[List[str]] = None,+ wrapped_columns: Optional[list[str]] = None,show_download: bool = True,max_columns: Optional[int] = 50,*,@@ -253,9 +253,9 @@ class table(Callable[[Union[- List[JSONType],- Dict[str, ListOrTuple[JSONType]],- "IntoDataFrame",+ list[JSONType],+ dict[str, ListOrTuple[JSONType]],+ IntoDataFrame,]],None,@@ -440,8 +440,8 @@ class table(return ""def _convert_value(- self, value: Union[List[int], List[str]]- ) -> Union[List[JSONType], "IntoDataFrame"]:+ self, value: Union[list[int], list[str]]+ ) -> Union[list[JSONType], IntoDataFrame]:indices = [int(v) for v in value]if self._has_stable_row_id:# Search across the original data@@ -523,7 +523,7 @@ class table()# Get column summaries if not chart-only mode- summaries: List[ColumnSummary] = []+ summaries: list[ColumnSummary] = []if self._show_column_summaries != "chart":for column in self._manager.get_column_names():try:@@ -565,7 +565,7 @@ class table(@functools.lru_cache(maxsize=1) # noqa: B019def _apply_filters_query_sort(self,- filters: Optional[List[Condition]],+ filters: Optional[list[Condition]],query: Optional[str],sort: Optional[SortArgs],) -> TableManager[Any]:@@ -669,8 +669,8 @@ class table(def _get_clamped_field_types(- field_types: List[Any], max_columns: Optional[int]-) -> List[Any]:+ field_types: list[Any], max_columns: Optional[int]+) -> list[Any]:if max_columns is not None and len(field_types) > max_columns:return field_types[:max_columns]return field_types@@ -679,7 +679,7 @@ def _get_clamped_field_types(def _validate_frozen_columns(freeze_columns_left: Optional[Sequence[str]],freeze_columns_right: Optional[Sequence[str]],- column_names_set: Set[str],+ column_names_set: set[str],) -> None:"""Validate frozen column configurations.@@ -718,10 +718,10 @@ def _validate_frozen_columns(def _validate_column_formatting(text_justify_columns: Optional[- Dict[str, Literal["left", "center", "right"]]+ dict[str, Literal["left", "center", "right"]]],- wrapped_columns: Optional[List[str]],- column_names_set: Set[str],+ wrapped_columns: Optional[list[str]],+ column_names_set: set[str],) -> None:"""Validate text justification and wrapped column configurations.diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.pyindex 48f1b0e732..c96ef6e75c 100644--- a/marimo/_plugins/ui/_impl/tables/default_table.py+++ b/marimo/_plugins/ui/_impl/tables/default_table.py@@ -1,13 +1,10 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from collections.abc import Sequencefrom typing import (Any,- Dict,- List,Optional,- Sequence,- Tuple,Union,cast,)@@ -37,9 +34,9 @@ from marimo._plugins.ui._impl.tables.table_manager import (JsonTableData = Union[Sequence[Union[str, int, float, bool, MIME, None]],Sequence[JSONType],- List[JSONType],- Dict[str, Sequence[Union[str, int, float, bool, MIME, None]]],- Dict[str, JSONType],+ list[JSONType],+ dict[str, Sequence[Union[str, int, float, bool, MIME, None]]],+ dict[str, JSONType],]@@ -105,12 +102,12 @@ class DefaultTableManager(TableManager[JsonTableData]):).to_json()return self._as_table_manager().to_json()- def select_rows(self, indices: List[int]) -> DefaultTableManager:+ def select_rows(self, indices: list[int]) -> DefaultTableManager:if isinstance(self.data, dict):# Column major dataif self.is_column_oriented:- new_data: Dict[Any, Any] = {- key: [cast(List[JSONType], value)[i] for i in indices]+ new_data: dict[Any, Any] = {+ key: [cast(list[JSONType], value)[i] for i in indices]for key, value in self.data.items()}return DefaultTableManager(new_data)@@ -121,11 +118,11 @@ class DefaultTableManager(TableManager[JsonTableData]):# Row major datareturn DefaultTableManager([self.data[i] for i in indices])- def select_columns(self, columns: List[str]) -> DefaultTableManager:+ def select_columns(self, columns: list[str]) -> DefaultTableManager:column_set = set(columns)# Column major dataif isinstance(self.data, dict):- new_data: Dict[str, Any] = {+ new_data: dict[str, Any] = {key: valuefor key, value in self.data.items()if key in column_set@@ -156,7 +153,7 @@ class DefaultTableManager(TableManager[JsonTableData]):cast(JsonTableData,{- key: cast(List[Any], value)[+ key: cast(list[Any], value)[offset : offset + count]for key, value in self.data.items()@@ -171,16 +168,16 @@ class DefaultTableManager(TableManager[JsonTableData]):def search(self, query: str) -> DefaultTableManager:query = query.lower()if isinstance(self.data, dict) and self.is_column_oriented:- mask: List[bool] = [+ mask: list[bool] = [any(- query in str(cast(List[Any], self.data[key])[row]).lower()+ query in str(cast(list[Any], self.data[key])[row]).lower()for key in self.data.keys())for row in range(self.get_num_rows() or 0)]results = {key: [- cast(List[Any], value)[i]+ cast(list[Any], value)[i]for i, match in enumerate(mask)if match]@@ -200,7 +197,7 @@ class DefaultTableManager(TableManager[JsonTableData]):def get_field_type(self, column_name: str- ) -> Tuple[FieldType, ExternalDataType]:+ ) -> tuple[FieldType, ExternalDataType]:del column_namereturn ("unknown", "object")@@ -237,7 +234,7 @@ class DefaultTableManager(TableManager[JsonTableData]):if isinstance(self.data, dict):if self.is_column_oriented:first = next(iter(self.data.values()), None)- return len(cast(List[Any], first))+ return len(cast(list[Any], first))else:return len(self.data)return len(self.data)@@ -245,7 +242,7 @@ class DefaultTableManager(TableManager[JsonTableData]):def get_num_columns(self) -> int:return len(self.data) if isinstance(self.data, dict) else 1- def get_column_names(self) -> List[str]:+ def get_column_names(self) -> list[str]:if isinstance(self.data, dict):return list(self.data.keys())first = next(iter(self.data), None)@@ -264,7 +261,7 @@ class DefaultTableManager(TableManager[JsonTableData]):) -> DefaultTableManager:if isinstance(self.data, dict) and self.is_column_oriented:# For column-oriented data, extract the sort column and get sorted indices- sort_column = cast(List[Any], self.data[by])+ sort_column = cast(list[Any], self.data[by])try:sorted_indices = sorted(range(len(sort_column)),@@ -284,7 +281,7 @@ class DefaultTableManager(TableManager[JsonTableData]):JsonTableData,{col: [- cast(List[Any], values)[i] for i in sorted_indices+ cast(list[Any], values)[i] for i in sorted_indices]for col, values in self.data.items()},@@ -348,10 +345,10 @@ class DefaultTableManager(TableManager[JsonTableData]):# we're going to assume that data has the right shape, after# having checked just the first entry- casted = cast(List[Union[str, int, float, bool, MIME, None]], data)+ casted = cast(list[Union[str, int, float, bool, MIME, None]], data)return [{"value": datum} for datum in casted]# Sequence of dicts- return cast(List[Dict[str, Any]], data)+ return cast(list[dict[str, Any]], data)def _is_column_oriented(data: JsonTableData) -> bool:diff --git a/marimo/_plugins/ui/_impl/tables/format.py b/marimo/_plugins/ui/_impl/tables/format.pyindex 9f66cf9445..a31e833e9c 100644--- a/marimo/_plugins/ui/_impl/tables/format.py+++ b/marimo/_plugins/ui/_impl/tables/format.py@@ -1,14 +1,14 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Callable, Dict, List, Union+from typing import Callable, Unionfrom marimo import _loggersfrom marimo._plugins.core.web_component import JSONTypeLOGGER = _loggers.marimo_logger()-FormatMapping = Dict[str, Union[str, Callable[..., JSONType]]]+FormatMapping = dict[str, Union[str, Callable[..., JSONType]]]def format_value(@@ -50,8 +50,8 @@ def format_value(def format_row(- row: Dict[str, JSONType], format_mapping: FormatMapping-) -> Dict[str, JSONType]:+ row: dict[str, JSONType], format_mapping: FormatMapping+) -> dict[str, JSONType]:# Return None if the format mapping is Noneif format_mapping is None:return row@@ -63,8 +63,8 @@ def format_row(def format_column(- col: str, values: List[JSONType], format_mapping: FormatMapping-) -> List[JSONType]:+ col: str, values: list[JSONType], format_mapping: FormatMapping+) -> list[JSONType]:# Return None if the format mapping is Noneif format_mapping is None:return valuesdiff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.pyindex 9c55ef6128..82728d1d2c 100644--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Optional, Tuple+from typing import Any, Optionalfrom marimo._data.models import (ColumnSummary,@@ -183,7 +183,7 @@ class IbisTableManagerFactory(TableManagerFactory):def get_field_type(self, column_name: str- ) -> Tuple[FieldType, ExternalDataType]:+ ) -> tuple[FieldType, ExternalDataType]:column = self.data[column_name]dtype = column.type()if dtype.is_string():diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.pyindex 2051adcec5..029797907b 100644--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport jsonfrom functools import cached_property-from typing import Any, Optional, Tuple, Union, cast+from typing import Any, Optional, Union, castimport narwhals.stable.v1 as nwfrom narwhals.stable.v1.typing import IntoFrameT@@ -118,7 +118,7 @@ class NarwhalsTableManager(def get_field_type(self, column_name: str- ) -> Tuple[FieldType, ExternalDataType]:+ ) -> tuple[FieldType, ExternalDataType]:dtype = self.nw_schema[column_name]dtype_string = str(dtype)if is_narwhals_string_type(dtype):diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex 74289740cf..6751dbc889 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport iofrom functools import cached_property-from typing import Any, Optional, Tuple+from typing import Any, Optionalimport narwhals.stable.v1 as nw@@ -125,7 +125,7 @@ class PandasTableManagerFactory(TableManagerFactory):# internal fields since they get displayed in the UI.def get_field_type(self, column_name: str- ) -> Tuple[FieldType, ExternalDataType]:+ ) -> tuple[FieldType, ExternalDataType]:dtype = self.schema[column_name]# If a df has duplicate columns, it won't be a series, but# a dataframe. In this case, we take the dtype of the columnsdiff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 272be98aae..c0c2a5a64a 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport iofrom functools import cached_property-from typing import Any, Optional, Tuple, Union+from typing import Any, Optional, Unionimport narwhals.stable.v1 as nw@@ -174,7 +174,7 @@ class PolarsTableManagerFactory(TableManagerFactory):# internal fields since they get displayed in the UI.def get_field_type(self, column_name: str- ) -> Tuple[FieldType, ExternalDataType]:+ ) -> tuple[FieldType, ExternalDataType]:dtype = self.schema[column_name]try:dtype_string = dtype._string_repr()diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.pyindex 5e27e5b9e5..a54d513ab8 100644--- a/marimo/_plugins/ui/_impl/tables/table_manager.py+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py@@ -6,7 +6,6 @@ from typing import (Any,Generic,Optional,- Tuple,TypeVar,)@@ -19,7 +18,7 @@ T = TypeVar("T")ColumnName = strFieldType = DataType-FieldTypes = list[Tuple[ColumnName, Tuple[FieldType, ExternalDataType]]]+FieldTypes = list[tuple[ColumnName, tuple[FieldType, ExternalDataType]]]class TableManager(abc.ABC, Generic[T]):@@ -109,7 +108,7 @@ class TableManager(abc.ABC, Generic[T]):@abc.abstractmethoddef get_field_type(self, column_name: str- ) -> Tuple[FieldType, ExternalDataType]:+ ) -> tuple[FieldType, ExternalDataType]:passdef get_field_types(self) -> FieldTypes:diff --git a/marimo/_plugins/ui/_impl/tables/utils.py b/marimo/_plugins/ui/_impl/tables/utils.pyindex 03ef4fb8b5..7b8e3e9fdf 100644--- a/marimo/_plugins/ui/_impl/tables/utils.py+++ b/marimo/_plugins/ui/_impl/tables/utils.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, List+from typing import Anyfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.ui._impl.tables.default_table import DefaultTableManager@@ -19,7 +19,7 @@ from marimo._plugins.ui._impl.tables.table_manager import ()from marimo._utils.narwhals_utils import can_narwhalify-MANAGERS: List[TableManagerFactory] = [+MANAGERS: list[TableManagerFactory] = [PandasTableManagerFactory(),PolarsTableManagerFactory(),IbisTableManagerFactory(),diff --git a/marimo/_plugins/ui/_impl/utils/dataframe.py b/marimo/_plugins/ui/_impl/utils/dataframe.pyindex fd506a9a83..5cd2ccc7fe 100644--- a/marimo/_plugins/ui/_impl/utils/dataframe.py+++ b/marimo/_plugins/ui/_impl/utils/dataframe.py@@ -2,9 +2,6 @@from __future__ import annotationsfrom typing import (- Dict,- List,- Tuple,TypeVar,Union,)@@ -19,13 +16,13 @@ LOGGER = _loggers.marimo_logger()T = TypeVar("T")Numeric = Union[int, float]-ListOrTuple = Union[List[T], Tuple[T, ...]]+ListOrTuple = Union[list[T], tuple[T, ...]]TableData = Union[- List[JSONType],+ list[JSONType],ListOrTuple[Union[str, int, float, bool, MIME, None]],- ListOrTuple[Dict[str, JSONType]],- Dict[str, ListOrTuple[JSONType]],+ ListOrTuple[dict[str, JSONType]],+ dict[str, ListOrTuple[JSONType]],IntoDataFrame,]diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.pyindex ea44df803a..9890cb2a2d 100644--- a/marimo/_pyodide/streams.py+++ b/marimo/_pyodide/streams.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport asyncioimport sys-from typing import Any, Callable, Iterable, Optional+from typing import TYPE_CHECKING, Any, Callable, Optionalfrom marimo import _loggersfrom marimo._messaging.cell_output import CellChannel, CellOutput@@ -19,6 +19,9 @@ from marimo._messaging.types import ()from marimo._types.ids import CellId_t+if TYPE_CHECKING:+ from collections.abc import Iterable+LOGGER = _loggers.marimo_logger()@@ -60,7 +63,7 @@ class PyodideStdout(Stdout):assert self.stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(- "write() argument must be a str, not %s" % type(data).__name__+ f"write() argument must be a str, not {type(data).__name__}")max_bytes = std_stream_max_bytes()if sys.getsizeof(data) > max_bytes:@@ -105,7 +108,7 @@ class PyodideStderr(Stderr):assert self.stream.cell_id is not Noneif not isinstance(data, str):raise TypeError(- "write() argument must be a str, not %s" % type(data).__name__+ f"write() argument must be a str, not {type(data).__name__}")max_bytes = std_stream_max_bytes()if sys.getsizeof(data) > max_bytes:@@ -148,7 +151,7 @@ class PyodideStdin(Stdin):assert self.stream.cell_id is not Noneif not isinstance(prompt, str):raise TypeError(- "prompt must be a str, not %s" % type(prompt).__name__+ f"prompt must be a str, not {type(prompt).__name__}")max_bytes = std_stream_max_bytes()if sys.getsizeof(prompt) > max_bytes:diff --git a/marimo/_runtime/app/common.py b/marimo/_runtime/app/common.pyindex 0b2a222902..56fca65f21 100644--- a/marimo/_runtime/app/common.py+++ b/marimo/_runtime/app/common.py@@ -1,11 +1,11 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Dict, Tuple+from typing import Anyfrom marimo._types.ids import CellId_t-OutputsType = Dict[CellId_t, Any]-DefsType = Dict[str, Any]+OutputsType = dict[CellId_t, Any]+DefsType = dict[str, Any]-RunOutput = Tuple[OutputsType, DefsType]+RunOutput = tuple[OutputsType, DefsType]diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.pyindex de60866322..83e0767c18 100644--- a/marimo/_runtime/app/script_runner.py+++ b/marimo/_runtime/app/script_runner.py@@ -2,7 +2,7 @@from __future__ import annotationsimport asyncio-from typing import TYPE_CHECKING, Any, Callable, Iterator+from typing import TYPE_CHECKING, Any, Callablefrom marimo._ast.cell import CellImplfrom marimo._dependencies.dependencies import DependencyManager@@ -28,6 +28,8 @@ from marimo._runtime.patches import (from marimo._types.ids import CellId_tif TYPE_CHECKING:+ from collections.abc import Iterator+from marimo._ast.app import InternalAppdiff --git a/marimo/_runtime/capture.py b/marimo/_runtime/capture.pyindex a47e6a73bb..3d0601699c 100644--- a/marimo/_runtime/capture.py+++ b/marimo/_runtime/capture.py@@ -2,7 +2,7 @@import contextlibimport ioimport sys-from typing import Iterator+from collections.abc import Iteratorfrom marimo._plugins.stateless.plain_text import plain_textfrom marimo._runtime.output import _outputdiff --git a/marimo/_runtime/cell_lifecycle_item.py b/marimo/_runtime/cell_lifecycle_item.pyindex 14eeb89d79..45d23ce929 100644--- a/marimo/_runtime/cell_lifecycle_item.py+++ b/marimo/_runtime/cell_lifecycle_item.py@@ -10,7 +10,7 @@ if TYPE_CHECKING:class CellLifecycleItem(abc.ABC):@abc.abstractmethod- def create(self, context: "RuntimeContext") -> None:+ def create(self, context: RuntimeContext) -> None:"""Create this itemThis method is executed at the beginning of a cell's lifecycle.@@ -19,7 +19,7 @@ class CellLifecycleItem(abc.ABC):...@abc.abstractmethod- def dispose(self, context: "RuntimeContext", deletion: bool) -> bool:+ def dispose(self, context: RuntimeContext, deletion: bool) -> bool:"""Dispose this itemThis method is executed at the end of a cell's lifecycle. Usediff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.pyindex c7125c1e6d..ff2331e476 100644--- a/marimo/_runtime/context/kernel_context.py+++ b/marimo/_runtime/context/kernel_context.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom contextlib import contextmanagerfrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Iterator, Optional+from typing import TYPE_CHECKING, Any, Optionalfrom marimo._ast.app import AppKernelRunnerRegistryfrom marimo._config.config import MarimoConfig@@ -21,6 +21,8 @@ from marimo._runtime.params import CLIArgs, QueryParamsfrom marimo._server.model import SessionModeif TYPE_CHECKING:+ from collections.abc import Iterator+from marimo._ast.app import InternalAppfrom marimo._messaging.types import Streamfrom marimo._runtime.runtime import Kerneldiff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.pyindex cb0417492a..244c3ac2e9 100644--- a/marimo/_runtime/context/script_context.py+++ b/marimo/_runtime/context/script_context.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport sysfrom contextlib import contextmanagerfrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Iterator, Optional+from typing import TYPE_CHECKING, Any, Optionalfrom marimo._ast.app import AppKernelRunnerRegistryfrom marimo._cli.parse_args import args_from_argv@@ -28,6 +28,8 @@ from marimo._runtime.patches import (from marimo._runtime.state import State, StateRegistryif TYPE_CHECKING:+ from collections.abc import Iterator+from marimo._ast.app import InternalAppfrom marimo._messaging.types import Streamfrom marimo._types.ids import CellId_tdiff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.pyindex a9f2de1083..56a9390e93 100644--- a/marimo/_runtime/context/types.py+++ b/marimo/_runtime/context/types.py@@ -10,7 +10,7 @@ import abcimport threadingfrom contextlib import contextmanagerfrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Iterator, Optional+from typing import TYPE_CHECKING, Any, Optionalfrom marimo._config.config import MarimoConfigfrom marimo._messaging.context import HTTP_REQUEST_CTX@@ -21,6 +21,8 @@ from marimo._runtime.functions import FunctionRegistryfrom marimo._runtime.requests import HTTPRequestif TYPE_CHECKING:+ from collections.abc import Iterator+from marimo._ast.app import AppKernelRunnerRegistry, InternalAppfrom marimo._messaging.types import Streamfrom marimo._output.hypertext import Htmldiff --git a/marimo/_runtime/context/utils.py b/marimo/_runtime/context/utils.pyindex 518cec1b46..2cf8750bf0 100644--- a/marimo/_runtime/context/utils.py+++ b/marimo/_runtime/context/utils.py@@ -2,7 +2,7 @@from __future__ import annotationsimport os-from typing import TYPE_CHECKING, Literal, Optional, Type+from typing import TYPE_CHECKING, Literal, Optionalfrom marimo._output.rich_help import mddocfrom marimo._runtime.context import ContextNotInitializedError, get_context@@ -74,7 +74,7 @@ class import_guard:def __exit__(self,- exception: Optional[Type[BaseException]],+ exception: Optional[type[BaseException]],instance: Optional[BaseException],_tracebacktype: Optional[TracebackType],) -> Literal[False]:diff --git a/marimo/_runtime/copy.py b/marimo/_runtime/copy.pyindex cb7eaaacf2..b832124991 100644--- a/marimo/_runtime/copy.py+++ b/marimo/_runtime/copy.py@@ -8,7 +8,6 @@ from typing import (Any,Callable,Generic,- Type,TypeVar,Union,cast,@@ -48,7 +47,7 @@ def _ro_fail() -> None:)-def shadow_wrap(ref_cls: Type[_Copy[T]], base: T) -> T:+def shadow_wrap(ref_cls: type[_Copy[T]], base: T) -> T:"""Wraps the base object by copying all attributes over to slots, and the thenrestricting write access to the object attributes / items directly. This isdiff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.pyindex b02c066296..14daa0c9d3 100644--- a/marimo/_runtime/dataflow.py+++ b/marimo/_runtime/dataflow.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport threadingfrom dataclasses import dataclass, field-from typing import TYPE_CHECKING, Any, Callable, List, Literal, Optional, Tuple+from typing import TYPE_CHECKING, Any, Callable, Literal, Optionalfrom marimo import _loggersfrom marimo._ast.cell import (@@ -19,13 +19,13 @@ if TYPE_CHECKING:from collections.abc import Collection-Edge = Tuple[CellId_t, CellId_t]+Edge = tuple[CellId_t, CellId_t]# EdgeWithVar uses a list rather than a set for the variables linking the cells# as sets are not JSON-serializable (required by static_notebook_template()).# The first entry is the source node; the second entry is a list of defs from# the source read by the destination; and the third entry is the destination# node.-EdgeWithVar = Tuple[CellId_t, List[str], CellId_t]+EdgeWithVar = tuple[CellId_t, list[str], CellId_t]LOGGER = _loggers.marimo_logger()diff --git a/marimo/_runtime/exceptions.py b/marimo/_runtime/exceptions.pyindex c3207c4deb..0fefc8530f 100644--- a/marimo/_runtime/exceptions.py+++ b/marimo/_runtime/exceptions.py@@ -20,6 +20,6 @@ class MarimoMissingRefError(BaseException):def __init__(self, ref: str, name_error: Optional[NameError] = None) -> None:- super(MarimoMissingRefError, self).__init__(ref)+ super().__init__(ref)self.ref = refself.name_error = name_errordiff --git a/marimo/_runtime/executor.py b/marimo/_runtime/executor.pyindex b5bde48b05..e41d0d80c0 100644--- a/marimo/_runtime/executor.py+++ b/marimo/_runtime/executor.py@@ -5,7 +5,7 @@ import inspectimport refrom abc import ABC, abstractmethodfrom copy import deepcopy-from typing import TYPE_CHECKING, Any, Callable, Optional, Type+from typing import TYPE_CHECKING, Any, Callable, Optionalfrom marimo._ast.cell import CellImpl, _is_coroutinefrom marimo._ast.variables import is_mangled_local, unmangle_local@@ -31,7 +31,7 @@ if TYPE_CHECKING:from marimo._runtime.dataflow import DirectedGraph-EXECUTION_TYPES: dict[str, Type[Executor]] = {}+EXECUTION_TYPES: dict[str, type[Executor]] = {}def raise_name_error(@@ -50,9 +50,9 @@ def raise_name_error(def register_execution_type(key: str,-) -> Callable[[Type[Executor]], Type[Executor]]:+) -> Callable[[type[Executor]], type[Executor]]:# Potentially expose as part of custom kernel API- def wrapper(cls: Type[Executor]) -> Type[Executor]:+ def wrapper(cls: type[Executor]) -> type[Executor]:EXECUTION_TYPES[key] = clsreturn clsdiff --git a/marimo/_runtime/functions.py b/marimo/_runtime/functions.pyindex 649e9eb4cf..21b22359a8 100644--- a/marimo/_runtime/functions.py+++ b/marimo/_runtime/functions.py@@ -4,12 +4,15 @@from __future__ import annotationsimport dataclasses-from typing import Any, Callable, Coroutine, Generic, Type, TypeVar+from typing import TYPE_CHECKING, Any, Callable, Generic, TypeVarfrom marimo._loggers import marimo_loggerfrom marimo._types.ids import CellId_tfrom marimo._utils.parse_dataclass import parse_raw+if TYPE_CHECKING:+ from collections.abc import Coroutine+LOGGER = marimo_logger()@@ -27,14 +30,14 @@ class EmptyArgs:@dataclasses.dataclassclass Function(Generic[S, T]):name: str- arg_cls: Type[S]+ arg_cls: type[S]function: Callable[[S], T] | Callable[[S], Coroutine[Any, Any, T]]cell_id: CellId_t | Nonedef __init__(self,name: str,- arg_cls: Type[S],+ arg_cls: type[S],function: Callable[[S], T],) -> None:from marimo._runtime.context import (diff --git a/marimo/_runtime/marimo_browser.py b/marimo/_runtime/marimo_browser.pyindex 8cf2114bea..cfe9165373 100644--- a/marimo/_runtime/marimo_browser.py+++ b/marimo/_runtime/marimo_browser.py@@ -75,7 +75,7 @@ def browser_open_fallback(return True-def build_browser_fallback() -> "type[webbrowser.BaseBrowser]":+def build_browser_fallback() -> type[webbrowser.BaseBrowser]:"""Dynamically create the class since BaseBrowser does not exist inpyodide.diff --git a/marimo/_runtime/packages/conda_package_manager.py b/marimo/_runtime/packages/conda_package_manager.pyindex dcdce9c6b3..2509933dda 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-from typing import List-from marimo._runtime.packages.module_name_to_conda_name import (module_name_to_conda_name,)@@ -30,7 +28,7 @@ class PixiPackageManager(CondaPackageManager):async def uninstall(self, package: str) -> bool:return self.run(["pixi", "remove", *split_packages(package)])- def list_packages(self) -> List[PackageDescription]:+ def list_packages(self) -> list[PackageDescription]:import jsonimport subprocessdiff --git a/marimo/_runtime/packages/package_manager.py b/marimo/_runtime/packages/package_manager.pyindex 2767b3cd6d..1f2740d26d 100644--- a/marimo/_runtime/packages/package_manager.py+++ b/marimo/_runtime/packages/package_manager.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport abcimport subprocessfrom dataclasses import dataclass-from typing import List, Optional+from typing import Optionalfrom marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager@@ -88,10 +88,10 @@ class PackageManager(abc.ABC):self,filepath: str,*,- packages_to_add: Optional[List[str]] = None,- packages_to_remove: Optional[List[str]] = None,- import_namespaces_to_add: Optional[List[str]] = None,- import_namespaces_to_remove: Optional[List[str]] = None,+ packages_to_add: Optional[list[str]] = None,+ packages_to_remove: Optional[list[str]] = None,+ import_namespaces_to_add: Optional[list[str]] = None,+ import_namespaces_to_remove: Optional[list[str]] = None,) -> None:del (filepath,@@ -113,7 +113,7 @@ class PackageManager(abc.ABC):return@abc.abstractmethod- def list_packages(self) -> List[PackageDescription]:+ def list_packages(self) -> list[PackageDescription]:"""List installed packages."""...diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.pyindex f650c3c058..b28a7ae04c 100644--- a/marimo/_runtime/packages/pypi_package_manager.py+++ b/marimo/_runtime/packages/pypi_package_manager.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport jsonimport subprocessimport sys-from typing import List, Optional+from typing import Optionalfrom marimo._runtime.packages.module_name_to_pypi_name import (module_name_to_pypi_name,@@ -24,8 +24,8 @@ class PypiPackageManager(CanonicalizingPackageManager):return module_name_to_pypi_name()def _list_packages_from_cmd(- self, cmd: List[str]- ) -> List[PackageDescription]:+ self, cmd: list[str]+ ) -> list[PackageDescription]:if not self.is_manager_installed():return []proc = subprocess.run(cmd, capture_output=True, text=True)@@ -62,7 +62,7 @@ class PipPackageManager(PypiPackageManager):])- def list_packages(self) -> List[PackageDescription]:+ def list_packages(self) -> list[PackageDescription]:cmd = ["pip", "--python", PY_EXE, "list", "--format=json"]return self._list_packages_from_cmd(cmd)@@ -97,7 +97,7 @@ class MicropipPackageManager(PypiPackageManager):except ValueError:return False- def list_packages(self) -> List[PackageDescription]:+ def list_packages(self) -> list[PackageDescription]:assert is_pyodide()import micropip # type: ignore@@ -125,10 +125,10 @@ class UvPackageManager(PypiPackageManager):self,filepath: str,*,- packages_to_add: Optional[List[str]] = None,- packages_to_remove: Optional[List[str]] = None,- import_namespaces_to_add: Optional[List[str]] = None,- import_namespaces_to_remove: Optional[List[str]] = None,+ packages_to_add: Optional[list[str]] = None,+ packages_to_remove: Optional[list[str]] = None,+ import_namespaces_to_add: Optional[list[str]] = None,+ import_namespaces_to_remove: Optional[list[str]] = None,) -> None:"""Update the notebook's script metadata with the packages to add/remove.@@ -197,7 +197,7 @@ class UvPackageManager(PypiPackageManager):["uv", "pip", "uninstall", *split_packages(package), "-p", PY_EXE])- def list_packages(self) -> List[PackageDescription]:+ def list_packages(self) -> list[PackageDescription]:cmd = ["uv", "pip", "list", "--format=json", "-p", PY_EXE]return self._list_packages_from_cmd(cmd)@@ -212,7 +212,7 @@ class RyePackageManager(PypiPackageManager):async def uninstall(self, package: str) -> bool:return self.run(["rye", "remove", *split_packages(package)])- def list_packages(self) -> List[PackageDescription]:+ def list_packages(self) -> list[PackageDescription]:cmd = ["rye", "list", "--format=json"]return self._list_packages_from_cmd(cmd)@@ -232,8 +232,8 @@ class PoetryPackageManager(PypiPackageManager):)def _list_packages_from_cmd(- self, cmd: List[str]- ) -> List[PackageDescription]:+ self, cmd: list[str]+ ) -> list[PackageDescription]:if not self.is_manager_installed():return []proc = subprocess.run(cmd, capture_output=True, text=True)@@ -256,6 +256,6 @@ class PoetryPackageManager(PypiPackageManager):)return packages- def list_packages(self) -> List[PackageDescription]:+ def list_packages(self) -> list[PackageDescription]:cmd = ["poetry", "show", "--no-dev"]return self._list_packages_from_cmd(cmd)diff --git a/marimo/_runtime/packages/utils.py b/marimo/_runtime/packages/utils.pyindex a46e475bdd..24697408c8 100644--- a/marimo/_runtime/packages/utils.py+++ b/marimo/_runtime/packages/utils.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport osimport sys-from typing import List, Optional+from typing import Optionalfrom marimo._utils.platform import is_pyodide@@ -48,7 +48,7 @@ def append_version(pkg_name: str, version: Optional[str]) -> str:return f"{pkg_name}=={version}"-def split_packages(package: str) -> List[str]:+def split_packages(package: str) -> list[str]:"""Splits a package string into a list of packages.@@ -64,8 +64,8 @@ def split_packages(package: str) -> List[str]:"package1 @ /path/to/package1" -> ["package1 @ /path/to/package1"]"foo==1.0; python_version>'3.6' bar==2.0; sys_platform=='win32'" -> ["foo==1.0; python_version>'3.6'", "bar==2.0; sys_platform=='win32'"]""" # noqa: E501- packages: List[str] = []- current_package: List[str] = []+ packages: list[str] = []+ current_package: list[str] = []in_environment_marker = Falsefor part in package.split():diff --git a/marimo/_runtime/params.py b/marimo/_runtime/params.pyindex 9f52e992a1..455e25b689 100644--- a/marimo/_runtime/params.py+++ b/marimo/_runtime/params.py@@ -1,7 +1,13 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Dict, Iterator, List, Optional, TypeVar, Union, overload+from typing import (+ TYPE_CHECKING,+ Optional,+ TypeVar,+ Union,+ overload,+)from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.ops import (@@ -20,6 +26,9 @@ from marimo._runtime.requests import ()from marimo._runtime.state import State, StateRegistry+if TYPE_CHECKING:+ from collections.abc import Iterator+@mddocclass QueryParams(State[SerializedQueryParams]):@@ -29,7 +38,7 @@ class QueryParams(State[SerializedQueryParams]):def __init__(self,- params: Dict[str, Union[str, List[str]]],+ params: dict[str, Union[str, list[str]]],stream: Optional[Stream] = None,_registry: Optional[StateRegistry] = None,):@@ -37,17 +46,17 @@ class QueryParams(State[SerializedQueryParams]):self._params = paramsself._stream = stream- T = TypeVar("T", str, List[str])+ T = TypeVar("T", str, list[str])@overload- def get(self, key: str) -> Optional[Union[str, List[str]]]: ...+ def get(self, key: str) -> Optional[Union[str, list[str]]]: ...@overload- def get(self, key: str, default: T) -> Union[str, List[str], T]: ...+ def get(self, key: str, default: T) -> Union[str, list[str], T]: ...def get(- self, key: str, default: Optional[Union[str, List[str]]] = None- ) -> Optional[Union[str, List[str]]]:+ self, key: str, default: Optional[Union[str, list[str]]] = None+ ) -> Optional[Union[str, list[str]]]:"""Get the value of the query parameter.Args:@@ -62,7 +71,7 @@ class QueryParams(State[SerializedQueryParams]):return defaultreturn self._params[key]- def get_all(self, key: str) -> List[str]:+ def get_all(self, key: str) -> list[str]:"""Get the value of a query parameter as a list."""value = self._params.get(key)if value is None:@@ -71,7 +80,7 @@ class QueryParams(State[SerializedQueryParams]):return valuereturn [value]- def __getitem__(self, key: str) -> Optional[Union[str, List[str]]]:+ def __getitem__(self, key: str) -> Optional[Union[str, list[str]]]:return self.get(key)def __contains__(self, key: str) -> bool:@@ -89,7 +98,7 @@ class QueryParams(State[SerializedQueryParams]):def __str__(self) -> str:return str(self._params)- def __setitem__(self, key: str, value: Union[str, List[str]]) -> None:+ def __setitem__(self, key: str, value: Union[str, list[str]]) -> None:if value is None or value == []: # type: ignoreself.remove(key)return@@ -103,7 +112,7 @@ class QueryParams(State[SerializedQueryParams]):QueryParamsDelete(key, None).broadcast(self._stream)self._set_value(self._params)- def set(self, key: str, value: Union[str, List[str]]) -> None:+ def set(self, key: str, value: Union[str, list[str]]) -> None:"""Set the value of a query parameter."""self[key] = value@@ -155,7 +164,7 @@ class QueryParams(State[SerializedQueryParams]):QueryParamsClear().broadcast(self._stream)self._set_value(self._params)- def to_dict(self) -> Dict[str, Union[str, List[str]]]:+ def to_dict(self) -> dict[str, Union[str, list[str]]]:return self._params@@ -169,7 +178,7 @@ class CLIArgs:):self._params = params- T = TypeVar("T", Primitive, List[Primitive])+ T = TypeVar("T", Primitive, list[Primitive])@overloaddef get(self, key: str) -> Optional[ListOrValue[Primitive]]: ...@@ -197,7 +206,7 @@ class CLIArgs:return defaultreturn self._params[key]- def get_all(self, key: str) -> List[Primitive]:+ def get_all(self, key: str) -> list[Primitive]:"""Get the value of a CLI arg as a list."""value = self._params.get(key)if value is None:diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.pyindex 877dd56d9e..a3049fb8f3 100644--- a/marimo/_runtime/patches.py+++ b/marimo/_runtime/patches.py@@ -6,10 +6,13 @@ import functoolsimport sysimport textwrapimport types-from typing import Any, Callable, Iterator+from typing import TYPE_CHECKING, Any, Callablefrom marimo._runtime import marimo_browser, marimo_pdb+if TYPE_CHECKING:+ from collections.abc import Iterator+def patch_pdb(debugger: marimo_pdb.MarimoPdb) -> None:import pdbdiff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.pyindex 82be28d42c..58e519ec61 100644--- a/marimo/_runtime/redirect_streams.py+++ b/marimo/_runtime/redirect_streams.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport contextlibimport osimport sys-from typing import Iterator+from typing import TYPE_CHECKINGfrom marimo._messaging.streams import (redirect,@@ -12,6 +12,9 @@ from marimo._messaging.streams import (from marimo._messaging.types import Stderr, Stdin, Stdout, Streamfrom marimo._types.ids import CellId_t+if TYPE_CHECKING:+ from collections.abc import Iterator+def forward_os_stream(stream_object: Stdout | Stderr, fd: int) -> None:while True:diff --git a/marimo/_runtime/reload/autoreload.py b/marimo/_runtime/reload/autoreload.pyindex ebabea986d..867226bd9b 100644--- a/marimo/_runtime/reload/autoreload.py+++ b/marimo/_runtime/reload/autoreload.py@@ -22,7 +22,7 @@ import weakreffrom dataclasses import dataclassfrom importlib import reloadfrom importlib.util import source_from_cache-from typing import Any, Callable, Dict, Generic, List, Tuple, Type, TypeVar+from typing import Any, Callable, Generic, TypeVarfrom marimo import _loggersfrom marimo._ast.cell import CellImpl@@ -47,8 +47,8 @@ class ModuleMTime:# (module-name, name) -> weakref, for replacing old code objects-OldObjectsMapping = Dict[- Tuple[str, str], List[weakref.ref] # type:ignore[type-arg]+OldObjectsMapping = dict[+ tuple[str, str], list[weakref.ref] # type:ignore[type-arg]]@@ -340,7 +340,7 @@ def update_property(old: object, new: object) -> None:update_generic(old.fset, new.fset) # type:ignore[attr-defined]-def isinstance2(a: object, b: object, typ: Type[Any]) -> bool:+def isinstance2(a: object, b: object, typ: type[Any]) -> bool:return isinstance(a, typ) and isinstance(b, typ)diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex 63eec4b655..29e90a73f6 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -3,16 +3,12 @@ from __future__ import annotationsimport timefrom collections import defaultdict+from collections.abc import Iterator, Mappingfrom dataclasses import asdict, dataclass, fieldfrom typing import (TYPE_CHECKING,Any,- Dict,- Iterator,- List,- Mapping,Optional,- Tuple,TypeVar,Union,)@@ -29,10 +25,10 @@ if TYPE_CHECKING:CompletionRequestId = strT = TypeVar("T")-ListOrValue = Union[T, List[T]]-SerializedQueryParams = Dict[str, ListOrValue[str]]+ListOrValue = Union[T, list[T]]+SerializedQueryParams = dict[str, ListOrValue[str]]Primitive = Union[str, bool, int, float]-SerializedCLIArgs = Dict[str, ListOrValue[Primitive]]+SerializedCLIArgs = dict[str, ListOrValue[Primitive]]@dataclass@@ -77,7 +73,7 @@ class HTTPRequest(Mapping[str, Any]):return f"HTTPRequest(path={self.url['path']}, params={len(self.query_params)})"@staticmethod- def from_request(request: HTTPConnection) -> "HTTPRequest":+ def from_request(request: HTTPConnection) -> HTTPRequest:def _url_to_dict(url: URL) -> dict[str, Any]:return {"path": url.path,@@ -141,9 +137,9 @@ class ExecuteStaleRequest: ...@dataclassclass ExecuteMultipleRequest:# ids of cells to run- cell_ids: List[CellId_t]+ cell_ids: list[CellId_t]# code to register/run for each cell- codes: List[str]+ codes: list[str]# incoming request, e.g. from Starlette or FastAPIrequest: Optional[HTTPRequest] = None# time at which the request was received@@ -153,7 +149,7 @@ class ExecuteMultipleRequest:return f"ExecuteMultipleRequest(cells={len(self.cell_ids)})"@property- def execution_requests(self) -> List[ExecutionRequest]:+ def execution_requests(self) -> list[ExecutionRequest]:return [ExecutionRequest(cell_id=cell_id,@@ -184,8 +180,8 @@ class RenameRequest:@dataclassclass SetUIElementValueRequest:- object_ids: List[UIElementId]- values: List[Any]+ object_ids: list[UIElementId]+ values: list[Any]# Incoming request, e.g. from Starlette or FastAPIrequest: Optional[HTTPRequest] = None# uniquely identifies the request@@ -201,7 +197,7 @@ class SetUIElementValueRequest:@staticmethoddef from_ids_and_values(- ids_and_values: List[Tuple[UIElementId, Any]],+ ids_and_values: list[tuple[UIElementId, Any]],request: Optional[HTTPRequest] = None,) -> SetUIElementValueRequest:if not ids_and_values:@@ -216,7 +212,7 @@ class SetUIElementValueRequest:)@property- def ids_and_values(self) -> List[Tuple[UIElementId, Any]]:+ def ids_and_values(self) -> list[tuple[UIElementId, Any]]:return list(zip(self.object_ids, self.values))@@ -225,7 +221,7 @@ class FunctionCallRequest:function_call_id: RequestIdnamespace: strfunction_name: str- args: Dict[str, Any]+ args: dict[str, Any]def __repr__(self) -> str:return f"FunctionCallRequest(id={self.function_call_id}, fn={self.namespace}.{self.function_name})"@@ -244,7 +240,7 @@ class AppMetadata:@dataclassclass SetCellConfigRequest:# Map from Cell ID to (possibly partial) CellConfig- configs: Dict[CellId_t, Dict[str, Any]]+ configs: dict[CellId_t, dict[str, Any]]@dataclass@@ -255,7 +251,7 @@ class SetUserConfigRequest:@dataclassclass CreationRequest:- execution_requests: Tuple[ExecutionRequest, ...]+ execution_requests: tuple[ExecutionRequest, ...]set_ui_element_value_request: SetUIElementValueRequestauto_run: boolrequest: Optional[HTTPRequest] = None@@ -289,7 +285,7 @@ class InstallMissingPackagesRequest:# Map from package name to desired version# If the package name is not in the map, the latest version# will be installed- versions: Dict[str, str]+ versions: dict[str, str]@dataclassdiff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.pyindex 9f65887d2c..a6e4a50d2d 100644--- a/marimo/_runtime/runner/cell_runner.py+++ b/marimo/_runtime/runner/cell_runner.py@@ -9,7 +9,7 @@ import signalimport threadingimport tracebackfrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, Union+from typing import TYPE_CHECKING, Any, Callable, Optional, Unionfrom marimo._ast.cell import CellImplfrom marimo._ast.variables import unmangle_local@@ -39,7 +39,7 @@ from marimo._types.ids import CellId_tLOGGER = marimo_logger()if TYPE_CHECKING:- from collections.abc import Sequence+ from collections.abc import Iterator, Sequencefrom marimo._runtime.context.types import ExecutionContextfrom marimo._runtime.runner.hooks_on_finish import OnFinishHookType@@ -100,16 +100,16 @@ class Runner:# injected context and hooksself.execution_context = execution_context- self.preparation_hooks: Sequence[Callable[["Runner"], Any]] = (+ self.preparation_hooks: Sequence[Callable[[Runner], Any]] = (preparation_hooks or [])self.pre_execution_hooks: Sequence[- Callable[[CellImpl, "Runner"], Any]+ Callable[[CellImpl, Runner], Any]] = pre_execution_hooks or []self.post_execution_hooks: Sequence[- Callable[[CellImpl, "Runner", RunResult], Any]+ Callable[[CellImpl, Runner, RunResult], Any]] = post_execution_hooks or []- self.on_finish_hooks: Sequence[Callable[["Runner"], Any]] = (+ self.on_finish_hooks: Sequence[Callable[[Runner], Any]] = (on_finish_hooks or [])diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex aa1ac75452..45773fcb23 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -322,8 +322,7 @@ def _broadcast_outputs(CellOp.broadcast_error(data=[MarimoExceptionRaisedError(- msg="This cell raised an exception: %s%s"- % (+ msg="This cell raised an exception: {}{}".format(exception_type,(f"('{str(run_result.exception)}')"diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 0020239ae9..c2f1000889 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -16,7 +16,7 @@ import timeimport tracebackfrom copy import copy, deepcopyfrom multiprocessing import connection-from typing import TYPE_CHECKING, Any, Callable, Iterator, List, Optional, cast+from typing import TYPE_CHECKING, Any, Callable, Optional, castfrom uuid import uuid4from marimo import _loggers@@ -148,7 +148,7 @@ from marimo._utils.typed_connection import TypedConnectionif TYPE_CHECKING:import queue- from collections.abc import Sequence+ from collections.abc import Iterator, Sequencefrom types import ModuleTypefrom marimo._plugins.ui._core.ui_element import UIElement@@ -1838,15 +1838,13 @@ class Kernel:return status, response, foundfound = Falseerror_title = "Function not found"- error_message = (- "Could not find function given request: %s" % request- )+ error_message = f"Could not find function given request: {request}"debug(error_title, error_message)elif function.cell_id is None:found = Trueerror_title = "Function not associated with cell"error_message = (- "Attempted to call a function without a cell id: %s" % request+ f"Attempted to call a function without a cell id: {request}")debug(error_title, error_message)else:@@ -1880,17 +1878,11 @@ class Kernel:)except MarimoInterrupt:error_title = "Interrupted"- error_message = (- "Function call (%s) was interrupted by the user"- % request.function_name- )+ error_message = f"Function call ({request.function_name}) was interrupted by the user"debug(error_title, error_message)except Exception as e:error_title = "Exception"- error_message = (- "Function call (name: %s, args: %s) failed with exception %s" # noqa: E501- % (request.function_name, request.args, str(e))- )+ error_message = f"Function call (name: {request.function_name}, args: {request.args}) failed with exception {str(e)}"debug(error_title, error_message)# Couldn't call function, or function call failed@@ -2006,7 +1998,7 @@ class Kernel:)def _update_script_metadata(- self, import_namespaces_to_add: List[str]+ self, import_namespaces_to_add: list[str]) -> None:filename = self.app_metadata.filenamediff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.pyindex 1e896dae33..5d13762132 100644--- a/marimo/_runtime/virtual_file.py+++ b/marimo/_runtime/virtual_file.py@@ -117,7 +117,7 @@ class VirtualFileLifecycleItem(CellLifecycleItem):assert self._virtual_file is not Nonereturn self._virtual_file- def create(self, context: "RuntimeContext" | None) -> None:+ def create(self, context: RuntimeContext | None) -> None:"""Create the virtual fileEvery virtual file gets a unique random name. Uniqueness is@@ -145,7 +145,7 @@ class VirtualFileLifecycleItem(CellLifecycleItem):self._virtual_file = VirtualFile(filename, self.buffer)context.virtual_file_registry.add(self._virtual_file, context)- def dispose(self, context: "RuntimeContext", deletion: bool) -> bool:+ def dispose(self, context: RuntimeContext, deletion: bool) -> bool:# Remove the file if the refcount is 0, or if the cell is being# deleted. (We can't rely on when the refcount will be decremented, so# we need to check for deletion explicitly to prevent leaks.)@@ -209,9 +209,7 @@ class VirtualFileRegistry:return self.registry[filename].refcountreturn 0- def add(- self, virtual_file: VirtualFile, context: "RuntimeContext"- ) -> None:+ def add(self, virtual_file: VirtualFile, context: RuntimeContext) -> None:if not context.virtual_files_supported:returndiff --git a/marimo/_runtime/win32_interrupt_handler.py b/marimo/_runtime/win32_interrupt_handler.pyindex a24058c99d..670bbbf46a 100644--- a/marimo/_runtime/win32_interrupt_handler.py+++ b/marimo/_runtime/win32_interrupt_handler.py@@ -11,7 +11,7 @@ if TYPE_CHECKING:class Win32InterruptHandler(threading.Thread):def __init__(self, interrupt_queue: "Queue[bool]") -> None:- super(Win32InterruptHandler, self).__init__()+ super().__init__()self.daemon = Trueself.interrupt_queue = interrupt_queuediff --git a/marimo/_save/ast.py b/marimo/_save/ast.pyindex 085c9ac1fe..e36da9b46e 100644--- a/marimo/_save/ast.py+++ b/marimo/_save/ast.py@@ -4,10 +4,13 @@ from __future__ import annotationsimport astimport inspectimport textwrap-from typing import Any, Callable, Sequence, cast+from typing import TYPE_CHECKING, Any, Callable, castfrom marimo._ast.variables import unmangle_local+if TYPE_CHECKING:+ from collections.abc import Sequence+ARG_PREFIX: str = "*"diff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex 605ba10a76..7dbde1ebc2 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -8,7 +8,7 @@ import inspectimport structimport sysimport types-from typing import TYPE_CHECKING, Any, Callable, Iterable, NamedTuple, Optional+from typing import TYPE_CHECKING, Any, Callable, NamedTuple, Optionalfrom marimo._ast.variables import (get_cell_from_local,@@ -32,6 +32,7 @@ from marimo._save.cache import Cache, CacheTypefrom marimo._types.ids import CellId_tif TYPE_CHECKING:+ from collections.abc import Iterablefrom types import CodeTypefrom marimo._ast.cell import CellImpldiff --git a/marimo/_save/loaders/loader.py b/marimo/_save/loaders/loader.pyindex bfa90f49a3..cf2ca3a687 100644--- a/marimo/_save/loaders/loader.py+++ b/marimo/_save/loaders/loader.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport osfrom abc import ABC, abstractmethodfrom pathlib import Path-from typing import TYPE_CHECKING, Any, Type+from typing import TYPE_CHECKING, Anyfrom marimo._runtime.context import get_contextfrom marimo._runtime.context.types import ContextNotInitializedError@@ -230,4 +230,4 @@ class BasePersistenceLoader(Loader):"""May throw FileNotFoundError"""-LoaderType = Type[Loader]+LoaderType = type[Loader]diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex 2353daa4a4..016109e22f 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -17,7 +17,6 @@ from typing import (Any,Callable,Optional,- Type,Union,cast,overload,@@ -67,7 +66,7 @@ class SkipWithBlock(Exception):"""Special exception to get around executing the with block body."""-class _cache_call(object):+class _cache_call:"""Like functools.cache but notebook-aware. See `cache` docstring`"""graph: DirectedGraph@@ -216,7 +215,7 @@ class _cache_call(object):return response-class _cache_context(object):+class _cache_context:def __init__(self,name: str,@@ -326,22 +325,20 @@ class _cache_context(object):"(cannot be in a function or class)")raise CacheException(- (- "`persistent_cache` could not resolve block"- f"{UNEXPECTED_FAILURE_BOILERPLATE}"- )+ "`persistent_cache` could not resolve block"+ f"{UNEXPECTED_FAILURE_BOILERPLATE}")def __exit__(self,- exception: Optional[Type[BaseException]],+ exception: Optional[type[BaseException]],instance: Optional[BaseException],_tracebacktype: Optional[TracebackType],) -> bool:sys.settrace(self._old_trace) # Clear to previous set trace.if not self._entered_trace:raise CacheException(- (f"Unexpected block format {UNEXPECTED_FAILURE_BOILERPLATE}")+ f"Unexpected block format {UNEXPECTED_FAILURE_BOILERPLATE}")# Backfill the loaded values into global scope.diff --git a/marimo/_schemas/session.py b/marimo/_schemas/session.pyindex 9713599152..1c495063b5 100644--- a/marimo/_schemas/session.py+++ b/marimo/_schemas/session.py@@ -1,7 +1,7 @@# Copyright 2025 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Dict, List, Literal, Optional, TypedDict, Union+from typing import Any, Literal, Optional, TypedDict, Union# Base types for extensibility@@ -29,12 +29,12 @@ class ErrorOutput(BaseDict):type: Literal["error"]ename: strevalue: str- traceback: List[str]+ traceback: list[str]class DataOutput(BaseDict):type: Literal["data"]- data: Dict[str, Any] # MIME-type bundles+ data: dict[str, Any] # MIME-type bundles# Union of all possible output types@@ -50,8 +50,8 @@ class Cell(BaseDict):id: strcode_hash: Optional[str]- outputs: List[OutputType]- console: List[StreamOutput]+ outputs: list[OutputType]+ console: list[StreamOutput]# We don't need to store code or cell config# since that exists in the notebook.py itself@@ -76,7 +76,7 @@ class NotebookSessionV1(BaseDict):# Metadata about the notebookmetadata: NotebookMetadata# The cells in the notebook- cells: List[Cell]+ cells: list[Cell]# In future, we may want to add# - variablesdiff --git a/marimo/_server/api/auth.py b/marimo/_server/api/auth.pyindex ee565a2465..5319286c40 100644--- a/marimo/_server/api/auth.py+++ b/marimo/_server/api/auth.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport base64import secretsimport typing-from typing import TYPE_CHECKING, Any, Dict, Optional+from typing import TYPE_CHECKING, Any, Optionalimport starletteimport starlette.status as status@@ -129,7 +129,7 @@ class CookieSession:Wrapper around starlette's Session to add typesafety"""- def __init__(self, session_state: Dict[str, Any]) -> None:+ def __init__(self, session_state: dict[str, Any]) -> None:self.session_state = session_statedef get_access_token(self) -> str:diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex c2708df713..83c551ceac 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, Any, Generator, Optional, cast+from typing import TYPE_CHECKING, Any, Optional, castfrom starlette.authentication import requiresfrom starlette.exceptions import HTTPException@@ -26,6 +26,8 @@ from marimo._server.models.completion import (from marimo._server.router import APIRouterif TYPE_CHECKING:+ from collections.abc import Generator+from anthropic import ( # type: ignore[import-not-found]Client,Stream as AnthropicStream,@@ -54,7 +56,7 @@ LOGGER = _loggers.marimo_logger()router = APIRouter()-def get_openai_client(config: MarimoConfig) -> "OpenAI":+def get_openai_client(config: MarimoConfig) -> OpenAI:try:from urllib.parse import parse_qs, urlparse@@ -117,7 +119,7 @@ def get_openai_client(config: MarimoConfig) -> "OpenAI":)-def get_anthropic_client(config: MarimoConfig) -> "Client":+def get_anthropic_client(config: MarimoConfig) -> Client:try:from anthropic import Client # type: ignore[import-not-found]except ImportError:@@ -267,7 +269,7 @@ def as_stream_response(LOGGER.debug(f"Completion content: {original_content}")-def get_google_client(config: MarimoConfig, model: str) -> "GenerativeModel":+def get_google_client(config: MarimoConfig, model: str) -> GenerativeModel:try:import google.generativeai as genai # type: ignore[import-not-found]except ImportError:diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.pyindex e4a9a75acc..3f4d7b3dbe 100644--- a/marimo/_server/api/endpoints/home.py+++ b/marimo/_server/api/endpoints/home.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport osimport tempfile-from typing import TYPE_CHECKING, List+from typing import TYPE_CHECKINGfrom starlette.authentication import requiresfrom starlette.responses import JSONResponse@@ -93,8 +93,8 @@ async def workspace_files(return WorkspaceFilesResponse(files=files, root=root)-def _get_active_sessions(app_state: AppState) -> List[MarimoFile]:- files: List[MarimoFile] = []+def _get_active_sessions(app_state: AppState) -> list[MarimoFile]:+ files: list[MarimoFile] = []for session_id, session in app_state.session_manager.sessions.items():state = session.connection_state()if state == ConnectionState.OPEN or state == ConnectionState.ORPHANED:diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex 4fd6a17d16..2c256dd5b6 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -369,7 +369,7 @@ class WebsocketHandler(SessionConsumer):))- def _reconnect_session(self, session: "Session", replay: bool) -> None:+ def _reconnect_session(self, session: Session, replay: bool) -> None:"""Reconnect to an existing session (kernel).A websocket can be closed when a user's computer goes to sleep,diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex 9dd4f31f68..e5443fe789 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -2,12 +2,12 @@from __future__ import annotationsimport asyncio+from collections.abc import AsyncIterablefrom dataclasses import dataclassfrom http.client import HTTPResponse, HTTPSConnectionfrom typing import (TYPE_CHECKING,Any,- AsyncIterable,Callable,Optional,Union,@@ -53,7 +53,7 @@ class AuthBackend(AuthenticationBackend):async def authenticate(self, conn: HTTPConnection- ) -> Optional[tuple["AuthCredentials", "BaseUser"]]:+ ) -> Optional[tuple[AuthCredentials, BaseUser]]:# We may not need to authenticate. This can be disabled# because the user is running in a trusted environment# or authentication is handled by a layer above usdiff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.pyindex 140e22c52e..b3dfb4db3a 100644--- a/marimo/_server/api/router.py+++ b/marimo/_server/api/router.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, List+from typing import TYPE_CHECKINGfrom marimo._server.api.endpoints.ai import router as ai_routerfrom marimo._server.api.endpoints.assets import router as assets_router@@ -32,7 +32,7 @@ if TYPE_CHECKING:# Define the app routes-def build_routes(base_url: str = "") -> List[BaseRoute]:+def build_routes(base_url: str = "") -> list[BaseRoute]:app_router = APIRouter(prefix=base_url)app_router.include_router(execution_router, prefix="/api/kernel", name="execution"diff --git a/marimo/_server/api/utils.py b/marimo/_server/api/utils.pyindex 2a38966e91..d38ed5039a 100644--- a/marimo/_server/api/utils.py+++ b/marimo/_server/api/utils.py@@ -6,7 +6,7 @@ import subprocessimport sysimport webbrowserfrom shutil import which-from typing import TYPE_CHECKING, Optional, Type, TypeVar+from typing import TYPE_CHECKING, Optional, TypeVarfrom marimo._utils.parse_dataclass import parse_raw@@ -31,7 +31,7 @@ def require_header(header: list[str] | None) -> str:async def parse_request(- request: Request, cls: Type[T], allow_unknown_keys: bool = False+ request: Request, cls: type[T], allow_unknown_keys: bool = False) -> T:"""Parse the request body as a dataclass of type `cls`"""return parse_raw(diff --git a/marimo/_server/asgi.py b/marimo/_server/asgi.pyindex 4121d1edd1..f066dd9355 100644--- a/marimo/_server/asgi.py+++ b/marimo/_server/asgi.py@@ -4,17 +4,14 @@ from __future__ import annotationsimport abcimport loggingfrom asyncio import iscoroutine+from collections.abc import Awaitablefrom functools import partialfrom pathlib import Pathfrom typing import (TYPE_CHECKING,- Awaitable,Callable,- Dict,- List,Optional,Protocol,- Tuple,Union,)@@ -47,7 +44,7 @@ class ASGIAppBuilder(abc.ABC):path: str,root: str,middleware: Optional[list[MiddlewareFactory]] = None,- ) -> "ASGIAppBuilder":+ ) -> ASGIAppBuilder:"""Adds a static application to the ASGI app at the specified path.@@ -69,7 +66,7 @@ class ASGIAppBuilder(abc.ABC):directory: str,validate_callback: Optional[ValidateCallback] = None,middleware: Optional[list[MiddlewareFactory]] = None,- ) -> "ASGIAppBuilder":+ ) -> ASGIAppBuilder:"""Adds a dynamic directory to the ASGI app, allowing for dynamic loading of applications from the specified directory.@@ -90,7 +87,7 @@ class ASGIAppBuilder(abc.ABC):pass@abc.abstractmethod- def build(self) -> "ASGIApp":+ def build(self) -> ASGIApp:"""Builds and returns the final ASGI application.@@ -118,7 +115,7 @@ class DynamicDirectoryMiddleware:self.base_path = base_path.rstrip("/")self.directory = Path(directory)self.app_builder = app_builder- self._app_cache: Dict[str, ASGIApp] = {}+ self._app_cache: dict[str, ASGIApp] = {}self.validate_callback = validate_callbackLOGGER.debug(f"Initialized DynamicDirectoryMiddleware with base_path={self.base_path}, "@@ -146,7 +143,7 @@ class DynamicDirectoryMiddleware:def _find_matching_file(self, relative_path: str- ) -> Optional[Tuple[Path, str]]:+ ) -> Optional[tuple[Path, str]]:"""Find a matching Python file in the directory structure.Returns tuple of (matching file, remaining path) if found, None otherwise."""@@ -408,18 +405,18 @@ def create_asgi_app(# support directories or code in the futureclass Builder(ASGIAppBuilder):def __init__(self) -> None:- self._mount_configs: List[- Tuple[str, str, Optional[list[MiddlewareFactory]]]+ self._mount_configs: list[+ tuple[str, str, Optional[list[MiddlewareFactory]]]] = []- self._dynamic_directory_configs: List[- Tuple[+ self._dynamic_directory_configs: list[+ tuple[str,str,Optional[ValidateCallback],Optional[list[MiddlewareFactory]],]] = []- self._app_cache: Dict[str, ASGIApp] = {}+ self._app_cache: dict[str, ASGIApp] = {}def with_app(self,@@ -427,7 +424,7 @@ def create_asgi_app(path: str,root: str,middleware: Optional[list[MiddlewareFactory]] = None,- ) -> "ASGIAppBuilder":+ ) -> ASGIAppBuilder:self._mount_configs.append((path, root, middleware))return self@@ -438,7 +435,7 @@ def create_asgi_app(directory: str,validate_callback: Optional[ValidateCallback] = None,middleware: Optional[list[MiddlewareFactory]] = None,- ) -> "ASGIAppBuilder":+ ) -> ASGIAppBuilder:self._dynamic_directory_configs.append((path, directory, validate_callback, middleware))@@ -481,7 +478,7 @@ def create_asgi_app(app.state.config_manager = config_readerreturn app- def build(self) -> "ASGIApp":+ def build(self) -> ASGIApp:# Handle individual app mounts first# Sort to ensure the root app is mounted lastself._mount_configs = sorted(diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 5c9e55d163..da3ddc4371 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -527,7 +527,7 @@ def get_html_contents() -> str:with urllib.request.urlopen(url) as response:return cast(str, response.read().decode("utf-8"))- with open(os.path.join(root, "index.html"), "r") as f:+ with open(os.path.join(root, "index.html")) as f:return f.read()diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex e8a9979307..f6f7418e25 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport osimport pathlibimport shutil-from typing import Any, Dict, Optional+from typing import Any, Optionalfrom marimo import _loggersfrom marimo._ast import codegen@@ -72,7 +72,7 @@ class AppFileManager:if os.path.exists(filename):raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,- detail="File {0} already exists".format(filename),+ detail=f"File {filename} already exists",)def _assert_path_is_the_same(self, filename: str) -> None:@@ -100,7 +100,7 @@ class AppFileManager:except Exception as err:raise HTTPException(status_code=HTTPStatus.SERVER_ERROR,- detail="Failed to save file {0}".format(filename),+ detail=f"Failed to save file {filename}",) from errdef _rename_file(self, new_filename: str) -> None:@@ -240,7 +240,7 @@ class AppFileManager:except AttributeError:return None- def save_app_config(self, config: Dict[str, Any]) -> str:+ def save_app_config(self, config: dict[str, Any]) -> str:"""Save the app configuration."""# Update the file with the latest app config# TODO(akshayka): Only change the `app = marimo.App` line (at top level@@ -331,7 +331,7 @@ class AppFileManager:status_code=HTTPStatus.BAD_REQUEST,detail="Cannot read code from an unnamed notebook",)- with open(self.filename, "r", encoding="utf-8") as f:+ with open(self.filename, encoding="utf-8") as f:contents = f.read().strip()return contentsdiff --git a/marimo/_server/file_router.py b/marimo/_server/file_router.pyindex 42cbe6d7dd..ac399d1c85 100644--- a/marimo/_server/file_router.py+++ b/marimo/_server/file_router.py@@ -6,7 +6,7 @@ import osimport pathlibimport signalfrom contextlib import contextmanager-from typing import TYPE_CHECKING, Generator, List, Optional+from typing import TYPE_CHECKING, Optionalfrom marimo import _loggersfrom marimo._config.config import WidthType@@ -18,6 +18,7 @@ from marimo._server.models.home import MarimoFilefrom marimo._utils.marimo_path import MarimoPathif TYPE_CHECKING:+ from collections.abc import Generatorfrom types import FrameTypeLOGGER = _loggers.marimo_logger()@@ -47,7 +48,7 @@ class AppFileRouter(abc.ABC):return AppFileRouter.from_directory(path)raise HTTPException(status_code=HTTPStatus.BAD_REQUEST,- detail="Path {0} is not a valid file or directory".format(path),+ detail=f"Path {path} is not a valid file or directory",)@staticmethod@@ -66,7 +67,7 @@ class AppFileRouter(abc.ABC):return LazyListOfFilesAppFileRouter(directory, include_markdown=False)@staticmethod- def from_files(files: List[MarimoFile]) -> AppFileRouter:+ def from_files(files: list[MarimoFile]) -> AppFileRouter:return ListOfFilesAppFileRouter(files)@staticmethod@@ -96,7 +97,7 @@ class AppFileRouter(abc.ABC):raise HTTPException(status_code=HTTPStatus.NOT_FOUND,- detail="File {0} not found".format(key),+ detail=f"File {key} not found",)@abc.abstractmethod@@ -115,7 +116,7 @@ class AppFileRouter(abc.ABC):@property@abc.abstractmethod- def files(self) -> List[FileInfo]:+ def files(self) -> list[FileInfo]:"""Get all files in a recursive tree."""@@ -130,16 +131,16 @@ class NewFileAppFileRouter(AppFileRouter):return None@property- def files(self) -> List[FileInfo]:+ def files(self) -> list[FileInfo]:return []class ListOfFilesAppFileRouter(AppFileRouter):- def __init__(self, files: List[MarimoFile]) -> None:+ def __init__(self, files: list[MarimoFile]) -> None:self._files = files@property- def files(self) -> List[FileInfo]:+ def files(self) -> list[FileInfo]:return [FileInfo(id=file.path,@@ -173,7 +174,7 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):# pass through Path to canonicalize, strips trailing slashesself._directory = str(pathlib.Path(directory))self.include_markdown = include_markdown- self._lazy_files: Optional[List[FileInfo]] = None+ self._lazy_files: Optional[list[FileInfo]] = None@propertydef directory(self) -> str:@@ -193,12 +194,12 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):self._lazy_files = None@property- def files(self) -> List[FileInfo]:+ def files(self) -> list[FileInfo]:if self._lazy_files is None:self._lazy_files = self._load_files()return self._lazy_files- def _load_files(self) -> List[FileInfo]:+ def _load_files(self) -> list[FileInfo]:import timestart_time = time.time()@@ -206,7 +207,7 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):def recurse(directory: str, depth: int = 0- ) -> Optional[List[FileInfo]]:+ ) -> Optional[list[FileInfo]]:if depth > MAX_DEPTH:return None@@ -222,8 +223,8 @@ class LazyListOfFilesAppFileRouter(AppFileRouter):LOGGER.debug("OSError scanning directory: %s", str(e))return None- files: List[FileInfo] = []- folders: List[FileInfo] = []+ files: list[FileInfo] = []+ folders: list[FileInfo] = []for entry in entries:# Skip hidden files and directories@@ -303,7 +304,7 @@ def timeout(seconds: int, message: str) -> Generator[None, None, None]:del signum, frameraise HTTPException(status_code=HTTPStatus.REQUEST_TIMEOUT,- detail="Request timed out: {0}".format(message),+ detail=f"Request timed out: {message}",)# Set the timeout handlerdiff --git a/marimo/_server/files/file_system.py b/marimo/_server/files/file_system.pyindex 52c36da0e6..5712a4b195 100644--- a/marimo/_server/files/file_system.py+++ b/marimo/_server/files/file_system.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom abc import ABC, abstractmethod-from typing import List, Literal, Optional+from typing import Literal, Optionalfrom marimo._server.models.files import FileDetailsResponse, FileInfo@@ -14,7 +14,7 @@ class FileSystem(ABC):pass@abstractmethod- def list_files(self, path: str) -> List[FileInfo]:+ def list_files(self, path: str) -> list[FileInfo]:"""List files and directories in a given path."""passdiff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex ac18e0a54c..151bac81e2 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -8,7 +8,7 @@ import platformimport reimport shutilimport subprocess-from typing import List, Literal, Optional, Union+from typing import Literal, Optional, Unionfrom marimo import _loggersfrom marimo._server.files.file_system import FileSystem@@ -34,9 +34,9 @@ class OSFileSystem(FileSystem):def get_root(self) -> str:return os.getcwd()- def list_files(self, path: str) -> List[FileInfo]:- files: List[FileInfo] = []- folders: List[FileInfo] = []+ def list_files(self, path: str) -> list[FileInfo]:+ files: list[FileInfo] = []+ folders: list[FileInfo] = []try:with os.scandir(path) as it:for entry in it:@@ -105,7 +105,7 @@ class OSFileSystem(FileSystem):def open_file(self, path: str, encoding: str | None = None) -> str:try:- with open(path, mode="r", encoding=encoding) as file:+ with open(path, encoding=encoding) as file:return file.read()except UnicodeDecodeError:# If its a UnicodeDecodeError, try as bytes and convert to base64@@ -201,15 +201,15 @@ class OSFileSystem(FileSystem):return False-def natural_sort_file(file: FileInfo) -> List[Union[int, str]]:+def natural_sort_file(file: FileInfo) -> list[Union[int, str]]:return natural_sort(file.name)-def natural_sort(filename: str) -> List[Union[int, str]]:+def natural_sort(filename: str) -> list[Union[int, str]]:def convert(text: str) -> Union[int, str]:return int(text) if text.isdigit() else text.lower()- def alphanum_key(key: str) -> List[Union[int, str]]:+ def alphanum_key(key: str) -> list[Union[int, str]]:return [convert(c) for c in re.split("([0-9]+)", key)]return alphanum_key(filename)diff --git a/marimo/_server/main.py b/marimo/_server/main.pyindex 1592e6410d..f237fdde8c 100644--- a/marimo/_server/main.py+++ b/marimo/_server/main.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, List, Optional+from typing import TYPE_CHECKING, Optionalfrom starlette.applications import Starlettefrom starlette.exceptions import HTTPException@@ -38,13 +38,13 @@ def create_starlette_app(*,base_url: str,host: Optional[str] = None,- middleware: Optional[List[Middleware]] = None,+ middleware: Optional[list[Middleware]] = None,lifespan: Optional[Lifespan[Starlette]] = None,enable_auth: bool = True,allow_origins: Optional[tuple[str, ...]] = None,lsp_port: Optional[int] = None,) -> Starlette:- final_middlewares: List[Middleware] = []+ final_middlewares: list[Middleware] = []if allow_origins is None:allow_origins = ("localhost", "127.0.0.1") + (diff --git a/marimo/_server/models/completion.py b/marimo/_server/models/completion.pyindex 1ee2b6fc95..d3c6f5c431 100644--- a/marimo/_server/models/completion.py+++ b/marimo/_server/models/completion.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom dataclasses import dataclass, field-from typing import Any, List, Literal, Optional+from typing import Any, Literal, Optionalfrom marimo._ai._types import ChatMessage@@ -11,18 +11,18 @@ from marimo._ai._types import ChatMessageclass SchemaColumn:name: strtype: str- sample_values: List[Any]+ sample_values: list[Any]@dataclassclass SchemaTable:name: str- columns: List[SchemaColumn]+ columns: list[SchemaColumn]@dataclassclass AiCompletionContext:- schema: List[SchemaTable] = field(default_factory=list)+ schema: list[SchemaTable] = field(default_factory=list)Language = Literal["python", "markdown", "sql"]@@ -41,6 +41,6 @@ class AiCompletionRequest:class ChatRequest:context: AiCompletionContextinclude_other_code: str- messages: List[ChatMessage]+ messages: list[ChatMessage]model: Optional[str] = None- variables: Optional[List[str]] = None+ variables: Optional[list[str]] = Nonediff --git a/marimo/_server/models/export.py b/marimo/_server/models/export.pyindex 7cafdcbac6..b1a4eb2b64 100644--- a/marimo/_server/models/export.py+++ b/marimo/_server/models/export.py@@ -2,13 +2,13 @@from __future__ import annotationsfrom dataclasses import dataclass-from typing import List, Optional+from typing import Optional@dataclassclass ExportAsHTMLRequest:download: bool- files: List[str]+ files: list[str]include_code: boolasset_url: Optional[str] = Nonediff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.pyindex 740fb4d24e..130deaea17 100644--- a/marimo/_server/models/files.py+++ b/marimo/_server/models/files.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom dataclasses import dataclass, field-from typing import List, Literal, Optional+from typing import Literal, Optionalfrom marimo._server.models.models import BaseResponse@@ -15,7 +15,7 @@ class FileInfo:is_directory: boolis_marimo_file: boollast_modified: Optional[float] = None- children: List["FileInfo"] = field(default_factory=list)+ children: list[FileInfo] = field(default_factory=list)@dataclass@@ -79,7 +79,7 @@ class FileUpdateRequest:@dataclassclass FileListResponse:- files: List[FileInfo]+ files: list[FileInfo]root: strdiff --git a/marimo/_server/models/home.py b/marimo/_server/models/home.pyindex d86ae6ea24..b050645197 100644--- a/marimo/_server/models/home.py+++ b/marimo/_server/models/home.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom dataclasses import dataclass-from typing import List, Optional+from typing import Optionalfrom marimo._server.models.files import FileInfofrom marimo._tutorials import Tutorial@@ -26,12 +26,12 @@ class MarimoFile:@dataclassclass RecentFilesResponse:- files: List[MarimoFile]+ files: list[MarimoFile]@dataclassclass RunningNotebooksResponse:- files: List[MarimoFile]+ files: list[MarimoFile]@dataclass@@ -47,7 +47,7 @@ class WorkspaceFilesRequest:@dataclassclass WorkspaceFilesResponse:root: str- files: List[FileInfo]+ files: list[FileInfo]@dataclassdiff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.pyindex 080a0c22a0..a220c644d6 100644--- a/marimo/_server/models/models.py+++ b/marimo/_server/models/models.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport osfrom dataclasses import dataclass-from typing import Any, Dict, List, Optional+from typing import Any, Optionalfrom marimo._ast.cell import CellConfigfrom marimo._config.config import MarimoConfig@@ -18,12 +18,12 @@ from marimo._types.ids import CellId_t, UIElementId@dataclassclass UpdateComponentValuesRequest:- object_ids: List[UIElementId]- values: List[Any]+ object_ids: list[UIElementId]+ values: list[Any]def zip(self,- ) -> List[tuple[UIElementId, Any]]:+ ) -> list[tuple[UIElementId, Any]]:return list(zip(self.object_ids, self.values))# Validate same length@@ -56,13 +56,13 @@ class ErrorResponse(BaseResponse):@dataclassclass FormatRequest:- codes: Dict[CellId_t, str]+ codes: dict[CellId_t, str]line_length: int@dataclassclass FormatResponse:- codes: Dict[CellId_t, str]+ codes: dict[CellId_t, str]@dataclass@@ -81,9 +81,9 @@ class RenameFileRequest:@dataclassclass RunRequest:# ids of cells to run- cell_ids: List[CellId_t]+ cell_ids: list[CellId_t]# code to register/run for each cell- codes: List[str]+ codes: list[str]# incoming request, e.g. from Starlette or FastAPIrequest: Optional[HTTPRequest] = None@@ -117,17 +117,17 @@ class RunScratchpadRequest:@dataclassclass SaveNotebookRequest:# id of each cell- cell_ids: List[CellId_t]+ cell_ids: list[CellId_t]# code for each cell- codes: List[str]+ codes: list[str]# name of each cell- names: List[str]+ names: list[str]# config for each cell- configs: List[CellConfig]+ configs: list[CellConfig]# path to appfilename: str# layout of app- layout: Optional[Dict[str, Any]] = None+ layout: Optional[dict[str, Any]] = None# persist the file to diskpersist: bool = True@@ -167,7 +167,7 @@ class CopyNotebookRequest:@dataclassclass SaveAppConfigurationRequest:# partial app config- config: Dict[str, Any]+ config: dict[str, Any]@dataclassdiff --git a/marimo/_server/models/packages.py b/marimo/_server/models/packages.pyindex ab182b3a7a..b253375cec 100644--- a/marimo/_server/models/packages.py+++ b/marimo/_server/models/packages.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom dataclasses import dataclass-from typing import List, Optional+from typing import Optionalfrom marimo._runtime.packages.package_manager import PackageDescription@@ -32,7 +32,7 @@ class RemovePackageRequest:@dataclassclass ListPackagesResponse:- packages: List[PackageDescription]+ packages: list[PackageDescription]@dataclassdiff --git a/marimo/_server/print.py b/marimo/_server/print.pyindex 444e97a0c3..f21005a781 100644--- a/marimo/_server/print.py+++ b/marimo/_server/print.py@@ -52,7 +52,9 @@ def print_startup(def print_shutdown() -> None:print_()- print_tabbed("\033[32mThanks for using marimo!\033[0m %s" % _utf8("🌊🍃"))+ print_tabbed(+ "\033[32mThanks for using marimo!\033[0m {}".format(_utf8("🌊🍃"))+ )print_()diff --git a/marimo/_server/recents.py b/marimo/_server/recents.pyindex 50c278d671..b4947a5c56 100644--- a/marimo/_server/recents.py+++ b/marimo/_server/recents.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport osimport pathlibfrom dataclasses import dataclass, field-from typing import Listfrom marimo import _loggersfrom marimo._server.models.home import MarimoFile@@ -14,7 +13,7 @@ from marimo._utils.paths import pretty_path@dataclassclass RecentFilesState:- files: List[str] = field(default_factory=list)+ files: list[str] = field(default_factory=list)# TODO(akshayka): _IGNORED_FOLDERS doesn't cover Windows@@ -81,14 +80,14 @@ class RecentFilesManager:self.config.write_toml(state)- def get_recents(self) -> List[MarimoFile]:+ def get_recents(self) -> list[MarimoFile]:if not self.config:return []state = self.config.read_toml(RecentFilesState, fallback=RecentFilesState())- files: List[MarimoFile] = []+ files: list[MarimoFile] = []cwd = pathlib.Path.cwd()limited_files = state.files[: self.MAX_FILES]diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.pyindex 74416525b4..49aa32d12c 100644--- a/marimo/_server/session/serialize.py+++ b/marimo/_server/session/serialize.py@@ -5,7 +5,7 @@ import asyncioimport hashlibimport jsonfrom pathlib import Path-from typing import List, Optional, cast+from typing import Optional, castfrom marimo import __version__, _loggersfrom marimo._messaging.cell_output import CellChannel, CellOutput@@ -35,16 +35,16 @@ LOGGER = _loggers.marimo_logger()def serialize_session_view(view: SessionView) -> NotebookSessionV1:"""Convert a SessionView to a NotebookSession schema."""- cells: List[Cell] = []+ cells: list[Cell] = []for cell_id, cell_op in view.cell_operations.items():- outputs: List[OutputType] = []- console: List[StreamOutput] = []+ outputs: list[OutputType] = []+ console: list[StreamOutput] = []# Convert outputif cell_op.output:if cell_op.output.channel == CellChannel.MARIMO_ERROR:- for error in cast(List[MarimoError], cell_op.output.data):+ for error in cast(list[MarimoError], cell_op.output.data):outputs.append(ErrorOutput(type="error",@@ -100,7 +100,7 @@ def deserialize_session(session: NotebookSessionV1) -> SessionView:view = SessionView()for cell in session["cells"]:- cell_outputs: List[CellOutput] = []+ cell_outputs: list[CellOutput] = []# Convert outputsfor output in cell["outputs"]:@@ -148,7 +148,7 @@ def deserialize_session(session: NotebookSessionV1) -> SessionView:continue# Convert console- console_outputs: List[CellOutput] = []+ console_outputs: list[CellOutput] = []for console in cell["console"]:console_outputs.append(CellOutput(diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 77aae79d44..496c4952da 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -27,7 +27,7 @@ import timefrom multiprocessing import connectionfrom multiprocessing.queues import Queue as MPQueuefrom pathlib import Path-from typing import Any, Dict, Optional, Union+from typing import Any, Optional, Unionfrom uuid import uuid4from marimo import _loggers@@ -351,8 +351,8 @@ class Room:def __init__(self) -> None:self.main_consumer: Optional[SessionConsumer] = None- self.consumers: Dict[SessionConsumer, ConsumerId] = {}- self.disposables: Dict[SessionConsumer, Disposable] = {}+ self.consumers: dict[SessionConsumer, ConsumerId] = {}+ self.disposables: dict[SessionConsumer, Disposable] = {}@propertydef size(self) -> int:diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 5a2182d172..a2b42f16bc 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -5,7 +5,7 @@ import base64import jsonimport osfrom textwrap import dedent-from typing import Any, List, Literal, Optional, cast+from typing import Any, Literal, Optional, castfrom marimo import __version__from marimo._ast.app import _AppConfig@@ -108,7 +108,7 @@ def static_notebook_template(cell_codes: list[str],cell_configs: list[CellConfig],cell_outputs: dict[CellId_t, CellOutput],- cell_console_outputs: dict[CellId_t, List[CellOutput]],+ cell_console_outputs: dict[CellId_t, list[CellOutput]],files: dict[str, str],asset_url: Optional[str] = None,) -> str:diff --git a/marimo/_snippets/snippets.py b/marimo/_snippets/snippets.pyindex da7943fb8f..b33ba0b9a9 100644--- a/marimo/_snippets/snippets.py+++ b/marimo/_snippets/snippets.py@@ -1,9 +1,10 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from collections.abc import Awaitable, Generatorfrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Awaitable, Generator, List, Optional+from typing import Any, Optionalfrom marimo import _loggersfrom marimo._ast.codegen import get_app@@ -23,21 +24,21 @@ class SnippetSection:@dataclassclass Snippet:title: str- sections: List[SnippetSection]+ sections: list[SnippetSection]@dataclassclass Snippets:- snippets: List[Snippet]+ snippets: list[Snippet]async def read_snippets() -> Snippets:- snippets: List[Snippet] = []+ snippets: list[Snippet] = []for file in read_snippet_filenames_from_config():app = get_app(file)assert app is not None- sections: List[SnippetSection] = []+ sections: list[SnippetSection] = []title = ""for cell in app._cell_manager.cells():@@ -114,7 +115,7 @@ def read_snippet_filenames_from_config() -> Generator[str, Any, None]:def read_snippet_filenames(- include_default_snippets: bool, custom_paths: List[str]+ include_default_snippets: bool, custom_paths: list[str]) -> Generator[str, Any, None]:paths: list[Path] = []if include_default_snippets:diff --git a/marimo/_sql/utils.py b/marimo/_sql/utils.pyindex ae9dc1a9d1..cc9f577620 100644--- a/marimo/_sql/utils.py+++ b/marimo/_sql/utils.py@@ -16,7 +16,7 @@ if TYPE_CHECKING:def wrapped_sql(query: str,connection: Optional[duckdb.DuckDBPyConnection],-) -> "duckdb.DuckDBPyRelation":+) -> duckdb.DuckDBPyRelation:DependencyManager.duckdb.require("to execute sql")# In Python globals() are scoped to modules; since this functiondiff --git a/marimo/_tracer.py b/marimo/_tracer.pyindex 8b95e5f75e..9b4f8813b1 100644--- a/marimo/_tracer.py+++ b/marimo/_tracer.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport osfrom contextlib import contextmanager-from typing import TYPE_CHECKING, Any, Sequence, cast+from typing import TYPE_CHECKING, Any, castfrom marimo import _loggersfrom marimo._config.settings import GLOBAL_SETTINGS@@ -14,6 +14,8 @@ from marimo._utils.platform import is_pyodideLOGGER = _loggers.marimo_logger()if TYPE_CHECKING:+ from collections.abc import Sequence+from opentelemetry import trace@@ -141,7 +143,7 @@ def _set_tracer_provider() -> None:trace.set_tracer_provider(provider)-def create_tracer(trace_name: str) -> "trace.Tracer":+def create_tracer(trace_name: str) -> trace.Tracer:"""Creates a tracer that logs to a file.diff --git a/marimo/_utils/config/config.py b/marimo/_utils/config/config.pyindex 1e1c7a8081..8e8267c9da 100644--- a/marimo/_utils/config/config.py+++ b/marimo/_utils/config/config.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport osfrom dataclasses import asdictfrom tempfile import TemporaryDirectory-from typing import Any, Optional, Type, TypeVar+from typing import Any, Optional, TypeVarfrom marimo._utils.parse_dataclass import parse_rawfrom marimo._utils.toml import read_toml@@ -21,7 +21,7 @@ class ConfigReader:self.filepath = filepath@staticmethod- def for_filename(filename: str) -> Optional["ConfigReader"]:+ def for_filename(filename: str) -> Optional[ConfigReader]:home_expansion = ConfigReader._get_home_directory()if home_expansion == "~":# path expansion failed@@ -30,7 +30,7 @@ class ConfigReader:filepath = os.path.join(home_directory, ROOT_DIR, filename)return ConfigReader(filepath)- def read_toml(self, cls: Type[T], *, fallback: T) -> T:+ def read_toml(self, cls: type[T], *, fallback: T) -> T:import tomlkittry:diff --git a/marimo/_utils/dataclass_to_openapi.py b/marimo/_utils/dataclass_to_openapi.pyindex d1f8cdf5a3..c5ed729b88 100644--- a/marimo/_utils/dataclass_to_openapi.py+++ b/marimo/_utils/dataclass_to_openapi.py@@ -4,18 +4,15 @@ from __future__ import annotationsimport dataclassesimport datetimeimport sys-from collections.abc import Mapping, Sequence+from collections.abc import Mapping, Sequence as CollectionSequencefrom decimal import Decimalfrom enum import Enumfrom typing import (Any,ClassVar,- Dict,ForwardRef,- List,Literal,Optional,- Type,Union,get_args,get_origin,@@ -29,9 +26,11 @@ if sys.version_info < (3, 11):else:from typing import NotRequired+from typing import Sequence # noqa: UP035+class PythonTypeToOpenAPI:- def __init__(self, name_overrides: Dict[Any, str], camel_case: bool):+ def __init__(self, name_overrides: dict[Any, str], camel_case: bool):self.name_overrides = name_overridesself.camel_case = camel_caseself.optional_name_overrides = {@@ -41,8 +40,8 @@ class PythonTypeToOpenAPI:def convert(self,py_type: Any,- processed_classes: Dict[Any, str],- ) -> Dict[str, Any]:+ processed_classes: dict[Any, str],+ ) -> dict[str, Any]:"""Convert a Python type to an OpenAPI schema.@@ -52,13 +51,15 @@ class PythonTypeToOpenAPI:origin = get_origin(py_type)optional_name_overrides = self.optional_name_overrides+ if isinstance(py_type, ForwardRef):+ return {"$ref": f"#/components/schemas/{py_type.__forward_arg__}"}+# Handle NewType by unwrapping to its base typeif hasattr(py_type, "__supertype__"): # NewType checkreturn self.convert(py_type.__supertype__, processed_classes)if origin is Union:args = get_args(py_type)-if py_type in processed_classes:ref = processed_classes[py_type]return {"$ref": f"#/components/schemas/{ref}"}@@ -105,13 +106,23 @@ class PythonTypeToOpenAPI:])}- elif origin in (list, List) or origin is Sequence:+ elif (+ origin is list+ or origin is CollectionSequence+ or origin is Sequence+ ):+ if py_type in processed_classes:+ ref = processed_classes[py_type]+ return {"$ref": f"#/components/schemas/{ref}"}(item_type,) = get_args(py_type)return {"type": "array","items": self.convert(item_type, processed_classes),}- elif origin in (dict, Dict) or origin is Mapping:+ elif origin is dict or origin is Mapping:+ if py_type in processed_classes:+ ref = processed_classes[py_type]+ return {"$ref": f"#/components/schemas/{ref}"}_key_type, value_type = get_args(py_type)return {"type": "object",@@ -166,7 +177,7 @@ class PythonTypeToOpenAPI:# Remove any keys that are optionalrequired = [key for key in required if key not in optional_keys]- schema: Dict[str, Any] = {+ schema: dict[str, Any] = {"type": "object","properties": properties,}@@ -210,8 +221,6 @@ class PythonTypeToOpenAPI:ref = processed_classes[py_type]return {"$ref": f"#/components/schemas/{ref}"}return {"type": "string", "enum": [e.value for e in py_type]}- elif isinstance(py_type, ForwardRef):- return {"$ref": f"#/components/schemas/{py_type.__forward_arg__}"}else:raise ValueError(f"Unsupported type: py_type={py_type}, origin={origin}"@@ -219,9 +228,9 @@ class PythonTypeToOpenAPI:def convert_dataclass(self,- cls: Type[Any],- processed_classes: Dict[Any, str],- ) -> Dict[str, Any]:+ cls: type[Any],+ processed_classes: dict[Any, str],+ ) -> dict[str, Any]:"""Convert a dataclass to an OpenAPI schema.Args:@@ -245,8 +254,8 @@ class PythonTypeToOpenAPI:type_hints = get_type_hints(cls)fields: tuple[dataclasses.Field[Any], ...] = dataclasses.fields(cls)- properties: Dict[str, Dict[str, Any]] = {}- required: List[str] = []+ properties: dict[str, dict[str, Any]] = {}+ required: list[str] = []for field in fields:cased_field_name = (@@ -273,7 +282,7 @@ class PythonTypeToOpenAPI:}required.append(cased_field_name)- schema: Dict[str, Any] = {+ schema: dict[str, Any] = {"type": "object","properties": properties,}diff --git a/marimo/_utils/file_watcher.py b/marimo/_utils/file_watcher.pyindex 2162571a11..3d0f809058 100644--- a/marimo/_utils/file_watcher.py+++ b/marimo/_utils/file_watcher.py@@ -5,8 +5,9 @@ import asyncioimport osfrom abc import ABC, abstractmethodfrom collections import defaultdict+from collections.abc import Coroutinefrom pathlib import Path-from typing import Any, Callable, Coroutine, Dict, Optional, Set+from typing import Any, Callable, Optionalfrom marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager@@ -18,7 +19,7 @@ Callback = Callable[[Path], Coroutine[None, None, None]]class FileWatcher(ABC):@staticmethod- def create(path: Path, callback: Callback) -> "FileWatcher":+ def create(path: Path, callback: Callback) -> FileWatcher:if DependencyManager.watchdog.has():LOGGER.debug("Using watchdog file watcher")return _create_watchdog(path, callback, asyncio.get_event_loop())@@ -137,9 +138,9 @@ class FileWatcherManager:def __init__(self) -> None:# Map of file paths to their watchers- self._watchers: Dict[str, FileWatcher] = {}+ self._watchers: dict[str, FileWatcher] = {}# Map of file paths to their callbacks- self._callbacks: Dict[str, Set[Callback]] = defaultdict(set)+ self._callbacks: dict[str, set[Callback]] = defaultdict(set)def add_callback(self, path: Path, callback: Callback) -> None:"""Add a callback for a file path. Creates watcher if needed."""diff --git a/marimo/_utils/flatten.py b/marimo/_utils/flatten.pyindex 9f4d2655f0..f900fb90ae 100644--- a/marimo/_utils/flatten.py+++ b/marimo/_utils/flatten.py@@ -12,11 +12,11 @@ installation of dm-tree on macOS is buggyfrom __future__ import annotationsimport itertools-from typing import Any, Callable, Dict, List, Tuple, Type, Union+from typing import Any, Callable, Union-STRUCT_TYPE = Union[Tuple[Any, ...], List[Any], Dict[Any, Any]]-UNFLATTEN_TYPE = Callable[[List[Any]], Union[STRUCT_TYPE, Any]]-FLATTEN_RET_TYPE = Tuple[List[Any], UNFLATTEN_TYPE]+STRUCT_TYPE = Union[tuple[Any, ...], list[Any], dict[Any, Any]]+UNFLATTEN_TYPE = Callable[[list[Any]], Union[STRUCT_TYPE, Any]]+FLATTEN_RET_TYPE = tuple[list[Any], UNFLATTEN_TYPE]class CyclicStructureError(Exception):@@ -31,7 +31,7 @@ def _flatten_sequence(value: list[Any] | tuple[Any, ...], json_compat_keys: bool, seen: set[int]) -> FLATTEN_RET_TYPE:"""Flatten a sequence of values"""- base_type: Type[List[Any]] | Type[Tuple[Any, ...]]+ base_type: type[list[Any]] | type[tuple[Any, ...]]if isinstance(value, list):base_type = listelif isinstance(value, tuple):diff --git a/marimo/_utils/formatter.py b/marimo/_utils/formatter.pyindex d92fff4b4a..98503f6d60 100644--- a/marimo/_utils/formatter.py+++ b/marimo/_utils/formatter.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport subprocessimport sys-from typing import Dictfrom marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager@@ -12,7 +11,7 @@ from marimo._types.ids import CellId_tLOGGER = _loggers.marimo_logger()-CellCodes = Dict[CellId_t, str]+CellCodes = dict[CellId_t, str]def ruff(codes: CellCodes, *cmd: str) -> CellCodes:diff --git a/marimo/_utils/lists.py b/marimo/_utils/lists.pyindex 6ae04dcda2..2342704ae0 100644--- a/marimo/_utils/lists.py+++ b/marimo/_utils/lists.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Iterable, Optional, TypeVar, Union+from collections.abc import Iterable+from typing import Optional, TypeVar, UnionT = TypeVar("T")diff --git a/marimo/_utils/log_formatter.py b/marimo/_utils/log_formatter.pyindex f931b2e7f2..fe1105d1d4 100644--- a/marimo/_utils/log_formatter.py+++ b/marimo/_utils/log_formatter.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport loggingimport logging.handlersimport sys-from typing import Any, Dict, cast+from typing import Any, casttry:import curses@@ -64,7 +64,7 @@ class LogFormatter(logging.Formatter):datefmt: str = DEFAULT_DATE_FORMAT,style: str = "%",color: bool = True,- colors: Dict[int, int] = DEFAULT_COLORS,+ colors: dict[int, int] = DEFAULT_COLORS,) -> None:r""":arg bool color: Enables color support.@@ -85,7 +85,7 @@ class LogFormatter(logging.Formatter):logging.Formatter.__init__(self, datefmt=datefmt)self._fmt = fmt- self._colors = {} # type: Dict[int, str]+ self._colors: dict[int, str] = {}if color and _stderr_supports_color():if curses is not None:fg_color = (@@ -109,7 +109,7 @@ class LogFormatter(logging.Formatter):# If curses is not present (currently we'll only get here for# colorama on windows), assume hard-coded ANSI color codes.for levelno, code in colors.items():- self._colors[levelno] = "\033[2;3%dm" % code+ self._colors[levelno] = "\033[2;3%dm" % code # noqa: UP031self._normal = "\033[0m"else:self._normal = ""@@ -120,7 +120,7 @@ class LogFormatter(logging.Formatter):assert isinstance(message, str) # guaranteed by loggingrecord.message = messageexcept Exception as e:- record.message = "Bad message (%r): %r" % (e, record.__dict__)+ record.message = f"Bad message ({e!r}): {record.__dict__!r}"record.asctime = self.formatTime(record, cast(str, self.datefmt))diff --git a/marimo/_utils/memoize.py b/marimo/_utils/memoize.pyindex 741cb97b59..7ba530617a 100644--- a/marimo/_utils/memoize.py+++ b/marimo/_utils/memoize.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Callable, Tuple, TypeVar, cast+from typing import Any, Callable, TypeVar, castT = TypeVar("T")@@ -14,7 +14,7 @@ def memoize_last_value(func: Callable[..., T]) -> Callable[..., T]:object identity for positional arguments instead of equalitywhich for functools requires the arguments to be hashable."""- last_input: Tuple[Tuple[Any, ...], frozenset[Tuple[str, Any]]] = (+ last_input: tuple[tuple[Any, ...], frozenset[tuple[str, Any]]] = ((),frozenset(),)@@ -23,7 +23,7 @@ def memoize_last_value(func: Callable[..., T]) -> Callable[..., T]:def wrapper(*args: Any, **kwargs: Any) -> T:nonlocal last_input, last_output- current_input: Tuple[Tuple[Any, ...], frozenset[Tuple[str, Any]]] = (+ current_input: tuple[tuple[Any, ...], frozenset[tuple[str, Any]]] = (args,frozenset(kwargs.items()),)diff --git a/marimo/_utils/parse_dataclass.py b/marimo/_utils/parse_dataclass.pyindex a879f1525d..c9987858ef 100644--- a/marimo/_utils/parse_dataclass.py+++ b/marimo/_utils/parse_dataclass.py@@ -8,7 +8,6 @@ from typing import (Any,Literal,Optional,- Type,TypeVar,Union,get_args,@@ -31,7 +30,7 @@ class DataclassParser:def __init__(self, allow_unknown_keys: bool = False):self.allow_unknown_keys = allow_unknown_keys- def _build_value(self, value: Any, cls: Type[T]) -> T:+ def _build_value(self, value: Any, cls: type[T]) -> T:# origin_cls is not None if cls is a container (such as list,# tuple, set, ...)origin_cls = get_origin(cls)@@ -101,7 +100,7 @@ class DataclassParser:else:return value # type: ignore[no-any-return]- def build_dataclass(self, values: dict[Any, Any], cls: Type[T]) -> T:+ def build_dataclass(self, values: dict[Any, Any], cls: type[T]) -> T:"""Returns instance of dataclass [cls] instantiated from [values]."""if not isinstance(values, dict):@@ -136,7 +135,7 @@ class DataclassParser:def parse_raw(message: Union[bytes, dict[Any, Any]],- cls: Type[T],+ cls: type[T],allow_unknown_keys: bool = False,) -> T:"""Utility to parse a message as JSON, and instantiate into supplied type.diff --git a/marimo/_utils/toml.py b/marimo/_utils/toml.pyindex f41f3a333b..6d7705e6cc 100644--- a/marimo/_utils/toml.py+++ b/marimo/_utils/toml.py@@ -1,13 +1,13 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, Any, Dict, Union+from typing import TYPE_CHECKING, Any, Unionif TYPE_CHECKING:from pathlib import Path-def read_toml(file_path: Union[str, Path]) -> Dict[str, Any]:+def read_toml(file_path: Union[str, Path]) -> dict[str, Any]:"""Read and parse a TOML file."""import tomlkitdiff --git a/marimo/_utils/url.py b/marimo/_utils/url.pyindex 5c01c90875..e9d220fd62 100644--- a/marimo/_utils/url.py+++ b/marimo/_utils/url.py@@ -136,5 +136,5 @@ def is_url(value: str, public: bool = False) -> bool:return result is not Nonereturn result is not None and not any(- (result.groupdict().get(key) for key in ("private_ip", "private_host"))+ result.groupdict().get(key) for key in ("private_ip", "private_host"))diff --git a/openapi/api.yaml b/openapi/api.yamlindex 73c03d63bc..e0061c127b 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -909,7 +909,21 @@ components:- function-call-resulttype: stringreturn_value:- $ref: '#/components/schemas/JSONType'+ nullable: true+ oneOf:+ - additionalProperties:+ $ref: '#/components/schemas/JSONType'+ type: object+ - items:+ $ref: '#/components/schemas/JSONType'+ type: array+ - type: string+ - type: integer+ - type: number+ - type: boolean+ - additionalProperties: true+ type: object+ - $ref: '#/components/schemas/MIME'status:$ref: '#/components/schemas/HumanReadableStatus'required:@@ -1097,10 +1111,38 @@ components:nullable: trueoneOf:- additionalProperties:- $ref: '#/components/schemas/JSONType'+ nullable: true+ oneOf:+ - additionalProperties:+ $ref: '#/components/schemas/JSONType'+ type: object+ - items:+ $ref: '#/components/schemas/JSONType'+ type: array+ - type: string+ - type: integer+ - type: number+ - type: boolean+ - additionalProperties: true+ type: object+ - $ref: '#/components/schemas/MIME'type: object- items:- $ref: '#/components/schemas/JSONType'+ nullable: true+ oneOf:+ - additionalProperties:+ $ref: '#/components/schemas/JSONType'+ type: object+ - items:+ $ref: '#/components/schemas/JSONType'+ type: array+ - type: string+ - type: integer+ - type: number+ - type: boolean+ - additionalProperties: true+ type: object+ - $ref: '#/components/schemas/MIME'type: array- type: string- type: integer@@ -2152,7 +2194,7 @@ components:type: objectinfo:title: marimo API- version: 0.11.7+ version: 0.11.9openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/pyproject.toml b/pyproject.tomlindex 874fbe7861..0698ce988a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -283,6 +283,7 @@ deploy = "mkdocs gh-deploy --force {args}"[tool.ruff]line-length = 79+target-version = "py39"include = ["marimo/**/*.py", "tests/**/*.py", "dagger/**/*.py"]exclude = ["examples",@@ -320,6 +321,8 @@ ignore = ["E501", # Line too long, we still trim"D415", # First line should end with a period, question mark, or exclamation point"FA102", # Use `from __future__ import annotations`+ "UP007", # Use X | Y for type annotations, not supported in 3.9+ "UP045", # Use X | None for optional type annotations, not supported in 3.9]extend-select = [# pyflakes@@ -383,6 +386,7 @@ extend-select = ["D211", # No blank lines allowed before class docstring"D214", # Section is over-indented"D215", # Section underline is over-indented+ "UP", # Upgrades]# Never try to fix `F401` (unused imports).diff --git a/tests/_ai/test_chat_convert.py b/tests/_ai/test_chat_convert.pyindex 769868df7a..fa96b83839 100644--- a/tests/_ai/test_chat_convert.py+++ b/tests/_ai/test_chat_convert.py@@ -1,7 +1,6 @@from __future__ import annotationsimport base64-from typing import Listimport pytest@@ -19,7 +18,7 @@ from marimo._plugins.ui._impl.chat.utils import from_chat_message_dict@pytest.fixture-def sample_messages() -> List[ChatMessage]:+def sample_messages() -> list[ChatMessage]:return [ChatMessage(role="user",@@ -28,7 +27,7 @@ def sample_messages() -> List[ChatMessage]:ChatAttachment(name="image.png",content_type="image/png",- url=f"data:image/png;base64,{base64.b64encode('hello'.encode())}",+ url=f"data:image/png;base64,{base64.b64encode(b'hello')}",),ChatAttachment(name="text.txt",@@ -45,7 +44,7 @@ def sample_messages() -> List[ChatMessage]:]-def test_convert_to_openai_messages(sample_messages: List[ChatMessage]):+def test_convert_to_openai_messages(sample_messages: list[ChatMessage]):result = convert_to_openai_messages(sample_messages)assert len(result) == 2@@ -74,7 +73,7 @@ def test_convert_to_openai_messages(sample_messages: List[ChatMessage]):)-def test_convert_to_anthropic_messages(sample_messages: List[ChatMessage]):+def test_convert_to_anthropic_messages(sample_messages: list[ChatMessage]):result = convert_to_anthropic_messages(sample_messages)assert len(result) == 2@@ -107,7 +106,7 @@ def test_convert_to_anthropic_messages(sample_messages: List[ChatMessage]):)-def test_convert_to_google_messages(sample_messages: List[ChatMessage]):+def test_convert_to_google_messages(sample_messages: list[ChatMessage]):result = convert_to_google_messages(sample_messages)assert len(result) == 2@@ -133,7 +132,7 @@ def test_convert_to_google_messages(sample_messages: List[ChatMessage]):]-def test_convert_to_groq_messages(sample_messages: List[ChatMessage]):+def test_convert_to_groq_messages(sample_messages: list[ChatMessage]):result = convert_to_groq_messages(sample_messages)assert len(result) == 2diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex 8ebddb69fd..79075d9b53 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -24,7 +24,7 @@ DIR_PATH = os.path.dirname(os.path.realpath(__file__))def get_expected_filecontents(name: str) -> str:- with open(os.path.join(DIR_PATH, f"codegen_data/{name}.py"), "r") as f:+ with open(os.path.join(DIR_PATH, f"codegen_data/{name}.py")) as f:contents = f.read()lines = contents.split("\n")break_index = Nonediff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.pyindex 48b277f437..697a507050 100644--- a/tests/_cli/test_cli.py+++ b/tests/_cli/test_cli.py@@ -18,7 +18,7 @@ import tempfileimport timeimport urllib.errorimport urllib.request-from typing import Any, Callable, Generator, Iterator, Optional+from typing import TYPE_CHECKING, Any, Callable, Optionalimport pytest@@ -29,6 +29,9 @@ from marimo._server.templates.templates import get_versionfrom marimo._utils.config.config import ROOT_DIR as CONFIG_ROOT_DIRfrom marimo._utils.toml import read_toml+if TYPE_CHECKING:+ from collections.abc import Generator, Iterator+HAS_UV = DependencyManager.which("uv")DIR_PATH = os.path.dirname(os.path.realpath(__file__))diff --git a/tests/_cli/test_cli_development.py b/tests/_cli/test_cli_development.pyindex e06015c7a6..00937d7491 100644--- a/tests/_cli/test_cli_development.py+++ b/tests/_cli/test_cli_development.py@@ -17,7 +17,7 @@ def test_cli_development_openapi() -> None:def test_openapi_up_to_date() -> None:- with open("openapi/api.yaml", "r") as f:+ with open("openapi/api.yaml") as f:current_content = yaml.safe_load(f)result = subprocess.run(diff --git a/tests/_cli/test_file_path.py b/tests/_cli/test_file_path.pyindex ef75e27157..4e84828741 100644--- a/tests/_cli/test_file_path.py+++ b/tests/_cli/test_file_path.py@@ -80,9 +80,9 @@ def test_github_issue_reader() -> None:with patch("urllib.request.urlopen") as mock_urlopen:mock_response = mock_open(- read_data="""{+ read_data=b"""{"body": "Some content.```python\\nprint('Hello, world!')\\n```"}- """.encode() # noqa: E501+ """ # noqa: E501)mock_urlopen.return_value = mock_response()@@ -108,7 +108,7 @@ def test_github_source_reader() -> None:assert reader.can_read(invalid_url) is Falsewith patch("urllib.request.urlopen") as mock_urlopen:- mock_response = mock_open(read_data="print('Hello, world!')".encode())+ mock_response = mock_open(read_data=b"print('Hello, world!')")mock_urlopen.return_value = mock_response()content, filename = reader.read(valid_url)@@ -154,7 +154,7 @@ def test_generic_url_reader() -> None:assert reader.can_read("local_file.py") is Falsewith patch("urllib.request.urlopen") as mock_urlopen:- mock_response = mock_open(read_data="print('Hello, world!')".encode())+ mock_response = mock_open(read_data=b"print('Hello, world!')")mock_urlopen.return_value = mock_response()content, filename = reader.read("https://example.com/file.py")@@ -262,7 +262,7 @@ def test_generic_url_reader_with_query_params():url = "https://example.com/file.py?param=value"assert reader.can_read(url) is Truewith patch("urllib.request.urlopen") as mock_urlopen:- mock_response = mock_open(read_data="print('Hello, world!')".encode())+ mock_response = mock_open(read_data=b"print('Hello, world!')")mock_urlopen.return_value = mock_response()content, filename = reader.read(url)assert content == "print('Hello, world!')"@@ -314,7 +314,7 @@ def test_github_source_reader_different_extensions():for url in urls:assert reader.can_read(url) is Truewith patch("urllib.request.urlopen") as mock_urlopen:- mock_response = mock_open(read_data="content".encode())+ mock_response = mock_open(read_data=b"content")mock_urlopen.return_value = mock_response()content, filename = reader.read(url)assert content == "content"diff --git a/tests/_cli/test_parse_args.py b/tests/_cli/test_parse_args.pyindex e4a7d23163..6275894aaf 100644--- a/tests/_cli/test_parse_args.py+++ b/tests/_cli/test_parse_args.py@@ -5,7 +5,7 @@ from marimo._cli.parse_args import parse_argsdef test_parse_args_no_args():assert parse_args(()) == {} # type: ignore- assert parse_args(("")) == {}+ assert parse_args("") == {}def test_parse_args_non_dashed():diff --git a/tests/_config/test_config_utils.py b/tests/_config/test_config_utils.pyindex ec01695936..db5f79ce64 100644--- a/tests/_config/test_config_utils.py+++ b/tests/_config/test_config_utils.py@@ -5,7 +5,7 @@ import osimport tempfilefrom contextlib import contextmanagerfrom pathlib import Path-from typing import List, Optional+from typing import Optionalfrom unittest import mockfrom marimo._config.utils import (@@ -16,8 +16,8 @@ from marimo._config.utils import (@contextmanagerdef _mock_file_exists(- exists: Optional[str | List[str]] = None,- doesnt_exist: Optional[str | List[str]] = None,+ exists: Optional[str | list[str]] = None,+ doesnt_exist: Optional[str | list[str]] = None,):if isinstance(exists, str):exists = [exists]diff --git a/tests/_data/mocks.py b/tests/_data/mocks.pyindex bd5abc3c69..d58f470ffb 100644--- a/tests/_data/mocks.py+++ b/tests/_data/mocks.py@@ -1,20 +1,22 @@from __future__ import annotationsimport datetime-from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Sequence+from typing import TYPE_CHECKING, Any, Literal, Optionalfrom marimo._dependencies.dependencies import DependencyManagerif TYPE_CHECKING:+ from collections.abc import Sequence+from narwhals.typing import IntoDataFrameDFType = Literal["pandas", "polars", "ibis", "pyarrow", "duckdb"]def create_dataframes(- data: Dict[str, Sequence[Any]],- include: Optional[List[DFType]] = None,- exclude: Optional[List[DFType]] = None,+ data: dict[str, Sequence[Any]],+ include: Optional[list[DFType]] = None,+ exclude: Optional[list[DFType]] = None,strict: bool = True,) -> list[IntoDataFrame]:dfs: list[IntoDataFrame] = []diff --git a/tests/_data/test_charts.py b/tests/_data/test_charts.pyindex c84852c304..a3ff29e2af 100644--- a/tests/_data/test_charts.py+++ b/tests/_data/test_charts.py@@ -1,7 +1,6 @@from __future__ import annotationsimport ast-from typing import List, Tupleimport pytest@@ -10,7 +9,7 @@ from marimo._data.models import DataTypefrom marimo._dependencies.dependencies import DependencyManagerfrom tests.mocks import snapshotter-TYPES: List[Tuple[DataType, bool]] = [+TYPES: list[tuple[DataType, bool]] = [("boolean", False),("date", False),("datetime", False),@@ -35,7 +34,7 @@ def test_get_chart_builder():def test_charts_altair_code():- outputs: List[str] = []+ outputs: list[str] = []for t, should_limit_to_10_items in TYPES:builder = get_chart_builder(t, should_limit_to_10_items)@@ -52,7 +51,7 @@ def test_charts_altair_code():def test_charts_bad_characters():- outputs: List[str] = []+ outputs: list[str] = []builder = get_chart_builder("string", False)chars = {"<": "angles",@@ -72,7 +71,7 @@ def test_charts_bad_characters():@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")def test_charts_altair_json():- outputs: List[str] = []+ outputs: list[str] = []import altair as altimport pandas as pddiff --git a/tests/_data/test_preview_column.py b/tests/_data/test_preview_column.pyindex 110a8296a8..68a859c471 100644--- a/tests/_data/test_preview_column.py+++ b/tests/_data/test_preview_column.py@@ -1,7 +1,7 @@from __future__ import annotationsimport sys-from typing import Generator+from typing import TYPE_CHECKINGimport pytest@@ -16,6 +16,9 @@ from marimo._plugins.ui._impl.charts.altair_transformer import (from marimo._runtime.requests import PreviewDatasetColumnRequestfrom tests.mocks import snapshotter+if TYPE_CHECKING:+ from collections.abc import Generator+HAS_DF_DEPS = DependencyManager.pandas.has() and DependencyManager.altair.has()HAS_SQL_DEPS = DependencyManager.duckdb.has()diff --git a/tests/_output/formatters/test_structures.py b/tests/_output/formatters/test_structures.pyindex 1daaacea38..a85805e342 100644--- a/tests/_output/formatters/test_structures.py+++ b/tests/_output/formatters/test_structures.py@@ -1,7 +1,7 @@from __future__ import annotationsimport sys-from typing import Any, List, cast+from typing import Any, castfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.formatters.structures import (@@ -53,7 +53,7 @@ async def test_matplotlib_special_case(def test_format_structure_types() -> None:formatted = cast(- List[Any], format_structure(["hello", True, False, None, 1, 1.0])+ list[Any], format_structure(["hello", True, False, None, 1, 1.0]))assert formatted[0] == "hello"assert formatted[1] is Truediff --git a/tests/_plugins/core/test_json_encoder.py b/tests/_plugins/core/test_json_encoder.pyindex d605d9e3af..a0f47b2197 100644--- a/tests/_plugins/core/test_json_encoder.py+++ b/tests/_plugins/core/test_json_encoder.py@@ -5,7 +5,7 @@ import dataclassesimport jsonfrom collections import namedtuplefrom dataclasses import dataclass-from typing import Any, Dict, List, Optional+from typing import Any, Optionalimport pytest@@ -147,8 +147,8 @@ def test_nested_mime_encoding() -> None:class MockDataclass:a: intb: str- items: Optional[List[Any]] = None- other_items: Optional[Dict[str, Any]] = None+ items: Optional[list[Any]] = None+ other_items: Optional[dict[str, Any]] = Noneclass Button(MIME):diff --git a/tests/_plugins/ui/_impl/chat/test_chat.py b/tests/_plugins/ui/_impl/chat/test_chat.pyindex 32d7465592..e22600adff 100644--- a/tests/_plugins/ui/_impl/chat/test_chat.py+++ b/tests/_plugins/ui/_impl/chat/test_chat.py@@ -2,7 +2,7 @@from __future__ import annotationsimport asyncio-from typing import AsyncIterator, Dict, List+from typing import TYPE_CHECKINGimport pytest@@ -22,10 +22,13 @@ from marimo._runtime.requests import SetUIElementValueRequestfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider+if TYPE_CHECKING:+ from collections.abc import AsyncIterator+def test_chat_init():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"@@ -38,19 +41,19 @@ def test_chat_init():def test_chat_with_prompts():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"- prompts: List[str] = ["Hello", "How are you?"]+ prompts: list[str] = ["Hello", "How are you?"]chat = ui.chat(mock_model, prompts=prompts)assert chat._component_args["prompts"] == promptsdef test_chat_with_config():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"@@ -62,7 +65,7 @@ def test_chat_with_config():async def test_chat_send_prompt():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del configreturn f"Response to: {messages[-1].content}"@@ -84,7 +87,7 @@ async def test_chat_send_prompt():async def test_chat_send_prompt_async_function():async def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del configawait asyncio.sleep(0.01)@@ -107,7 +110,7 @@ async def test_chat_send_prompt_async_function():async def test_chat_send_prompt_async_generator():async def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> AsyncIterator[str]:del configdel messages@@ -133,7 +136,7 @@ async def test_chat_send_prompt_async_generator():def test_chat_get_history():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"@@ -157,7 +160,7 @@ def test_chat_get_history():def test_chat_delete_history():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"@@ -179,7 +182,7 @@ def test_chat_delete_history():def test_chat_delete_message():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"@@ -202,20 +205,20 @@ def test_chat_delete_message():def test_chat_convert_value():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"chat = ui.chat(mock_model)- value: Dict[str, List[Dict[str, str]]] = {+ value: dict[str, list[dict[str, str]]] = {"messages": [{"role": "user", "content": "Hello"},{"role": "assistant", "content": "Hi there!"},]}- converted: List[ChatMessage] = chat._convert_value(value)+ converted: list[ChatMessage] = chat._convert_value(value)assert len(converted) == 2assert converted[0].role == "user"assert converted[0].content == "Hello"@@ -225,7 +228,7 @@ def test_chat_convert_value():def test_chat_convert_value_invalid():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"@@ -238,14 +241,14 @@ def test_chat_convert_value_invalid():async def test_chat_with_on_message():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"on_message_called = False- def on_message(messages: List[ChatMessage]) -> None:+ def on_message(messages: list[ChatMessage]) -> None:del messagesnonlocal on_message_calledon_message_called = True@@ -262,7 +265,7 @@ async def test_chat_with_on_message():def test_chat_with_show_configuration_controls():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"@@ -273,7 +276,7 @@ def test_chat_with_show_configuration_controls():async def test_chat_clear_messages():def mock_model(- messages: List[ChatMessage], config: ChatModelConfig+ messages: list[ChatMessage], config: ChatModelConfig) -> str:del messages, configreturn "Mock response"diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.pyindex bfd2702c92..224a961c50 100644--- a/tests/_plugins/ui/_impl/tables/test_default_table.py+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport unittestfrom datetime import date-from typing import Any, Dict+from typing import Anyimport pytest@@ -292,7 +292,7 @@ class TestDefaultTable(unittest.TestCase):class TestColumnarDefaultTable(unittest.TestCase):def setUp(self) -> None:- self.data: Dict[str, Any] = {+ self.data: dict[str, Any] = {"name": ["Alice", "Bob", "Charlie", "Dave", "Eve"],"age": [30, 25, 35, 28, 22],"birth_year": [diff --git a/tests/_runtime/test_capture.py b/tests/_runtime/test_capture.pyindex 70ef79bf2b..d1c21a60e5 100644--- a/tests/_runtime/test_capture.py+++ b/tests/_runtime/test_capture.py@@ -2,13 +2,13 @@from __future__ import annotationsimport re-from typing import Any, Dict, Tuple+from typing import Anyfrom tests.conftest import ExecReqProvider, MockedKerneldef _has_output(- messages: list[Tuple[str, Dict[Any, Any]]], pattern: str+ messages: list[tuple[str, dict[Any, Any]]], pattern: str) -> bool:for op, data in messages:if (diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 8d67f79969..93964612aa 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -5,7 +5,7 @@ import pathlibimport sysimport textwrapfrom dataclasses import dataclass-from typing import Sequence+from typing import TYPE_CHECKINGimport pytest@@ -44,6 +44,9 @@ from marimo._server.model import SessionModefrom marimo._utils.parse_dataclass import parse_rawfrom tests.conftest import ExecReqProvider, MockedKernel+if TYPE_CHECKING:+ from collections.abc import Sequence+def _check_edges(error: Error, expected_edges: Sequence[EdgeWithVar]) -> None:assert isinstance(error, CycleError)diff --git a/tests/_save/mocks.py b/tests/_save/mocks.pyindex 0ec2c73dec..d84e8dc380 100644--- a/tests/_save/mocks.py+++ b/tests/_save/mocks.py@@ -1,6 +1,6 @@from __future__ import annotations-from typing import Any, Dict, Optional+from typing import Any, Optionalfrom marimo._save.cache import Cache, CacheTypefrom marimo._save.loaders import Loader@@ -11,7 +11,7 @@ class MockLoader(Loader):self,name: str = "mock",save_path: str = "",- data: Optional[Dict[str, Any]] = None,+ data: Optional[dict[str, Any]] = None,stateful_refs: Optional[set[str]] = None,) -> None:self.save_path = save_pathdiff --git a/tests/_schemas/test_schema.py b/tests/_schemas/test_schema.pyindex 8ef8929cf4..ae12ee2293 100644--- a/tests/_schemas/test_schema.py+++ b/tests/_schemas/test_schema.py@@ -13,7 +13,7 @@ import yamlreason="This test is flaky on Windows",)def test_session_schema_up_to_date() -> None:- with open("marimo/_schemas/generated/session.yaml", "r") as f:+ with open("marimo/_schemas/generated/session.yaml") as f:current_content = yaml.safe_load(f)script_path = (diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex 70802e3d6d..6f739a7162 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport unittestfrom contextlib import contextmanagerfrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any, List+from typing import TYPE_CHECKING, Anyfrom unittest.mock import MagicMock, patchimport pytest@@ -56,7 +56,7 @@ class Choice:# OpenAI@dataclassclass FakeChoices:- choices: List[Choice]+ choices: list[Choice]@pytest.mark.skipif(@@ -476,7 +476,7 @@ def no_google_ai_config(config: UserConfigManager):class TestStreamResponse(unittest.TestCase):- def simulate_stream(self, contents: List[str]) -> Any:+ def simulate_stream(self, contents: list[str]) -> Any:@dataclassclass MockContent:content: strdiff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.pyindex ee954a3f90..3b48955177 100644--- a/tests/_server/api/endpoints/test_file_explorer.py+++ b/tests/_server/api/endpoints/test_file_explorer.py@@ -84,7 +84,7 @@ def test_update_file(client: TestClient) -> None:assert response.status_code == 200, response.textassert response.headers["content-type"] == "application/json"assert response.json()["success"] is True- with open(test_file_path, "r") as f:+ with open(test_file_path) as f:assert f.read() == "new content"with open(test_file_path, "w") as f:f.write(test_content)diff --git a/tests/_server/api/endpoints/test_ws_rtc.py b/tests/_server/api/endpoints/test_ws_rtc.pyindex 72a367449c..047dea19ca 100644--- a/tests/_server/api/endpoints/test_ws_rtc.py+++ b/tests/_server/api/endpoints/test_ws_rtc.py@@ -1,7 +1,7 @@from __future__ import annotationsimport asyncio-from typing import AsyncGenerator+from typing import TYPE_CHECKINGimport pytestfrom pycrdt import Doc, Text@@ -15,6 +15,9 @@ from marimo._server.api.endpoints.ws import (from marimo._server.file_router import MarimoFileKeyfrom marimo._types.ids import CellId_t+if TYPE_CHECKING:+ from collections.abc import AsyncGenerator+@pytest.fixture # type: ignoreasync def setup_ycell() -> AsyncGenerator[None, None]:diff --git a/tests/_server/api/test_auth.py b/tests/_server/api/test_auth.pyindex aa74bd33a8..62b1ef8dd7 100644--- a/tests/_server/api/test_auth.py+++ b/tests/_server/api/test_auth.py@@ -132,7 +132,7 @@ async def test_validate_auth_with_missing_password_in_basic_auth(conn = create_connection(app)# Run all middlewareawait app.build_middleware_stack()(conn.scope, mock_receive, mock_send)- basic_auth_header = f"Basic {base64.b64encode('test:'.encode()).decode()}"+ basic_auth_header = f"Basic {base64.b64encode(b'test:').decode()}"conn._headers = Headers({"Authorization": basic_auth_header})assert validate_auth(conn) is Falsediff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.pyindex e4bfd30ca4..45d25ad022 100644--- a/tests/_server/api/test_middleware.py+++ b/tests/_server/api/test_middleware.py@@ -5,7 +5,7 @@ import ioimport jsonimport timefrom multiprocessing import Process-from typing import TYPE_CHECKING, Any, Tuple+from typing import TYPE_CHECKING, Anyimport pytestimport uvicorn@@ -373,7 +373,7 @@ class TestProxyMiddleware:@pytest.fixturedef app_with_mpl_proxy(- self, edit_app: Starlette, mpl_server: Tuple[str, int]+ self, edit_app: Starlette, mpl_server: tuple[str, int]) -> ASGIApp:"""Create the app with ProxyMiddleware targeting the matplotlib plugin server."""host, port = mpl_serverdiff --git a/tests/_server/conftest.py b/tests/_server/conftest.pyindex f0855e82e3..49cbc9b577 100644--- a/tests/_server/conftest.py+++ b/tests/_server/conftest.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport osimport sysfrom tempfile import TemporaryDirectory-from typing import Generator, Iterator+from typing import TYPE_CHECKINGimport pytestimport uvicorn@@ -17,6 +17,9 @@ from marimo._server.sessions import SessionManagerfrom marimo._server.utils import initialize_asynciofrom tests._server.mocks import get_mock_session_manager+if TYPE_CHECKING:+ from collections.abc import Generator, Iterator+app = create_starlette_app(base_url="", enable_auth=True)diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.pyindex 7009fe9b22..c53aafa07d 100644--- a/tests/_server/files/test_os_file_system.py+++ b/tests/_server/files/test_os_file_system.py@@ -84,7 +84,7 @@ def test_get_details(test_dir: str, fs: OSFileSystem) -> None:test_dir,"file",test_file_name,- "some content".encode("utf-8"),+ b"some content",)file_info = fs.get_details(os.path.join(test_dir, test_file_name))assert isinstance(file_info, FileDetailsResponse)@@ -168,7 +168,7 @@ def test_update_file(test_dir: str, fs: OSFileSystem) -> None:f.write("Initial content")new_content = "Updated content"fs.update_file(file_path, new_content)- with open(file_path, "r") as f:+ with open(file_path) as f:assert f.read() == new_contentdiff --git a/tests/_server/mocks.py b/tests/_server/mocks.pyindex d32359b463..fec56a379d 100644--- a/tests/_server/mocks.py+++ b/tests/_server/mocks.py@@ -24,7 +24,7 @@ def get_mock_session_manager() -> SessionManager:temp_file = tempfile.NamedTemporaryFile(suffix=".py", delete=False)temp_file.write(- """+ b"""import marimo__generated_with = "0.0.1"@@ -39,7 +39,7 @@ def __():if __name__ == "__main__":app.run()-""".encode()+""")temp_file.close()diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.pyindex 634ff67acf..5033a0ee3e 100644--- a/tests/_server/templates/test_templates.py+++ b/tests/_server/templates/test_templates.py@@ -25,7 +25,7 @@ class TestNotebookPageTemplate(unittest.TestCase):os.path.join(os.path.dirname(__file__), "data"))index_html = os.path.join(root, "index.html")- with open(index_html, "r") as f:+ with open(index_html) as f:self.html = f.read()self.base_url = "/subpath"@@ -152,7 +152,7 @@ class TestHomePageTemplate(unittest.TestCase):os.path.join(os.path.dirname(__file__), "data"))index_html = os.path.join(root, "index.html")- with open(index_html, "r") as f:+ with open(index_html) as f:self.html = f.read()self.base_url = "/subpath"@@ -186,7 +186,7 @@ class TestStaticNotebookTemplate(unittest.TestCase):os.path.join(os.path.dirname(__file__), "data"))index_html = os.path.join(root, "index.html")- with open(index_html, "r") as f:+ with open(index_html) as f:self.html = f.read()self.user_config = DEFAULT_CONFIG@@ -371,7 +371,7 @@ class TestWasmNotebookTemplate(unittest.TestCase):os.path.join(os.path.dirname(__file__), "data"))index_html = os.path.join(root, "index.html")- with open(index_html, "r") as f:+ with open(index_html) as f:self.html = f.read()self.version = "1.0.0"diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.pyindex f4252ff870..1cf2f80edd 100644--- a/tests/_server/test_file_manager.py+++ b/tests/_server/test_file_manager.py@@ -4,7 +4,7 @@ import osimport shutilimport sysimport tempfile-from typing import Generator+from typing import TYPE_CHECKINGimport pytest@@ -14,6 +14,9 @@ from marimo._server.api.status import HTTPException, HTTPStatusfrom marimo._server.file_manager import AppFileManagerfrom marimo._server.models.models import SaveNotebookRequest+if TYPE_CHECKING:+ from collections.abc import Generator+save_request = SaveNotebookRequest(cell_ids=["1"],filename="save_existing.py",@@ -32,7 +35,7 @@ def app_file_manager() -> Generator[AppFileManager, None, None]:temp_file = tempfile.NamedTemporaryFile(suffix=".py", delete=False)temp_file.write(- """+ b"""import marimo__generated_with = "0.0.1"app = marimo.App()@@ -43,7 +46,7 @@ def __():return mo,if __name__ == "__main__":app.run()-""".encode()+""")temp_file.close()@@ -130,7 +133,7 @@ def test_rename_different_filetype(app_file_manager: AppFileManager) -> None:initial_filename = app_file_manager.filenameassert initial_filenameassert initial_filename.endswith(".py")- with open(initial_filename, "r") as f:+ with open(initial_filename) as f:contents = f.read()assert "app = marimo.App()" in contentsassert "marimo-version" not in contents@@ -138,7 +141,7 @@ def test_rename_different_filetype(app_file_manager: AppFileManager) -> None:next_filename = app_file_manager.filenameassert next_filenameassert next_filename.endswith(".md")- with open(next_filename, "r") as f:+ with open(next_filename) as f:contents = f.read()assert "marimo-version" in contentsassert "app = marimo.App()" not in contents@@ -148,7 +151,7 @@ def test_save_app_config_valid(app_file_manager: AppFileManager) -> None:app_file_manager.filename = "app_config.py"try:app_file_manager.save_app_config({})- with open(app_file_manager.filename, "r", encoding="utf-8") as f:+ with open(app_file_manager.filename, encoding="utf-8") as f:contents = f.read()assert "app = marimo.App" in contentsfinally:diff --git a/tests/_server/test_file_router.py b/tests/_server/test_file_router.pyindex 454dcac197..9023d247fe 100644--- a/tests/_server/test_file_router.py+++ b/tests/_server/test_file_router.py@@ -39,7 +39,7 @@ class TestAppFileRouter(unittest.TestCase):self.test_file1.close()self.test_file2.write(file_contents.encode())self.test_file2.close()- self.test_file_3.write("marimo-version: 0.0.0".encode())+ self.test_file_3.write(b"marimo-version: 0.0.0")self.test_file_3.close()# Create a nested directory and filediff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex 7ef963e470..f8c5dc1bea 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -216,11 +216,11 @@ def test_kernel_manager_interrupt(tmp_path) -> None:kernel_manager.interrupt_kernel()try:- with open(file, "r") as f:+ with open(file) as f:assert f.read() == "0"# if kernel failed to interrupt, f will read as "1"time.sleep(1.5)- with open(file, "r") as f:+ with open(file) as f:assert f.read() == "0"finally:if sys.platform == "win32":diff --git a/tests/_smoke_tests/run_all.py b/tests/_smoke_tests/run_all.pyindex 161156a776..f17af69f98 100644--- a/tests/_smoke_tests/run_all.py+++ b/tests/_smoke_tests/run_all.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport asyncioimport osimport pathlib-from typing import Any, Dict, Optional+from typing import Any, Optionalimport pytestimport yaml@@ -23,7 +23,7 @@ async def test_all_smoke_tests() -> None:all_py_paths = list(pathlib.Path(root).rglob("*.py"))assert all_py_paths, "No smoke tests found"- with open(config_file, "r") as f: # noqa: ASYNC101 ASYNC230+ with open(config_file) as f: # noqa: ASYNC101 ASYNC230smoke_test_config = yaml.load(f.read(), Loader=yaml.FullLoader)semaphore = asyncio.Semaphore(CONCURRENT_TESTS)@@ -41,7 +41,7 @@ async def test_all_examples() -> None:all_py_paths = list(pathlib.Path(root).rglob("*.py"))assert all_py_paths, "No examples found"- with open(config_file, "r") as f: # noqa: ASYNC101 ASYNC230+ with open(config_file) as f: # noqa: ASYNC101 ASYNC230smoke_test_config = yaml.load(f.read(), Loader=yaml.FullLoader)semaphore = asyncio.Semaphore(CONCURRENT_TESTS)@@ -55,7 +55,7 @@ async def test_all_examples() -> None:async def _run_test(file: pathlib.Path,root: str,- smoke_test_config: Dict[str, Any],+ smoke_test_config: dict[str, Any],semaphore: asyncio.Semaphore,with_uv: bool,) -> None:@@ -71,7 +71,7 @@ async def _run_test()input_data = file_config.get("input", None)- with open(file, "r") as f: # noqa: ASYNC101 ASYNC230+ with open(file) as f: # noqa: ASYNC101 ASYNC230content = f.read()if "marimo.App(" not in content:returndiff --git a/tests/_sql/test_duckdb.py b/tests/_sql/test_duckdb.pyindex 3de30550f0..d9af35dd29 100644--- a/tests/_sql/test_duckdb.py+++ b/tests/_sql/test_duckdb.py@@ -3,7 +3,7 @@from __future__ import annotationsfrom copy import deepcopy-from typing import TYPE_CHECKING, Generator+from typing import TYPE_CHECKINGimport pytest@@ -18,6 +18,8 @@ HAS_DUCKDB = DependencyManager.duckdb.has()HAS_PANDAS = DependencyManager.pandas.has()if TYPE_CHECKING:+ from collections.abc import Generator+import duckdbdiff --git a/tests/_sql/test_sql.py b/tests/_sql/test_sql.pyindex f99d9f5d46..cf75cf6cef 100644--- a/tests/_sql/test_sql.py+++ b/tests/_sql/test_sql.py@@ -3,7 +3,7 @@from __future__ import annotationsimport os-from typing import TYPE_CHECKING, Generator+from typing import TYPE_CHECKINGfrom unittest.mock import MagicMock, patchimport pytest@@ -13,6 +13,8 @@ from marimo._plugins import uifrom marimo._sql.sql import _query_includes_limit, sqlif TYPE_CHECKING:+ from collections.abc import Generator+import duckdbimport sqlalchemy as sadiff --git a/tests/_utils/test_dataclass_to_openapi.py b/tests/_utils/test_dataclass_to_openapi.pyindex f33b720981..058cbc5c95 100644--- a/tests/_utils/test_dataclass_to_openapi.py+++ b/tests/_utils/test_dataclass_to_openapi.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport dataclassesimport sys-from typing import Any, ClassVar, List, Literal, Optional, TypedDict, Union+from typing import Any, ClassVar, Literal, Optional, TypedDict, Unionimport pytest@@ -24,7 +24,7 @@ class Person:name: strage: intaddress: Address- tags: List[str]+ tags: list[str]metadata: Anydiff --git a/tests/_utils/test_file_watcher.py b/tests/_utils/test_file_watcher.pyindex 88d0e6b125..c25c2dafa6 100644--- a/tests/_utils/test_file_watcher.py+++ b/tests/_utils/test_file_watcher.py@@ -6,7 +6,6 @@ import osimport sysfrom pathlib import Pathfrom tempfile import NamedTemporaryFile-from typing import Listimport pytest@@ -17,7 +16,7 @@ async def test_polling_file_watcher() -> None:with NamedTemporaryFile(delete=False) as tmp_file:tmp_path = Path(tmp_file.name)- callback_calls: List[Path] = []+ callback_calls: list[Path] = []async def test_callback(path: Path):return callback_calls.append(path)@@ -64,9 +63,9 @@ async def test_file_watcher_manager() -> None:try:# Track callback calls- callback1_calls: List[Path] = []- callback2_calls: List[Path] = []- callback3_calls: List[Path] = []+ callback1_calls: list[Path] = []+ callback2_calls: list[Path] = []+ callback3_calls: list[Path] = []async def callback1(path: Path) -> None:callback1_calls.append(path)diff --git a/tests/_utils/test_flatten.py b/tests/_utils/test_flatten.pyindex ea2f142c20..770414637a 100644--- a/tests/_utils/test_flatten.py+++ b/tests/_utils/test_flatten.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Dict, List, Tuple+from typing import Anyimport pytest@@ -11,9 +11,9 @@ from marimo._utils.flatten import (flatten,)-L = List[Any]-T = Tuple[Any, ...]-D = Dict[Any, Any]+L = list[Any]+T = tuple[Any, ...]+D = dict[Any, Any]def test_flat_list() -> None:diff --git a/tests/_utils/test_parse_dataclass.py b/tests/_utils/test_parse_dataclass.pyindex a2bab0e0f8..9ef6e2c2a4 100644--- a/tests/_utils/test_parse_dataclass.py+++ b/tests/_utils/test_parse_dataclass.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport jsonfrom dataclasses import asdict, dataclassfrom enum import Enum-from typing import Any, Dict, List, Literal, Optional, Tuple, Union+from typing import Any, Literal, Optional, Unionimport pytest@@ -92,7 +92,7 @@ class TestParseRaw:def test_nested_list(self) -> None:@dataclassclass Nested:- configs: List[Config]+ configs: list[Config]nested = Nested(configs=[@@ -107,7 +107,7 @@ class TestParseRaw:def test_nested_dict(self) -> None:@dataclassclass Nested:- configs: Dict[str, Config]+ configs: dict[str, Config]nested = Nested(configs={@@ -122,7 +122,7 @@ class TestParseRaw:def test_nested_tuple_ellipses(self) -> None:@dataclassclass Nested:- configs: Tuple[Config, ...]+ configs: tuple[Config, ...]nested = Nested(configs=tuple(@@ -139,7 +139,7 @@ class TestParseRaw:def test_nested_tuple_fixed(self) -> None:@dataclassclass Nested:- configs: Tuple[str, Config]+ configs: tuple[str, Config]nested = Nested(configs=(diff --git a/tests/conftest.py b/tests/conftest.pyindex c6f7d9f1df..35cc7720d7 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -8,7 +8,7 @@ import reimport sysimport textwrapfrom tempfile import TemporaryDirectory-from typing import TYPE_CHECKING, Any, Generator+from typing import TYPE_CHECKING, Anyimport pytestfrom _pytest import runner@@ -37,6 +37,7 @@ from marimo._types.ids import CellId_tfrom marimo._utils.parse_dataclass import parse_rawif TYPE_CHECKING:+ from collections.abc import Generatorfrom types import ModuleType# register import hooks for third-party module formattersdiff --git a/tests/mocks.py b/tests/mocks.pyindex 4971a31470..4729ff5506 100644--- a/tests/mocks.py+++ b/tests/mocks.py@@ -44,7 +44,7 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:print("Snapshot updated")# Read snapshot- with open(filepath, "r") as f:+ with open(filepath) as f:expected = normalize(f.read())assert result, "Result is empty"diff --git a/tests/test_api.py b/tests/test_api.pyindex d47d1d344f..26ca42246c 100644--- a/tests/test_api.py+++ b/tests/test_api.py@@ -1,7 +1,7 @@from __future__ import annotationsimport inspect-from typing import Any, Optional, Set+from typing import Any, Optionalfrom tests.mocks import snapshotter@@ -9,7 +9,7 @@ snapshot = snapshotter(__file__)def _explore_module(- module: Any, indent: int = 0, visited: Optional[Set[int]] = None+ module: Any, indent: int = 0, visited: Optional[set[int]] = None) -> list[str]:"""Recursively explore a module and print all public exported items.