Skip to content

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

additional ruff fixes (#9132)

Shahmir Varqha0c319d2fc503
diff --git a/marimo/__init__.py b/marimo/__init__.py
index d461312b3d..9c21e8a099 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -14,7 +14,7 @@ marimo is designed to be:
5. fun
"""
-__all__ = [
+__all__ = [ # noqa: RUF022
# Core API
"App",
"Cell",
diff --git a/marimo/_ai/_tools/base.py b/marimo/_ai/_tools/base.py
index 3105a0e559..89f2685e5e 100644
--- a/marimo/_ai/_tools/base.py
+++ b/marimo/_ai/_tools/base.py
@@ -263,7 +263,7 @@ class ToolContext:
)
-class ToolBase(Generic[ArgsT, OutT], ABC):
+class ToolBase(ABC, Generic[ArgsT, OutT]):
"""
Minimal base class for dual-registered tools.
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 04233c6be3..ab46d52bbb 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -735,7 +735,7 @@ class App:
if self._filename is not None:
# Run linting checks to provide better error messages for breaking errors.
- linter, messages = collect_messages(self._filename)
+ _linter, messages = collect_messages(self._filename)
if messages:
sys.stderr.write(messages)
# Re-raise the original exception but without trace
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index defc900ab1..7257aed199 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -274,9 +274,9 @@ class CellImpl:
@property
def imported_namespaces(self) -> set[Name]:
"""Return a set of the namespaces imported by this cell."""
- return set(
+ return {
import_data.module.split(".")[0] for import_data in self.imports
- )
+ }
def namespace_to_variable(self, namespace: str) -> Name | None:
"""Returns the variable name corresponding to an imported namespace
@@ -322,7 +322,7 @@ class CellImpl:
# Check that def matches the single definition
name = tree.body[0].name
ast_name = unmangle_local(variables.pop()).name
- if not (name == ast_name):
+ if name != ast_name:
return None
if name.startswith("_"):
@@ -334,7 +334,7 @@ class CellImpl:
):
return None
- return list(variable_data)[0]
+ return next(iter(variable_data))
@property
def init_variable_data(self) -> dict[Name, VariableData]:
diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.py
index 9c74ab2b29..ef91125a6b 100644
--- a/marimo/_ast/cell_manager.py
+++ b/marimo/_ast/cell_manager.py
@@ -511,7 +511,7 @@ class CellManager:
self._cell_data = new_cell_data
# Add the new ids to the set, so we don't reuse them in the future
- for _id in id_mapping.keys():
+ for _id in id_mapping:
self._cell_id_generator.seen_ids.add(_id)
@property
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 87c1ff4a24..d7dabb03ee 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -296,7 +296,7 @@ def to_functiondef(
if allowed_refs is None:
allowed_refs = BUILTINS
- refs: tuple[str, ...] = tuple()
+ refs: tuple[str, ...] = ()
sorted_refs = sorted(cell.refs)
for ref in sorted_refs:
if ref not in allowed_refs:
@@ -323,7 +323,7 @@ def to_functiondef(
# external call. We collect them such that we can determine if a variable
# def is actually ever used. This is a nice little trick such that mypy and
# other static analysis tools can capture unused variables across cells.
- defs: tuple[str, ...] = tuple()
+ defs: tuple[str, ...] = ()
if cell.defs:
# SQL defs should not be included in the return value.
sql_defs = (
@@ -389,7 +389,7 @@ def to_top_functiondef(
decorator = to_decorator(cell.config, fn="class_definition")
else:
decorator = to_decorator(cell.config, fn="function")
- return "\n".join([decorator, cell.code.strip()])
+ return f"{decorator}\n{cell.code.strip()}"
return ""
@@ -589,9 +589,7 @@ def recover(filepath: Path) -> str:
def is_multiline_comment(node: ast.stmt) -> bool:
"""Checks if a node is a docstring or a multiline comment."""
- if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):
- return True
- return False
+ return isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant)
def get_header_comments(filename: str | Path) -> str | None:
diff --git a/marimo/_ast/scanner.py b/marimo/_ast/scanner.py
index de21d6e154..8fcc040f43 100644
--- a/marimo/_ast/scanner.py
+++ b/marimo/_ast/scanner.py
@@ -507,9 +507,7 @@ def _strip_trailing_return(body_lines: list[str]) -> None:
line_stripped = line.strip()
if line_indent == body_indent and (
line_stripped == "return"
- or line_stripped.startswith("return ")
- or line_stripped.startswith("return\t")
- or line_stripped.startswith("return(")
+ or line_stripped.startswith(("return ", "return\t", "return("))
):
# Remove the return line and any trailing blank lines after it
del body_lines[idx:]
diff --git a/marimo/_ast/toplevel.py b/marimo/_ast/toplevel.py
index ddd7db3e20..0db471d59e 100644
--- a/marimo/_ast/toplevel.py
+++ b/marimo/_ast/toplevel.py
@@ -275,9 +275,9 @@ class TopLevelExtraction:
self.collection.add(status)
# Refresh names
- potential_refs = set(
- [status.name for status in self.statuses if not status.is_toplevel]
- )
+ potential_refs = {
+ status.name for status in self.statuses if not status.is_toplevel
+ }
self.unshadowed = BUILTINS - defs
self.allowed_refs.update(self.unshadowed)
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index bc35ffb4c9..27b069094d 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -248,11 +248,11 @@ class ScopedVisitor(ast.NodeVisitor):
# so marking it as a deleted ref is in practice a big deal. For 100%
# correctness we would prune unbound locals from refs, not here but
# when variables added as defs and refs.
- return set(
+ return {
name
for name in self._refs
if any(ref.deleted for ref in self._refs[name])
- )
+ }
def _if_local_then_mangle(
self, name: str, ignore_scope: bool = False
diff --git a/marimo/_cli/files/file_path.py b/marimo/_cli/files/file_path.py
index fa753f1821..3d03b28e35 100644
--- a/marimo/_cli/files/file_path.py
+++ b/marimo/_cli/files/file_path.py
@@ -29,9 +29,7 @@ def is_github_src(url: str, ext: str) -> bool:
if hostname != "github.com" and hostname != "raw.githubusercontent.com":
return False
path: str = urllib.parse.urlparse(url).path
- if not path.endswith(ext):
- return False
- return True
+ return path.endswith(ext)
def get_github_src_url(url: str) -> str:
@@ -46,12 +44,7 @@ def is_gist_src(url: str) -> bool:
return False
hostname = urllib.parse.urlparse(url).hostname
- if (
- hostname != "gist.github.com"
- and hostname != "gist.githubusercontent.com"
- ):
- return False
- return True
+ return hostname in ("gist.github.com", "gist.githubusercontent.com")
def get_gist_src_url(url: str) -> str:
@@ -277,11 +270,11 @@ class FileContentReader:
Args:
name (str): File path or URL
- Raises:
- ValueError: If the file cannot be read
-
Returns:
Tuple[str, str]: File content and filename
+
+ Raises:
+ ValueError: If the file cannot be read
"""
for reader in self.readers:
if reader.can_read(name):
@@ -422,11 +415,11 @@ def validate_name(
allow_new_file (bool): Whether to allow creating a new file
allow_directory (bool): Whether to allow a directory
- Raises:
- ValueError: If the file name is invalid
-
Returns:
Path to the file and temporary directory
+
+ Raises:
+ ValueError: If the file name is invalid
"""
from marimo._cli.files.cloudflare import R2FileHandler
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index 4920ccf963..6a22fe8849 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -84,6 +84,8 @@ if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
from types import TracebackType
+ from typing_extensions import Self
+
from marimo._ast.cell_manager import CellManager
from marimo._runtime.dataflow import DirectedGraph
from marimo._runtime.runtime import Kernel
@@ -591,7 +593,7 @@ class AsyncCodeModeContext:
# Async context manager
# ------------------------------------------------------------------
- async def __aenter__(self) -> AsyncCodeModeContext:
+ async def __aenter__(self) -> Self:
self._ops = []
self._pending_adds = {}
self._packages_to_install = []
diff --git a/marimo/_convert/common/__init__.py b/marimo/_convert/common/__init__.py
index d50666223b..3193834246 100644
--- a/marimo/_convert/common/__init__.py
+++ b/marimo/_convert/common/__init__.py
@@ -20,7 +20,7 @@ from marimo._convert.common.format import (
sql_to_marimo,
)
-__all__ = [
+__all__ = [ # noqa: RUF022
# utils
"get_download_filename",
"get_filename",
diff --git a/marimo/_convert/ipynb/__init__.py b/marimo/_convert/ipynb/__init__.py
index 4cc7b6fd0f..719063e54d 100644
--- a/marimo/_convert/ipynb/__init__.py
+++ b/marimo/_convert/ipynb/__init__.py
@@ -15,7 +15,7 @@ from marimo._convert.ipynb.to_ir import (
convert_from_ipynb_to_notebook_ir,
)
-__all__ = [
+__all__ = [ # noqa: RUF022
# Export (IR → ipynb)
"convert_from_ir_to_ipynb",
# Import (ipynb → IR)
diff --git a/marimo/_convert/ipynb/to_ir.py b/marimo/_convert/ipynb/to_ir.py
index e0353fade3..181c5a8f6c 100644
--- a/marimo/_convert/ipynb/to_ir.py
+++ b/marimo/_convert/ipynb/to_ir.py
@@ -204,15 +204,13 @@ def transform_add_marimo_import(sources: list[CodeCell]) -> list[CodeCell]:
def is_in_import_line(line: str) -> bool:
if line.startswith("import marimo as mo"):
return True
- if line.startswith("import ") or line.startswith("from "):
+ if line.startswith(("import ", "from ")):
return "import marimo as mo" in line
return False
# Slow check
lines = cell.strip().split("\n")
- if any(is_in_import_line(line) for line in lines):
- return True
- return False
+ return any(is_in_import_line(line) for line in lines)
already_has_marimo_import = any(
has_marimo_import(cell.source) for cell in sources
@@ -243,15 +241,11 @@ def transform_add_subprocess_import(
def is_in_import_line(line: str) -> bool:
stripped = line.strip()
- if stripped.startswith("import subprocess"):
- return True
- return False
+ return stripped.startswith("import subprocess")
# Slow check
lines = cell.strip().split("\n")
- if any(is_in_import_line(line) for line in lines):
- return True
- return False
+ return any(is_in_import_line(line) for line in lines)
already_has_subprocess_import = any(
has_subprocess_import(cell.source) for cell in sources
diff --git a/marimo/_convert/markdown/to_ir.py b/marimo/_convert/markdown/to_ir.py
index 0eb7b758c8..aeb6f8fd93 100644
--- a/marimo/_convert/markdown/to_ir.py
+++ b/marimo/_convert/markdown/to_ir.py
@@ -119,7 +119,7 @@ def formatted_code_block(
# ```{.python.marimo attr=...}
else:
head = f"""{guard}{{.{language}.marimo{attribute_str}}}"""
- return "\n".join([head, code, guard, ""])
+ return f"{head}\n{code}\n{guard}\n"
def app_config_from_root(root: Element) -> dict[str, Any]:
diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.py
index daacbd0ab9..7a7b5128b2 100644
--- a/marimo/_data/get_datasets.py
+++ b/marimo/_data/get_datasets.py
@@ -540,11 +540,7 @@ def _db_type_to_data_type(db_type: str) -> DataType:
if db_type in _INTEGER_TYPES or db_type.startswith("uint"):
return "integer"
- if (
- db_type in _NUMERIC_TYPES
- or db_type.startswith("decimal")
- or db_type.startswith("float")
- ):
+ if db_type in _NUMERIC_TYPES or db_type.startswith(("decimal", "float")):
return "number"
if db_type in _BOOLEAN_TYPES:
@@ -569,15 +565,9 @@ def _db_type_to_data_type(db_type: str) -> DataType:
return "string"
# Nested types
- if (
- db_type.startswith("union")
- or db_type.startswith("map")
- or db_type.startswith("struct")
- or db_type.startswith("list")
- or db_type.startswith("array")
- or db_type.startswith("json")
- or ("[" in db_type and "]" in db_type)
- ):
+ if db_type.startswith(
+ ("union", "map", "struct", "list", "array", "json")
+ ) or ("[" in db_type and "]" in db_type):
return "unknown"
# Other special types
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index d0e5f951b9..40a3a167bf 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -239,7 +239,6 @@ class DependencyManager:
pytest = Dependency("pytest")
vegafusion = Dependency("vegafusion")
vl_convert_python = Dependency("vl_convert")
- dotenv = Dependency("dotenv")
docstring_to_markdown = Dependency(
"docstring_to_markdown", min_version="0.17.0"
)
diff --git a/marimo/_lint/rule_engine.py b/marimo/_lint/rule_engine.py
index 124f61dae5..9660240672 100644
--- a/marimo/_lint/rule_engine.py
+++ b/marimo/_lint/rule_engine.py
@@ -47,10 +47,7 @@ class EarlyStoppingConfig:
if self.stop_on_breaking and diagnostic.severity == Severity.BREAKING:
return True
- if self.stop_on_runtime and diagnostic.severity == Severity.RUNTIME:
- return True
-
- return False
+ return self.stop_on_runtime and diagnostic.severity == Severity.RUNTIME
class RuleEngine:
@@ -86,7 +83,7 @@ class RuleEngine:
# Process rules as they complete
while pending_tasks:
# Wait for at least one task to complete
- done, pending = await asyncio.wait(
+ done, _pending = await asyncio.wait(
pending_tasks.keys(), return_when=asyncio.FIRST_COMPLETED
)
diff --git a/marimo/_lint/rules/formatting/markdown_dedent.py b/marimo/_lint/rules/formatting/markdown_dedent.py
index 9a752e8e9a..2e354ec3ca 100644
--- a/marimo/_lint/rules/formatting/markdown_dedent.py
+++ b/marimo/_lint/rules/formatting/markdown_dedent.py
@@ -102,13 +102,11 @@ class MarkdownDedentRule(LintRule):
line_count = len(cell.code.splitlines())
line_start = notebook_cell.lineno + 1
overly_dedented = any(
- [
- line[0] != " "
- for line in ctx.contents[
- line_start : line_start + line_count
- ]
- if line
+ line[0] != " "
+ for line in ctx.contents[
+ line_start : line_start + line_count
]
+ if line
)
if needs_dedent or overly_dedented:
diff --git a/marimo/_lint/rules/runtime/branch_expression.py b/marimo/_lint/rules/runtime/branch_expression.py
index 448132ba3e..f29bc56a96 100644
--- a/marimo/_lint/rules/runtime/branch_expression.py
+++ b/marimo/_lint/rules/runtime/branch_expression.py
@@ -238,9 +238,7 @@ class BranchExpressionRule(LintRule):
# Direct mo.* calls (mo.md, mo.Html, etc.)
if isinstance(func.value, ast.Name) and func.value.id == "mo":
# Exclude mo.stop()
- if func.attr == "stop":
- return False
- return True
+ return func.attr != "stop"
# mo.ui.* or other nested mo.* calls
if isinstance(func.value, ast.Attribute) and (
@@ -248,9 +246,7 @@ class BranchExpressionRule(LintRule):
and func.value.value.id == "mo"
):
# Exclude mo.output.* calls (append, replace, clear)
- if func.value.attr == "output":
- return False
- return True
+ return func.value.attr != "output"
return False
diff --git a/marimo/_lint/validate_graph.py b/marimo/_lint/validate_graph.py
index 2be61a0b64..a0d894aba6 100644
--- a/marimo/_lint/validate_graph.py
+++ b/marimo/_lint/validate_graph.py
@@ -52,9 +52,7 @@ def check_for_multiple_definitions(
) -> dict[CellId_t, list[MultipleDefinitionError]]:
"""Check whether multiple cells define the same global name."""
errors = defaultdict(list)
- defs = sorted(
- list(set().union(*(cell.defs for _, cell in graph.cells.items())))
- )
+ defs = sorted(set().union(*(cell.defs for cell in graph.cells.values())))
for name in defs:
defining_cells = graph.definitions[name]
if len(defining_cells) > 1:
@@ -62,7 +60,7 @@ def check_for_multiple_definitions(
errors[cid].append(
MultipleDefinitionError(
name=str(name),
- cells=tuple(sorted(defining_cells - set([cid]))),
+ cells=tuple(sorted(defining_cells - {cid})),
)
)
return errors
diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.py
index 6bc66deb12..dc586d4c41 100644
--- a/marimo/_messaging/console_output_worker.py
+++ b/marimo/_messaging/console_output_worker.py
@@ -61,11 +61,7 @@ def _add_output_to_buffer(
outputs_buffered_per_cell: dict[CellId_t, list[ConsoleMsg]],
) -> None:
cell_id = console_output.cell_id
- buffer = (
- outputs_buffered_per_cell[cell_id]
- if cell_id in outputs_buffered_per_cell
- else None
- )
+ buffer = outputs_buffered_per_cell.get(cell_id, None)
if buffer and _can_merge_outputs(buffer[-1], console_output):
buffer[-1].data += console_output.data
elif buffer:
diff --git a/marimo/_messaging/msgspec_encoder.py b/marimo/_messaging/msgspec_encoder.py
index 026bd55ba0..ae79f2f5c8 100644
--- a/marimo/_messaging/msgspec_encoder.py
+++ b/marimo/_messaging/msgspec_encoder.py
@@ -209,10 +209,10 @@ def enc_hook(obj: Any) -> Any:
# Handle collections types
if isinstance(obj, (list, tuple, set, frozenset)):
- return list([enc_hook(item) for item in obj])
+ return [enc_hook(item) for item in obj]
if isinstance(obj, collections.deque):
- return list([enc_hook(item) for item in obj])
+ return [enc_hook(item) for item in obj]
# Handle dict and dict-like types
if isinstance(
diff --git a/marimo/_output/formatters/structures.py b/marimo/_output/formatters/structures.py
index 998cc27b48..a0ae1105a7 100644
--- a/marimo/_output/formatters/structures.py
+++ b/marimo/_output/formatters/structures.py
@@ -22,7 +22,7 @@ if TYPE_CHECKING:
def is_structures_formatter(
formatter: formatting.Formatter[object] | None,
) -> bool:
- return formatter is formatting.get_formatter(tuple())
+ return formatter is formatting.get_formatter(())
def _leaf_formatter(
diff --git a/marimo/_plugins/stateless/accordion.py b/marimo/_plugins/stateless/accordion.py
index fa40c04bef..6509ae94c8 100644
--- a/marimo/_plugins/stateless/accordion.py
+++ b/marimo/_plugins/stateless/accordion.py
@@ -50,7 +50,7 @@ def accordion(
return md(tab).text
return as_html(tab).text
- item_labels = list(md(label).text for label in items)
+ item_labels = [md(label).text for label in items]
item_content = "".join(
["<div>" + render_content(item) + "</div>" for item in items.values()]
)
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
index 4c7d54d5f2..2c81f8e547 100644
--- a/marimo/_plugins/stateless/image.py
+++ b/marimo/_plugins/stateless/image.py
@@ -209,7 +209,7 @@ def image(
# TODO: Consider downsampling here. This is something matplotlib does
# implicitly, and can potentially remove the bottle-neck of very large
# images.
- if isinstance(src, io.BufferedReader) or isinstance(src, io.BytesIO):
+ if isinstance(src, (io.BufferedReader, io.BytesIO)):
src.seek(0)
resolved_src = mo_data.image(src.read()).url
elif isinstance(src, bytes):
diff --git a/marimo/_plugins/stateless/image_compare.py b/marimo/_plugins/stateless/image_compare.py
index 1852a6999e..ecceea3cad 100644
--- a/marimo/_plugins/stateless/image_compare.py
+++ b/marimo/_plugins/stateless/image_compare.py
@@ -103,7 +103,7 @@ def _process_image_to_url(src: ImageLike) -> str:
src = _normalize_image(src)
# different types handling
- if isinstance(src, io.BufferedReader) or isinstance(src, io.BytesIO):
+ if isinstance(src, (io.BufferedReader, io.BytesIO)):
src.seek(0)
return mo_data.image(src.read()).url
elif isinstance(src, bytes):
diff --git a/marimo/_plugins/stateless/nav_menu.py b/marimo/_plugins/stateless/nav_menu.py
index 6abe571f2b..1ac983389e 100644
--- a/marimo/_plugins/stateless/nav_menu.py
+++ b/marimo/_plugins/stateless/nav_menu.py
@@ -98,11 +98,7 @@ def _build_and_validate_menu(menu: dict[str, JSONType]) -> NavMenu:
def validate_href(href: str) -> str:
if not isinstance(href, str):
raise ValueError(f"Invalid href: {href}, expected string")
- if (
- href.startswith("/")
- or href.startswith("#")
- or href.startswith("http")
- ):
+ if href.startswith(("/", "#", "http")):
return href
raise ValueError(f"Invalid href: {href}, must start with / or #")
diff --git a/marimo/_plugins/ui/_impl/data_editor.py b/marimo/_plugins/ui/_impl/data_editor.py
index c2bd186a0f..a0b2150fa3 100644
--- a/marimo/_plugins/ui/_impl/data_editor.py
+++ b/marimo/_plugins/ui/_impl/data_editor.py
@@ -450,7 +450,7 @@ def _apply_positional_edit_row_oriented(
"""Apply a positional edit to row-oriented data."""
if edit["rowIdx"] >= len(data):
# Create a new row with None values for all columns
- new_row = {col: None for col in data[0].keys()}
+ new_row = {col: None for col in data[0]}
data.append(new_row)
original_value = data[0][edit["columnId"]] if data else None
dtype = schema.get(edit["columnId"]) if schema else None
@@ -616,7 +616,7 @@ def _apply_column_edit_row_oriented(
for row in data:
new_row = {}
- for key in row.keys():
+ for key in row:
if key == column_name:
new_row[new_column_name] = row[key]
else:
diff --git a/marimo/_plugins/ui/_impl/data_explorer.py b/marimo/_plugins/ui/_impl/data_explorer.py
index 6e38c612f8..9d99eed80a 100644
--- a/marimo/_plugins/ui/_impl/data_explorer.py
+++ b/marimo/_plugins/ui/_impl/data_explorer.py
@@ -62,15 +62,15 @@ class data_explorer(UIElement[dict[str, Any], dict[str, Any]]):
manager = get_table_manager(df_no_idx)
- encoding_fields = dict(
- x=x,
- y=y,
- row=row,
- column=column,
- color=color,
- size=size,
- shape=shape,
- )
+ encoding_fields = {
+ "x": x,
+ "y": y,
+ "row": row,
+ "column": column,
+ "color": color,
+ "size": size,
+ "shape": shape,
+ }
# Create ChartSpec structure for frontend
initial_value: dict[str, Any] = {
diff --git a/marimo/_plugins/ui/_impl/file_browser.py b/marimo/_plugins/ui/_impl/file_browser.py
index 53bd0190c0..6db1793191 100644
--- a/marimo/_plugins/ui/_impl/file_browser.py
+++ b/marimo/_plugins/ui/_impl/file_browser.py
@@ -302,7 +302,7 @@ class file_browser(
# Sort based on natural sort (alpha, then num)
all_file_paths = sorted(
- list(path.iterdir()), key=lambda f: natural_sort(f.name)
+ path.iterdir(), key=lambda f: natural_sort(f.name)
)
is_truncated = False
diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py
index ba14e39ba5..5b31d829b9 100644
--- a/marimo/_plugins/ui/_impl/plotly.py
+++ b/marimo/_plugins/ui/_impl/plotly.py
@@ -813,10 +813,7 @@ def _trace_needs_scatter_range_fallback(trace: Any) -> bool:
if mode is None:
return False
- if isinstance(mode, str) and "markers" in mode:
- return False
-
- return True
+ return not (isinstance(mode, str) and "markers" in mode)
def _extract_scatter_points_from_range(
diff --git a/marimo/_plugins/ui/_impl/run_button.py b/marimo/_plugins/ui/_impl/run_button.py
index cd735b68c2..19509ee15b 100644
--- a/marimo/_plugins/ui/_impl/run_button.py
+++ b/marimo/_plugins/ui/_impl/run_button.py
@@ -89,7 +89,7 @@ class run_button(UIElement[Any, Any]):
)
def _convert_value(self, value: Any) -> Any:
- if value == 0:
+ if value == 0: # noqa: SIM103
# frontend's value == 0 only during initialization; first value
# frontend will send is 1
return False
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index f5fbc67eb8..049a0e6566 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -799,11 +799,7 @@ class table(
self._has_any_selection = len(coordinates) > 0
return self._searched_manager.select_cells(coordinates) # type: ignore
else:
- indices = [
- int(v)
- for v in value
- if isinstance(v, int) or isinstance(v, str)
- ]
+ indices = [int(v) for v in value if isinstance(v, (int, str))]
self._has_any_selection = len(indices) > 0
if self._has_stable_row_id:
# Search across the original data
@@ -1533,7 +1529,7 @@ class table(
)
# For dictionary or list data, return sequential indices
- if isinstance(self.data, dict) or isinstance(self.data, list):
+ if isinstance(self.data, (dict, list)):
return GetRowIdsResponse(
row_ids=list(range(num_rows_searched)),
all_rows=False,
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index c3d879d6d7..76022bbbb6 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -247,7 +247,7 @@ class DefaultTableManager(TableManager[JsonTableData]):
mask: list[bool] = [
any(
query in str(cast(list[Any], self.data[key])[row]).lower()
- for key in self.data.keys()
+ for key in self.data
)
for row in range(self.get_num_rows() or 0)
]
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index d174a6b1c0..eba2594359 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -120,7 +120,7 @@ class NarwhalsTableManager(
frame = self.as_frame()
_data = frame.to_dict(as_series=False).copy()
- for col in _data.keys():
+ for col in _data:
if col in format_mapping:
_data[col] = [
format_value(col, x, format_mapping) for x in _data[col]
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 47568a8e13..bb81fc8841 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -472,9 +472,7 @@ class PandasTableManagerFactory(TableManagerFactory):
if lower_dtype.startswith("interval"):
return ("string", dtype)
- if lower_dtype.startswith("int") or lower_dtype.startswith(
- "uint"
- ):
+ if lower_dtype.startswith(("int", "uint")):
return ("integer", dtype)
if lower_dtype.startswith("float"):
return ("number", dtype)
diff --git a/marimo/_plugins/ui/_impl/tabs.py b/marimo/_plugins/ui/_impl/tabs.py
index 4f339e2952..5841ce46a8 100644
--- a/marimo/_plugins/ui/_impl/tabs.py
+++ b/marimo/_plugins/ui/_impl/tabs.py
@@ -82,7 +82,7 @@ class tabs(UIElement[str, str]):
)
self._tab_keys = list(tabs.keys())
- tab_labels = list(md(label).text for label in tabs)
+ tab_labels = [md(label).text for label in tabs]
index = (
str(self._tab_keys.index(value))
diff --git a/marimo/_plugins/ui/_impl/utils/dataframe.py b/marimo/_plugins/ui/_impl/utils/dataframe.py
index 0e71bd7505..52bfea0fc9 100644
--- a/marimo/_plugins/ui/_impl/utils/dataframe.py
+++ b/marimo/_plugins/ui/_impl/utils/dataframe.py
@@ -99,11 +99,11 @@ def download_as(
filename (str | None, optional): The filename to use for the downloaded file.
Defaults to None, which uses a random filename.
- Raises:
- ValueError: If unrecognized format.
-
Returns:
tuple: (url, user-facing filename with extension) for the downloaded file.
+
+ Raises:
+ ValueError: If unrecognized format.
"""
if drop_marimo_index:
# Remove the selection column if exists
diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.py
index 24048ee11d..773d69c7d5 100644
--- a/marimo/_runtime/app/script_runner.py
+++ b/marimo/_runtime/app/script_runner.py
@@ -70,13 +70,11 @@ class AppScriptRunner:
self._executor = get_executor(ExecutionConfig())
def _cancel(self, cell_id: CellId_t) -> None:
- cancelled = set(
+ cancelled = {
cid
- for cid in dataflow.transitive_closure(
- self.app.graph, set([cell_id])
- )
+ for cid in dataflow.transitive_closure(self.app.graph, {cell_id})
if cid in self.cells_to_run
- )
+ }
for cid in cancelled:
self.app.graph.cells[cid].set_run_result_status("cancelled")
self.cells_cancelled |= cancelled
@@ -120,7 +118,7 @@ class AppScriptRunner:
if isinstance(unwrapped_exception, MarimoStopError):
self._cancel(cid)
else:
- raise e
+ raise
finally:
for hook in post_execute_hooks:
hook()
@@ -166,7 +164,7 @@ class AppScriptRunner:
if isinstance(unwrapped_exception, MarimoStopError):
self._cancel(cid)
else:
- raise e
+ raise
finally:
for hook in post_execute_hooks:
hook()
diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.py
index b29e5bff46..a7ac254784 100644
--- a/marimo/_runtime/commands.py
+++ b/marimo/_runtime/commands.py
@@ -159,8 +159,8 @@ class HTTPRequest(Mapping[str, Any]):
query_params=query_params,
path_params=request.path_params,
cookies=request.cookies,
- user=request["user"] if "user" in request else {},
- meta=request["meta"] if "meta" in request else {},
+ user=request.get("user", {}),
+ meta=request.get("meta", {}),
# Left out for now. This may contain information that the app author
# does not want to expose.
# session=request.session if "session" in request else {},
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index c5c6c303f0..59cef39853 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -55,9 +55,8 @@ def _should_include_name(name: str, prefix: str) -> bool:
return False
elif not prefix.startswith("_"):
return False
- else:
- # Only include dunder names when prefix starts with an underscore
- return True
+ # Only include dunder names when prefix starts with an underscore
+ return True
else:
return True
@@ -417,10 +416,6 @@ def _isinstance_external(obj: Any, *, class_ref: str) -> bool:
return isinstance(obj, target_class)
-class HasKeysMethod(Protocol):
- def keys(self) -> Collection[Any]: ...
-
-
class HasColumnsProperty(Protocol):
@property
def columns(self) -> Collection[Any]: ...
@@ -431,8 +426,9 @@ def _key_options_from_ipython_method(obj: Any) -> list[str]:
return [str(key) for key in obj._ipython_key_completions_()]
-def _key_options_via_keys_method(obj: HasKeysMethod) -> list[str]:
- return [str(key) for key in obj.keys()]
+def _key_options_via_keys_method(obj: Mapping[Any, Any]) -> list[str]:
+ """Completion keys from a mapping. Only used after ``isinstance(obj, Mapping)``."""
+ return [str(key) for key in obj]
# TODO refactor to customize the `CompletionOption.info` with `"columns"`
@@ -497,7 +493,7 @@ def _resolve_chained_key_path(obj_name: str, document: str) -> list[list[str]]:
# if nodes directly after `obj_name` node are not key accessor `[""]`, exit
# we expect to never hit this condition
- if not node.type == "trailer":
+ if node.type != "trailer":
break
key_path.append(ast.literal_eval(node.get_code()))
@@ -631,7 +627,7 @@ def complete(
graph.cells[cid].code
for cid in dataflow.topological_sort(
graph,
- set(graph.cells.keys()) - set([request.cell_id]),
+ set(graph.cells.keys()) - {request.cell_id},
)
]
diff --git a/marimo/_runtime/copy.py b/marimo/_runtime/copy.py
index d41d6853be..97059fdeea 100644
--- a/marimo/_runtime/copy.py
+++ b/marimo/_runtime/copy.py
@@ -6,12 +6,16 @@ import weakref
from collections.abc import Callable
from copy import copy
from typing import (
+ TYPE_CHECKING,
Any,
Generic,
TypeVar,
cast,
)
+if TYPE_CHECKING:
+ from typing_extensions import Self
+
T = TypeVar("T")
Ref = weakref.ReferenceType[T] | Callable[[], T]
@@ -74,22 +78,20 @@ def shadow_wrap(ref_cls: type[_Copy[T]], base: T) -> T:
# Apply attributes as slots reflection, but remove the attributes that are
# set explicitly by the wrapper class (or not allowed like __dict__).
- slots = set(dir(base)) - set(
- [
- "__new__",
- "__setattr__",
- "__setitem__",
- "__doc__",
- "__class__",
- "__dict__",
- "__module__",
- "__slots__",
- "__dir__",
- "__init__",
- "__weakref__",
- "__ref__",
- ]
- )
+ slots = set(dir(base)) - {
+ "__new__",
+ "__setattr__",
+ "__setitem__",
+ "__doc__",
+ "__class__",
+ "__dict__",
+ "__module__",
+ "__slots__",
+ "__dir__",
+ "__init__",
+ "__weakref__",
+ "__ref__",
+ }
# pointer off the class to lock attributes / items.
_fixed = [False]
@@ -118,7 +120,7 @@ def shadow_wrap(ref_cls: type[_Copy[T]], base: T) -> T:
def __setitem__(self, name: str, value: Any) -> None:
_ro_fail()
- def __new__(cls) -> ReadOnly_try_marimo_unwrap_copy:
+ def __new__(cls) -> Self:
instance = ref_cls.__new__(cls)
for n, m in inspect.getmembers(base):
if n != "__weakref__":
diff --git a/marimo/_runtime/dataflow/__init__.py b/marimo/_runtime/dataflow/__init__.py
index 426df2cc6d..ebbe5cdadd 100644
--- a/marimo/_runtime/dataflow/__init__.py
+++ b/marimo/_runtime/dataflow/__init__.py
@@ -78,8 +78,8 @@ def induced_subgraph(
parents: dict[CellId_t, set[CellId_t]] = {}
children: dict[CellId_t, set[CellId_t]] = {}
for cid in cell_ids:
- parents[cid] = set(p for p in graph.parents[cid] if p in cell_ids)
- children[cid] = set(c for c in graph.children[cid] if c in cell_ids)
+ parents[cid] = {p for p in graph.parents[cid] if p in cell_ids}
+ children[cid] = {c for c in graph.children[cid] if c in cell_ids}
return parents, children
@@ -88,9 +88,9 @@ def get_cycles(
) -> list[tuple[Edge, ...]]:
"""Get all cycles among `cell_ids`."""
_, induced_children = induced_subgraph(graph, cell_ids)
- induced_edges = set(
- [(u, v) for u in induced_children for v in induced_children[u]]
- )
+ induced_edges = {
+ (u, v) for u in induced_children for v in induced_children[u]
+ }
return [c for c in graph.cycles if all(e in induced_edges for e in c)]
diff --git a/marimo/_runtime/dataflow/runner.py b/marimo/_runtime/dataflow/runner.py
index e7165504ce..0b8bd0f737 100644
--- a/marimo/_runtime/dataflow/runner.py
+++ b/marimo/_runtime/dataflow/runner.py
@@ -58,13 +58,11 @@ class Runner:
graph = self._graph
substitutions = set(kwargs.keys())
unsubstituted_refs = cell_impl.refs - substitutions
- parent_ids = set(
- [
- parent_id
- for parent_id in graph.parents[cell_impl.cell_id]
- if graph.cells[parent_id].defs.intersection(unsubstituted_refs)
- ]
- )
+ parent_ids = {
+ parent_id
+ for parent_id in graph.parents[cell_impl.cell_id]
+ if graph.cells[parent_id].defs.intersection(unsubstituted_refs)
+ }
return transitive_closure(graph, parent_ids, children=False)
@staticmethod
diff --git a/marimo/_runtime/functions.py b/marimo/_runtime/functions.py
index 95463abd94..a726d030c6 100644
--- a/marimo/_runtime/functions.py
+++ b/marimo/_runtime/functions.py
@@ -56,7 +56,7 @@ class Function(Generic[S, T]):
return self.function(parse_raw(args, self.arg_cls))
except Exception as e:
LOGGER.error(f"Error calling function {self.name}: {e}")
- raise e
+ raise
@dataclasses.dataclass
diff --git a/marimo/_runtime/packages/module_registry.py b/marimo/_runtime/packages/module_registry.py
index 852bd435fd..fa0fdcc83b 100644
--- a/marimo/_runtime/packages/module_registry.py
+++ b/marimo/_runtime/packages/module_registry.py
@@ -43,15 +43,14 @@ class ModuleRegistry:
def modules(self) -> set[str]:
"""Modules imported by cells."""
- return set(
+ return {
mod
for cell in self.graph.cells.values()
for mod in cell.imported_namespaces
- )
+ }
def missing_modules(self) -> set[str]:
"""Modules that will fail to import."""
- return (
- set(mod for mod in self.modules() if not _is_module_installed(mod))
- - self.excluded_modules
- )
+ return {
+ mod for mod in self.modules() if not _is_module_installed(mod)
+ } - self.excluded_modules
diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.py
index 8d99388bbe..0dd6ca6f76 100644
--- a/marimo/_runtime/packages/pypi_package_manager.py
+++ b/marimo/_runtime/packages/pypi_package_manager.py
@@ -443,15 +443,13 @@ class UvPackageManager(PypiPackageManager):
- These should be passed directly to uv which handles them correctly
"""
# Git URLs: git+https://, git+ssh://, git://
- if package.startswith("git+") or package.startswith("git://"):
+ if package.startswith(("git+", "git://")):
return True
# Direct references with @ (PEP 440 direct references)
if " @ " in package:
return True
# URLs (https://, http://, file://)
- if "://" in package:
- return True
- return False
+ return "://" in package
def _is_installed(package: str) -> bool:
return version_map.has(package)
@@ -473,7 +471,7 @@ class UvPackageManager(PypiPackageManager):
if _is_direct_reference(im) or _is_installed(im)
]
- if filepath.endswith(".md") or filepath.endswith(".qmd"):
+ if filepath.endswith((".md", ".qmd")):
# md and qmd require writing to a faux python file first.
return self._process_md_changes(
filepath, packages_to_add, packages_to_remove, upgrade=upgrade
diff --git a/marimo/_runtime/packages/utils.py b/marimo/_runtime/packages/utils.py
index 44b78aa714..3a6d70b1e8 100644
--- a/marimo/_runtime/packages/utils.py
+++ b/marimo/_runtime/packages/utils.py
@@ -94,7 +94,7 @@ def split_packages(package: str) -> list[str]:
current_package.append(part)
elif in_environment_marker:
current_package.append(part)
- if part.endswith("'") or part.endswith('"'):
+ if part.endswith(("'", '"')):
in_environment_marker = False
packages.append(" ".join(current_package))
current_package = []
diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.py
index 7d9084ba7c..e37c5ccfe7 100644
--- a/marimo/_runtime/patches.py
+++ b/marimo/_runtime/patches.py
@@ -301,9 +301,7 @@ def patch_jedi_parameter_completion() -> None:
lines = [
line.strip().lstrip("#") for line in maybe_comment.splitlines()
]
- min_indent = min(
- [len(line) - len(line.lstrip()) for line in lines]
- )
+ min_indent = min(len(line) - len(line.lstrip()) for line in lines)
return "\n".join(
line.strip().lstrip("#")[min_indent:]
for line in maybe_comment.splitlines()
diff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.py
index 6b629de7fd..38f38cb45a 100644
--- a/marimo/_runtime/primitives.py
+++ b/marimo/_runtime/primitives.py
@@ -28,15 +28,13 @@ UNCLONABLE_TYPES = [
"marimo._runtime.watch._directory.DirectoryState",
]
-UNCLONABLE_MODULES = set(
- [
- "_asyncio",
- "_io",
- "marimo._ast",
- "marimo._plugins.ui",
- "numpy.lib.npyio",
- ]
-)
+UNCLONABLE_MODULES = {
+ "_asyncio",
+ "_io",
+ "marimo._ast",
+ "marimo._plugins.ui",
+ "numpy.lib.npyio",
+}
def is_external(value: Any) -> bool:
@@ -145,13 +143,13 @@ def is_unclonable_type(obj: object) -> bool:
# Cell objects in particular are hidden by functools.wraps.
if isinstance(obj, Cell):
return True
- return any([is_instance_by_name(obj, name) for name in UNCLONABLE_TYPES])
+ return any(is_instance_by_name(obj, name) for name in UNCLONABLE_TYPES)
def from_unclonable_module(obj: object) -> bool:
obj = obj if hasattr(obj, "__module__") else obj.__class__
return hasattr(obj, "__module__") and any(
- [obj.__module__.startswith(name) for name in UNCLONABLE_MODULES]
+ obj.__module__.startswith(name) for name in UNCLONABLE_MODULES
)
diff --git a/marimo/_runtime/reload/autoreload.py b/marimo/_runtime/reload/autoreload.py
index 4c7afef0fa..ada9c1f819 100644
--- a/marimo/_runtime/reload/autoreload.py
+++ b/marimo/_runtime/reload/autoreload.py
@@ -343,7 +343,7 @@ def update_class(old: object, new: object) -> None:
pass # skip non-writable attributes
old_dict_keys = set(old.__dict__.keys())
- for key in new.__dict__.keys():
+ for key in new.__dict__:
if key not in old_dict_keys:
try:
setattr(old, key, getattr(new, key))
diff --git a/marimo/_runtime/reload/module_watcher.py b/marimo/_runtime/reload/module_watcher.py
index 5c848f87a2..9b765883d1 100644
--- a/marimo/_runtime/reload/module_watcher.py
+++ b/marimo/_runtime/reload/module_watcher.py
@@ -99,12 +99,12 @@ def _get_excluded_modules(modules: dict[str, types.ModuleType]) -> set[str]:
):
return _excluded_modules_cache[1]
- result = set(
+ result = {
modname
for modname in modules
if (m := modules.get(modname)) is not None
and _is_third_party_module(m)
- )
+ }
_excluded_modules_cache = (cache_key, result)
return result
@@ -121,10 +121,10 @@ def _check_modules(
# haven't found a reliable way to do this, however.
excludes = _get_excluded_modules(sys_modules)
- target_modules = set(m for m in modified_modules if m is not None)
- target_filenames = set(
+ target_modules = {m for m in modified_modules if m is not None}
+ target_filenames = {
t.__file__ for t in target_modules if hasattr(t, "__file__")
- )
+ }
for modname, module in modules.items():
if _depends_on(
@@ -186,7 +186,7 @@ def watch_modules(
)
with graph.lock:
LOGGER.debug("Acquired graph lock.")
- for modname in stale_modules.keys():
+ for modname in stale_modules:
# prune definitions that are derived from stale modules
cell_id = modname_to_cell_id[modname]
cell = graph.cells[cell_id]
@@ -202,10 +202,7 @@ def watch_modules(
# staleness
stale_cell_ids = dataflow.transitive_closure(
graph,
- set(
- modname_to_cell_id[modname]
- for modname in stale_modules
- ),
+ {modname_to_cell_id[modname] for modname in stale_modules},
relatives=dataflow.get_import_block_relatives(graph),
)
for cid in stale_cell_ids:
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index 1bca34a577..c878a89046 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -115,10 +115,7 @@ def should_show_traceback(
# SQL parsing errors happen in SQL cells so showing a
# python traceback is not useful.
- if isinstance(exception, MarimoSQLError):
- return False
-
- return True
+ return not isinstance(exception, MarimoSQLError)
class Runner:
@@ -271,11 +268,11 @@ class Runner:
def cancel(self, cell_id: CellId_t) -> None:
"""Mark a cell (and its descendants) as cancelled."""
- descendants = set(
+ descendants = {
cid
- for cid in dataflow.transitive_closure(self.graph, set([cell_id]))
+ for cid in dataflow.transitive_closure(self.graph, {cell_id})
if cid in self.cells_to_run
- )
+ }
self.cancelled_cells.add(cell_id, descendants)
for cid in descendants:
self.graph.cells[cid].set_run_result_status("cancelled")
@@ -290,11 +287,7 @@ class Runner:
def _get_run_position(self, cell_id: CellId_t) -> int | None:
"""Position in the original run queue"""
- return (
- self._run_position[cell_id]
- if cell_id in self._run_position
- else None
- )
+ return self._run_position.get(cell_id, None)
def _runs_after(self, source: CellId_t, target: CellId_t) -> bool | None:
"""Compare run positions.
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index f27400d69c..3d479cd459 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -76,9 +76,9 @@ def _set_imported_defs(
with ctx.graph.lock:
LOGGER.debug("Acquired graph lock to update import workspace.")
if cell.import_workspace.is_import_block:
- cell.import_workspace.imported_defs = set(
+ cell.import_workspace.imported_defs = {
name for name in cell.defs if name in ctx.glbls
- )
+ }
@kernel_tracer.start_as_current_span("set_status_idle")
@@ -131,7 +131,7 @@ def _broadcast_variables(
values = [
create_variable_value(
name=variable,
- value=(ctx.glbls[variable] if variable in ctx.glbls else None),
+ value=(ctx.glbls.get(variable, None)),
)
for variable in cell.defs
]
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 9fd8524237..d37cb2ed52 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -248,7 +248,7 @@ def defs() -> tuple[str, ...]:
try:
ctx = get_context()
except ContextNotInitializedError:
- return tuple()
+ return ()
if ctx.execution_context is not None:
return tuple(
@@ -257,7 +257,7 @@ def defs() -> tuple[str, ...]:
for defn in ctx.graph.cells[ctx.execution_context.cell_id].defs
)
)
- return tuple()
+ return ()
@mddoc
@@ -270,7 +270,7 @@ def refs() -> tuple[str, ...]:
try:
ctx = get_context()
except ContextNotInitializedError:
- return tuple()
+ return ()
# builtins that have not been shadowed by the user
unshadowed_builtins = BUILTINS.difference(
@@ -286,7 +286,7 @@ def refs() -> tuple[str, ...]:
if defn not in unshadowed_builtins
)
)
- return tuple()
+ return ()
@mddoc
@@ -847,7 +847,7 @@ class Kernel:
module_reloader is not None
and module_reloader.cell_uses_stale_modules(cell)
):
- self.graph.set_stale(set([cell.cell_id]), prune_imports=True)
+ self.graph.set_stale({cell.cell_id}, prune_imports=True)
LOGGER.debug("registered cell %s", cell_id)
LOGGER.debug("parents: %s", self.graph.parents[cell_id])
LOGGER.debug("children: %s", self.graph.children[cell_id])
@@ -993,7 +993,7 @@ class Kernel:
cell = self.graph.cells.get(cell_id, None)
if cell:
prev_imports: set[Name] = (
- set([im.namespace for im in previous_cell.imports])
+ {im.namespace for im in previous_cell.imports}
if previous_cell
else set()
)
@@ -1317,7 +1317,7 @@ class Kernel:
self.errors = all_errors
for cid in self.errors:
- cell = self.graph.cells[cid] if cid in self.graph.cells else None
+ cell = self.graph.cells.get(cid, None)
if (
cell is not None
and not cell.config.disabled
@@ -3076,7 +3076,7 @@ class SqlCallbacks:
request.query, self._kernel.globals
)
validate_result = SqlCatalogCheckResult(
- success=True if error_message is None else False,
+ success=error_message is None,
error_message=error_message,
)
broadcast_notification(
@@ -3263,7 +3263,7 @@ class PackagesCallbacks:
return
resolved_packages: dict[str, PackageRequirement] = {}
- for pkg in request.versions.keys():
+ for pkg in request.versions:
pkg_req = PackageRequirement.parse(pkg)
resolved_packages[pkg_req.name] = pkg_req
@@ -3372,12 +3372,12 @@ class PackagesCallbacks:
# This consists of cells that either statically reference the installed
# module, or that previously failed with a ModuleNotFoundError matching
# an installed module.
- cells_to_run = set(
+ cells_to_run = {
cid
for module in installed_modules
if (cid := self._kernel.module_registry.defining_cell(module))
is not None
- )
+ }
for cid, cell in self._kernel.graph.cells.items():
if (
diff --git a/marimo/_runtime/virtual_file/__init__.py b/marimo/_runtime/virtual_file/__init__.py
index 4a9b3bfffc..7c7209ab3b 100644
--- a/marimo/_runtime/virtual_file/__init__.py
+++ b/marimo/_runtime/virtual_file/__init__.py
@@ -24,7 +24,7 @@ from marimo._runtime.virtual_file.virtual_file import (
read_virtual_file_chunked,
)
-__all__ = [
+__all__ = [ # noqa: RUF022
# Storage
"VirtualFileStorage",
"SharedMemoryStorage",
diff --git a/marimo/_runtime/virtual_file/storage.py b/marimo/_runtime/virtual_file/storage.py
index 6fd7a653e9..7c409c9f88 100644
--- a/marimo/_runtime/virtual_file/storage.py
+++ b/marimo/_runtime/virtual_file/storage.py
@@ -247,7 +247,7 @@ class VirtualFileStorageManager:
_instance: VirtualFileStorageManager | None = None
_storage: VirtualFileStorage | None = None
- def __new__(cls) -> VirtualFileStorageManager:
+ def __new__(cls) -> VirtualFileStorageManager: # noqa: PYI034
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
diff --git a/marimo/_runtime/watch/_directory.py b/marimo/_runtime/watch/_directory.py
index 788be76ecb..2e23a45148 100644
--- a/marimo/_runtime/watch/_directory.py
+++ b/marimo/_runtime/watch/_directory.py
@@ -35,7 +35,7 @@ def _hashable_walk(
) -> set[tuple[Path, tuple[str], tuple[str]]]:
return cast(
set[tuple[Path, tuple[str], tuple[str]]],
- set((p, *map(tuple, r)) for p, *r in walked),
+ {(p, *map(tuple, r)) for p, *r in walked},
)
diff --git a/marimo/_save/cache.py b/marimo/_save/cache.py
index 28c490c4e7..919ca35338 100644
--- a/marimo/_save/cache.py
+++ b/marimo/_save/cache.py
@@ -196,10 +196,10 @@ class Cache:
elif isinstance(value, set):
# Sets cannot be recursive (require hashable items), but keep the
# reference.
- result = set(
+ result = {
self._restore_from_stub_if_needed(item, scope, memo)
for item in value
- )
+ }
value.clear()
value.update(result)
result = value
@@ -328,10 +328,10 @@ class Cache:
)
elif isinstance(value, set):
# sets cannot be recursive (require hashable items)
- converted = set(
+ converted = {
self._convert_to_stub_if_needed(item, memo, preserve_pointers)
for item in value
- )
+ }
if preserve_pointers:
value.clear()
value.update(converted)
diff --git a/marimo/_save/hash.py b/marimo/_save/hash.py
index 53f177734e..5638a44208 100644
--- a/marimo/_save/hash.py
+++ b/marimo/_save/hash.py
@@ -179,8 +179,7 @@ def get_and_update_context_from_scope(
if scope_refs is None:
scope_refs = set()
for ref in scope_refs:
- if ref in ctx_scope:
- ctx_scope.remove(ref)
+ ctx_scope.discard(ref)
# This is typically done in post execution hook, but it will not be
# called in script mode.
@@ -946,13 +945,11 @@ class BlockHasher:
ref_cells = set().union(
*[self.graph.definitions.get(ref, set()) for ref in refs]
)
- ref_cells |= set(
- [
- cell
- for ref in refs
- if (cell := get_cell_from_local(ref, self.cell_id))
- ]
- )
+ ref_cells |= {
+ cell
+ for ref in refs
+ if (cell := get_cell_from_local(ref, self.cell_id))
+ }
assert len(ref_cells) == 1, (
"Inconsistent references, cannot determine execution path. "
f"Got {ref_cells} expected set({self.cell_id}). "
diff --git a/marimo/_save/loaders/loader.py b/marimo/_save/loaders/loader.py
index 391143a5b7..f323123039 100644
--- a/marimo/_save/loaders/loader.py
+++ b/marimo/_save/loaders/loader.py
@@ -34,7 +34,7 @@ class LoaderError(BaseException):
"""Base exception such that it can be raised as context for other errors."""
def __init__(self, message: str) -> None:
- self.message = "\n".join([message, INCONSISTENT_CACHE_BOILER_PLATE])
+ self.message = f"{message}\n{INCONSISTENT_CACHE_BOILER_PLATE}"
super().__init__(message)
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index 902aba6667..017a470a52 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -231,11 +231,11 @@ class _cache_call(CacheContext, Generic[P, R]):
if graph is not None:
self.scoped_refs |= graph.cells[cell_id].defs & set(glbls.keys())
# The defined private variables of this cell, normalized
- self.scoped_refs |= set(
+ self.scoped_refs |= {
unmangle_local(x).name
- for x in glbls.keys()
+ for x in glbls
if is_mangled_local(x, cell_id)
- )
+ }
# Load global cache from state
name = self.__name__
@@ -492,9 +492,9 @@ class _cache_call(CacheContext, Generic[P, R]):
runtime = time.time() - start_time
self._finalize_cache_update(attempt, response, runtime, scope)
- except Exception as e:
+ except Exception:
failed = True
- raise e
+ raise
finally:
# NB. Exceptions raise their own side effects.
if ctx and not failed:
@@ -620,9 +620,9 @@ class _cache_call_async(_cache_call[P, R]):
runtime = time.time() - start_time
self._finalize_cache_update(attempt, response, runtime, scope)
- except Exception as e:
+ except Exception:
failed = True
- raise e
+ raise
finally:
# NB. Exceptions raise their own side effects.
if ctx and not failed:
@@ -806,9 +806,9 @@ class _cache_context(SkipContext, CacheContext):
traceback.print_exc(file=tmpio)
tmpio.seek(0)
write_traceback(tmpio.read())
- except Exception as e:
+ except Exception:
failed = True
- raise e
+ raise
finally:
if not failed:
# Conditional because pendantically, the side effect is on restore /
diff --git a/marimo/_save/stores/redis.py b/marimo/_save/stores/redis.py
index 0442d67442..490403ddf9 100644
--- a/marimo/_save/stores/redis.py
+++ b/marimo/_save/stores/redis.py
@@ -23,9 +23,7 @@ class RedisStore(Store):
def put(self, key: str, value: bytes) -> bool:
result = self.redis.set(key, value)
- if result is None:
- return False
- return True
+ return result is not None
def hit(self, key: str) -> bool:
return self.redis.exists(key) > 0
diff --git a/marimo/_server/ai/ids.py b/marimo/_server/ai/ids.py
index d5625393e3..88eb0227ae 100644
--- a/marimo/_server/ai/ids.py
+++ b/marimo/_server/ai/ids.py
@@ -43,18 +43,13 @@ class AiModelId:
def _guess_provider(model: str) -> AiProviderId:
def is_google(model: str) -> bool:
- return model.startswith("google") or model.startswith("gemini")
+ return model.startswith(("google", "gemini"))
def is_anthropic(model: str) -> bool:
return model.startswith("claude")
def is_openai(model: str) -> bool:
- return (
- model.startswith("gpt")
- or model.startswith("o4")
- or model.startswith("o3")
- or model.startswith("o1")
- )
+ return model.startswith(("gpt", "o4", "o3", "o1"))
if is_google(model):
return AiProviderId("google")
diff --git a/marimo/_server/ai/mcp/__init__.py b/marimo/_server/ai/mcp/__init__.py
index 78eecfca0b..c0592dc1d1 100644
--- a/marimo/_server/ai/mcp/__init__.py
+++ b/marimo/_server/ai/mcp/__init__.py
@@ -26,7 +26,7 @@ from marimo._server.ai.mcp.transport import (
)
from marimo._server.ai.mcp.types import MCPToolArgs
-__all__ = [
+__all__ = [ # noqa: RUF022
# Client classes
"MCPClient",
"MCPServerConnection",
diff --git a/marimo/_server/ai/mcp/client.py b/marimo/_server/ai/mcp/client.py
index aa0ccdf7ab..5da01d1e21 100644
--- a/marimo/_server/ai/mcp/client.py
+++ b/marimo/_server/ai/mcp/client.py
@@ -137,7 +137,7 @@ class MCPClient:
del self.connections[server_name]
# Disconnect from servers that need to be updated (will reconnect below)
- for server_name in diff.servers_to_update.keys():
+ for server_name in diff.servers_to_update:
LOGGER.info(f"Updating server: {server_name}")
await self.disconnect_from_server(server_name)
# Clean up old connection, will be recreated below
@@ -419,8 +419,7 @@ class MCPClient:
# Connect to servers concurrently
tasks = [
- self.connect_to_server(server_name)
- for server_name in self.servers.keys()
+ self.connect_to_server(server_name) for server_name in self.servers
]
connection_results = await asyncio.gather(
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.py
index c46822a8fb..712f8840d8 100644
--- a/marimo/_server/ai/providers.py
+++ b/marimo/_server/ai/providers.py
@@ -430,13 +430,10 @@ class OpenAIProvider(OpenAIClientMixin, PydanticProvider["PydanticOpenAI"]):
return False
# If using a custom base_url that's not OpenAI, don't assume reasoning is supported
- if (
+ return not (
self.config.base_url
and "api.openai.com" not in self.config.base_url
- ):
- return False
-
- return True
+ )
class AzureOpenAIProvider(OpenAIProvider):
diff --git a/marimo/_server/api/endpoints/ws/ws_message_loop.py b/marimo/_server/api/endpoints/ws/ws_message_loop.py
index bc7e9c294b..05a844baed 100644
--- a/marimo/_server/api/endpoints/ws/ws_message_loop.py
+++ b/marimo/_server/api/endpoints/ws/ws_message_loop.py
@@ -109,7 +109,7 @@ class WebSocketMessageLoop:
)
except Exception as e:
LOGGER.error("Error sending message to frontend: %s", str(e))
- raise e
+ raise
async def _listen_for_disconnect(self) -> None:
"""Listen for WebSocket disconnect."""
@@ -122,7 +122,7 @@ class WebSocketMessageLoop:
self.on_disconnect(e, self._cancel_messages_task)
except Exception as e:
LOGGER.error("Error listening for disconnect: %s", str(e))
- raise e
+ raise
def _should_filter_operation(self, op: str) -> bool:
"""Determine if operation should be filtered based on kiosk mode.
diff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.py
index 221048594d..2b28e68367 100644
--- a/marimo/_server/api/middleware.py
+++ b/marimo/_server/api/middleware.py
@@ -557,7 +557,7 @@ class ProxyMiddleware:
LOGGER.error(
f"Failed to connect to {ws_url} after {max_retries} attempts. Final error: {e}"
)
- raise e
+ raise
raise ValueError("Failed to connect to LSP server")
@@ -614,8 +614,6 @@ class ProxyMiddleware:
await asyncio.gather(*relay_tasks)
except asyncio.CancelledError:
pass
- except Exception as e:
- raise e
finally:
for task in relay_tasks:
if not task.done():
diff --git a/marimo/_server/errors.py b/marimo/_server/errors.py
index 33f6de096c..5ef6781f04 100644
--- a/marimo/_server/errors.py
+++ b/marimo/_server/errors.py
@@ -35,10 +35,7 @@ def _is_api_request(request: Request) -> bool:
# Check Accept header for application/json (case-insensitive)
accept = request.headers.get("accept", "")
- if "application/json" in accept.lower():
- return True
-
- return False
+ return "application/json" in accept.lower()
# Convert exceptions to JSON responses
diff --git a/marimo/_server/export/_html_asset_server.py b/marimo/_server/export/_html_asset_server.py
index 6f18de4302..e5107232ad 100644
--- a/marimo/_server/export/_html_asset_server.py
+++ b/marimo/_server/export/_html_asset_server.py
@@ -11,6 +11,8 @@ if TYPE_CHECKING:
from pathlib import Path
from types import TracebackType
+ from typing_extensions import Self
+
class _HtmlAssetRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self) -> None:
@@ -65,7 +67,7 @@ class HtmlAssetServer(AbstractContextManager["HtmlAssetServer"]):
with self._server.dynamic_html_lock:
self._server.dynamic_html = html
- def __enter__(self) -> HtmlAssetServer:
+ def __enter__(self) -> Self:
if not self._directory.is_dir():
raise RuntimeError(f"Static assets not found at {self._directory}")
diff --git a/marimo/_server/export/_live_notebook_server.py b/marimo/_server/export/_live_notebook_server.py
index 81bfaf608a..4c885087a2 100644
--- a/marimo/_server/export/_live_notebook_server.py
+++ b/marimo/_server/export/_live_notebook_server.py
@@ -7,12 +7,16 @@ import tempfile
import time
from contextlib import AbstractContextManager
from pathlib import Path
+from typing import TYPE_CHECKING
from urllib.error import URLError
from urllib.request import urlopen
from marimo import _loggers
from marimo._utils.net import find_free_port
+if TYPE_CHECKING:
+ from typing_extensions import Self
+
LOGGER = _loggers.marimo_logger()
_LIVE_SERVER_START_TIMEOUT_S = 90.0
@@ -42,7 +46,7 @@ class LiveNotebookServer(AbstractContextManager["LiveNotebookServer"]):
def health_url(self) -> str:
return f"{self.page_url}/health"
- def __enter__(self) -> LiveNotebookServer:
+ def __enter__(self) -> Self:
"""Start the server process and block until the health endpoint is ready."""
self._log_file = tempfile.NamedTemporaryFile(
diff --git a/marimo/_server/utils.py b/marimo/_server/utils.py
index 7abb7bc33d..60821dcbff 100644
--- a/marimo/_server/utils.py
+++ b/marimo/_server/utils.py
@@ -5,8 +5,6 @@ import asyncio
import sys
from typing import TYPE_CHECKING, Any, TypeVar
-from marimo._utils.net import find_free_port as find_free_port
-
if TYPE_CHECKING:
from collections.abc import Coroutine
diff --git a/marimo/_session/state/serialize.py b/marimo/_session/state/serialize.py
index e1f5df807e..5db465ca0b 100644
--- a/marimo/_session/state/serialize.py
+++ b/marimo/_session/state/serialize.py
@@ -502,9 +502,7 @@ class SessionCacheManager:
return False
if "script_metadata_hash" not in metadata:
return False
- if metadata.get("script_metadata_hash") != key.script_metadata_hash:
- return False
- return True
+ return metadata.get("script_metadata_hash") == key.script_metadata_hash
def read_session_view(self, key: SessionCacheKey) -> SessionView:
"""Read the session view from the cache files.
diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.py
index e87e4cf426..805ef69ca3 100644
--- a/marimo/_session/state/session_view.py
+++ b/marimo/_session/state/session_view.py
@@ -257,9 +257,9 @@ class SessionView:
self.variable_notifications = notification
# Set of variable names that are in scope.
- variable_names: set[str] = set(
- [v.name for v in self.variable_notifications.variables]
- )
+ variable_names: set[str] = {
+ v.name for v in self.variable_notifications.variables
+ }
# Remove any variable values that are no longer in scope.
next_values: dict[str, VariableValue] = {}
diff --git a/marimo/_snippets/snippets.py b/marimo/_snippets/snippets.py
index 584095abf0..4e02bd09ab 100644
--- a/marimo/_snippets/snippets.py
+++ b/marimo/_snippets/snippets.py
@@ -80,7 +80,7 @@ def get_title_from_code(code: str) -> str:
if not code:
return ""
code = code.strip()
- if not (code.startswith("mo.md") or code.startswith("#")):
+ if not (code.startswith(("mo.md", "#"))):
return ""
start = code.find("#")
diff --git a/marimo/_sql/utils.py b/marimo/_sql/utils.py
index de86f8f07f..4d17982906 100644
--- a/marimo/_sql/utils.py
+++ b/marimo/_sql/utils.py
@@ -256,7 +256,7 @@ def is_query_empty(query: str) -> bool:
return True
# If the query starts with -- or /*, it's likely just comments
- if stripped.startswith("--") or stripped.startswith("/*"):
+ if stripped.startswith(("--", "/*")):
import re
# Remove /* */ comments
diff --git a/marimo/_utils/async_path.py b/marimo/_utils/async_path.py
index c568af60c1..2423043784 100644
--- a/marimo/_utils/async_path.py
+++ b/marimo/_utils/async_path.py
@@ -15,6 +15,8 @@ StrPath = str | os.PathLike[str]
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Iterator
+ from typing_extensions import Self
+
class AsyncPath(PurePath):
"""
@@ -23,11 +25,14 @@ class AsyncPath(PurePath):
This class inherits from PurePath for path manipulation and adds async filesystem methods.
"""
- def __new__(cls, *args: Any, **kwargs: Any) -> AsyncPath:
+ def __new__(cls, *args: Any, **kwargs: Any) -> Self:
# Create the path using the same logic as PurePath
+ path_cls: type[AsyncPath]
if cls is AsyncPath:
- cls = AsyncWindowsPath if os.name == "nt" else AsyncPosixPath
- return super().__new__(cls, *args, **kwargs) # type: ignore
+ path_cls = AsyncWindowsPath if os.name == "nt" else AsyncPosixPath
+ else:
+ path_cls = cls
+ return super().__new__(path_cls, *args, **kwargs) # type: ignore
def __truediv__(self, other: StrPath) -> AsyncPath:
# Override to return AsyncPath instance
diff --git a/marimo/_utils/dataclass_to_openapi.py b/marimo/_utils/dataclass_to_openapi.py
index 8b4a0bfda7..9114ad6197 100644
--- a/marimo/_utils/dataclass_to_openapi.py
+++ b/marimo/_utils/dataclass_to_openapi.py
@@ -246,11 +246,11 @@ class PythonTypeToOpenAPI:
cls (Any): The dataclass type or instance to convert.
processed_classes (Dict[Any, str]): A dictionary of processed classes.
- Raises:
- ValueError: If cls is not a dataclass.
-
Returns:
Dict[str, Any]: The OpenAPI schema.
+
+ Raises:
+ ValueError: If cls is not a dataclass.
"""
# If cls is an instance, get its class
if not isinstance(cls, type) and dataclasses.is_dataclass(cls):
diff --git a/marimo/_utils/distributor.py b/marimo/_utils/distributor.py
index f7181cfb75..127902cb76 100644
--- a/marimo/_utils/distributor.py
+++ b/marimo/_utils/distributor.py
@@ -20,7 +20,7 @@ T = TypeVar("T", covariant=True)
Consumer = Callable[[T], None]
-class Distributor(Generic[T], Protocol):
+class Distributor(Protocol, Generic[T]):
"""Base class for distributors."""
def add_consumer(self, consumer: Consumer[T]) -> Disposable:
diff --git a/marimo/_utils/format_signature.py b/marimo/_utils/format_signature.py
index d4c096722e..c8023dcb7e 100644
--- a/marimo/_utils/format_signature.py
+++ b/marimo/_utils/format_signature.py
@@ -13,9 +13,7 @@ def format_signature(prefix: str, signature_text: str, width: int = 39) -> str:
except ModuleNotFoundError:
pass
- if black_installed and (
- prefix.startswith("class") or prefix.startswith("def")
- ):
+ if black_installed and (prefix.startswith(("class", "def"))):
# Coarse try-except because we're using internal black APIs;
# many other well-established projects use these APIs, which
# gives us at least a small amount of confidence in our use.
diff --git a/marimo/_utils/inline_script_metadata.py b/marimo/_utils/inline_script_metadata.py
index ab17faddd2..0b7acaf2dc 100644
--- a/marimo/_utils/inline_script_metadata.py
+++ b/marimo/_utils/inline_script_metadata.py
@@ -98,7 +98,7 @@ def _get_pyproject_from_filename(name: str) -> dict[str, Any] | None:
if name.endswith(".py"):
return read_pyproject_from_script(contents)
- if not (name.endswith(".md") or name.endswith(".qmd")):
+ if not (name.endswith((".md", ".qmd"))):
raise ValueError(
f"Unsupported file type: {name}. Only .py and .md files are supported."
)
@@ -155,12 +155,13 @@ def _pyproject_toml_to_requirements_txt(
# attached, so we cannot do .index()
dep_index: int | None = None
for i, dep in enumerate(dependencies):
- if (
- dep == dependency
- or dep.startswith(f"{dependency}==")
- or dep.startswith(f"{dependency}<")
- or dep.startswith(f"{dependency}>")
- or dep.startswith(f"{dependency}~")
+ if dep == dependency or dep.startswith(
+ (
+ f"{dependency}==",
+ f"{dependency}<",
+ f"{dependency}>",
+ f"{dependency}~",
+ )
):
dep_index = i
break
diff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.py
index df5c928d48..9b0f85d434 100644
--- a/marimo/_utils/narwhals_utils.py
+++ b/marimo/_utils/narwhals_utils.py
@@ -246,11 +246,7 @@ def is_narwhals_lazyframe(df: Any) -> TypeIs[nw.LazyFrame[Any]]:
Checks both v1 and main.
"""
- return (
- isinstance(df, nw.LazyFrame)
- or isinstance(df, nw_main.LazyFrame)
- or isinstance(df, nw1.LazyFrame)
- )
+ return isinstance(df, (nw.LazyFrame, nw_main.LazyFrame, nw1.LazyFrame))
def is_narwhals_dataframe(df: Any) -> TypeIs[nw.DataFrame[Any]]:
@@ -259,11 +255,7 @@ def is_narwhals_dataframe(df: Any) -> TypeIs[nw.DataFrame[Any]]:
Checks both v1 and main.
"""
- return (
- isinstance(df, nw.DataFrame)
- or isinstance(df, nw_main.DataFrame)
- or isinstance(df, nw1.DataFrame)
- )
+ return isinstance(df, (nw.DataFrame, nw_main.DataFrame, nw1.DataFrame))
if TYPE_CHECKING:
diff --git a/marimo/_utils/site_packages.py b/marimo/_utils/site_packages.py
index 2489a8ea3d..31aff9b41c 100644
--- a/marimo/_utils/site_packages.py
+++ b/marimo/_utils/site_packages.py
@@ -79,9 +79,7 @@ def module_exists_in_site_packages(module_name: str) -> bool:
for entry in os.listdir(site_dir):
module = entry.split("-", 1)[0]
if module == module_name and (
- entry.endswith(".egg-info")
- or entry.endswith(".dist-info")
- or entry.endswith(".egg")
+ entry.endswith((".egg-info", ".dist-info", ".egg"))
):
return True
@@ -105,9 +103,7 @@ def has_local_conflict(module_name: str, directory: str) -> bool:
# Check for local package directory
local_pkg = os.path.join(directory, module_name)
- if os.path.isdir(local_pkg) and os.path.isfile(
- os.path.join(local_pkg, "__init__.py")
- ):
- return True
-
- return False
+ return bool(
+ os.path.isdir(local_pkg)
+ and os.path.isfile(os.path.join(local_pkg, "__init__.py"))
+ )
diff --git a/pyproject.toml b/pyproject.toml
index ea483a1862..2c0d366b88 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -330,76 +330,47 @@ ignore = [
# From new version of Ruff: We should fix these, but it raises too many errors
"BLE001", # Do not catch blind exception: `Exception`
- "C405", # Unnecessary literal set
+ "RUF059", # Unused unpacked variable
"DTZ001", # `datetime.datetime()` called without a `tzinfo` argument
"PLW1510", # `subprocess.run` without explicit `check`
- "FLY002", # Static join to f-string
- "RUF059", # Unused unpacked variable
"S110", # `try`-`except`-`pass`
"TRY004", # Type check without `TypeError`
"SIM102", # Use a single `if` statement instead of nested `if` statements
"SIM117", # Use a single `with` statement with multiple contexts instead of nested `with` statements
- "SIM118", # Use `key in dict` instead of `key in dict.keys()`
- "RUF015", # Unnecessary iterable allocation for first element
- "C408", # Unnecessary `dict`/`list`/`tuple` call
- "C419", # Unnecessary comprehension inside `any`/`all`/`sum`/`min`/`max`
- "SIM103", # Needless bool
- "PIE810", # Multiple `startswith` / `endswith` calls
- "C401", # Unnecessary generator set
"RUF012", # Mutable class default
"S102", # Use of `exec`
- "TRY201", # Verbose `raise` (use `raise` without exception name)
"PYI036", # Bad `sys.exit` annotation
- "RUF013", # Implicit optional
"DTZ005", # `datetime.now()` called without `tzinfo`
"PLC0206", # Dict index without `.items()`
"PYI066", # Put branches for newer Python versions first when branching on `sys.version_info` comparisons
"SIM115", # Open file without context handler
- "C403", # Unnecessary list comprehension set
- "C414", # Unnecessary double cast or process
- "SIM101", # Duplicate `isinstance` call
- "SIM401", # Use `dict.get` instead of if-else block
"DTZ006", # `datetime.fromtimestamp()` called without `tzinfo`
"DTZ007", # `datetime.strptime()` called without zone
"DTZ011", # `date.today()` used
- "PYI034", # Non-self return type
- "RUF022", # Unsorted `__all__`
"TRY401", # Verbose log message
"UP007", # Use `X | Y` for type annotations
- "D420", # Incorrect docstring section order
"DTZ012", # `date.fromtimestamp()` called without `tzinfo`
"DTZ901", # `datetime.min` / `datetime.max` used
"PLW0602", # Global variable not assigned
"S112", # `try`-`except`-`continue`
"TRY203", # Useless `try`-`except`
- "C409", # Unnecessary list literal passed to `tuple()` (rewrite as a tuple literal)
"PLC0105", # Type name incorrect variance
- "C400", # Unnecessary generator list
- "C411", # Unnecessary list call
"PLE1205", # Logging too many args
"PLW1508", # Invalid envvar default
"PLW1509", # `subprocess` `preexec_fn` argument
- "PYI059", # Generic not last base class
"PYI063", # PEP 484-style positional-only parameter
- "SIM201", # Negate equal op
"DTZ002", # `datetime.today()` called without tz
- "FURB132", # Check and remove from set
- "PERF102", # Incorrect dict iterator
- "PIE794", # Duplicate class field definition
"PLC0205", # Single string `__slots__`
- "PLC0414", # Useless import alias
"PLE0704", # Misplaced bare `raise`
"PLR1704", # Redefined argument from local
"PLW0129", # Assert on string literal
- "PLW0133", # Useless exception statement
"PLW0642", # Self or cls assignment
"PYI006", # Bad `sys.version_info` comparison
"SIM113", # `enumerate` for loop
- "SIM210", # If expression with `True`/`False`
"T100", # Debugger
"UP045", # Use `X | None` for optional type annotations
-
]
+
extend-select = [
# pyflakes
"F",
@@ -472,6 +443,8 @@ convention = "google"
[tool.ruff.lint.per-file-ignores]
"**/{tests}/*" = ["ANN201", "ANN202", "T201", "D", "F841", "PLW1514"]
"dagger/*" = ["TID252"]
+# Prefer multi-line "\n".join([...]) expected strings in codegen tests.
+"tests/_ast/test_codegen.py" = ["FLY002"]
[tool.ruff.lint.isort]
required-imports = ["from __future__ import annotations"]
diff --git a/tests/_ai/llm/test_impl.py b/tests/_ai/llm/test_impl.py
index 5f900441df..6b23b74c55 100644
--- a/tests/_ai/llm/test_impl.py
+++ b/tests/_ai/llm/test_impl.py
@@ -287,7 +287,7 @@ class TestOpenAI:
self, mock_openai_client, test_messages, test_config
):
"""Test calling the openai class with a custom base URL."""
- mock_client, mock_openai_class = mock_openai_client
+ _mock_client, mock_openai_class = mock_openai_client
# Create model with API key and base URL
model = openai(
@@ -560,7 +560,7 @@ class TestGroq:
self, mock_groq_client, test_messages, test_config
):
"""Test calling the groq class with a custom base URL."""
- mock_client, mock_groq_class = mock_groq_client
+ _mock_client, mock_groq_class = mock_groq_client
# Create model with API key and base URL
model = groq(
diff --git a/tests/_ast/test_cell.py b/tests/_ast/test_cell.py
index 4ebef9a1ea..3b620cd701 100644
--- a/tests/_ast/test_cell.py
+++ b/tests/_ast/test_cell.py
@@ -25,7 +25,7 @@ class TestCellRun:
cell = app.cell(f)
assert cell.name == "f"
assert not cell.refs
- assert cell.defs == set(["x"])
+ assert cell.defs == {"x"}
assert not cell._is_coroutine
assert cell.run() == ("output", {"x": 4})
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index d32653ce42..2b5c128a4a 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -1462,9 +1462,9 @@ def test_recover(tmp_path: Path) -> None:
recovered = codegen.recover(tempfile_name)
codes = [
- "\n".join(['"santa"', "", '"clause"', "", "", ""]),
+ '"santa"\n\n"clause"\n\n\n',
"",
- "\n".join(["", "123"]),
+ "\n123",
]
names = ["a", "b", "c"]
@@ -1518,12 +1518,12 @@ def test_is_internal_cell_name() -> None:
def test_format_tuple_elements() -> None:
kv_case = codegen.format_tuple_elements(
"@app.fn(...)",
- tuple(["a", "b", "c"]),
+ ("a", "b", "c"),
)
assert kv_case == "@app.fn(a, b, c)"
indent_case = codegen.format_tuple_elements(
- "def fn(...):", tuple(["a", "b", "c"]), indent=True
+ "def fn(...):", ("a", "b", "c"), indent=True
)
assert indent_case == " def fn(a, b, c):"
diff --git a/tests/_ast/test_compiler.py b/tests/_ast/test_compiler.py
index d05a88c0cc..a5002d3bf4 100644
--- a/tests/_ast/test_compiler.py
+++ b/tests/_ast/test_compiler.py
@@ -25,8 +25,8 @@ class TestParseCell:
cell = compile_cell(code)
assert cell.key == hash(code)
assert cell.code == code
- assert cell.defs == set(["x", "z"])
- assert cell.refs == set(["y"])
+ assert cell.defs == {"x", "z"}
+ assert cell.refs == {"y"}
@staticmethod
def test_local_variables() -> None:
@@ -98,49 +98,49 @@ class TestImportWorkspace:
def test_simple_import_statement() -> None:
code = "import foo"
cell = compile_cell(code)
- assert cell.defs == set(["foo"])
+ assert cell.defs == {"foo"}
assert cell.import_workspace.is_import_block
assert not cell.import_workspace.imported_defs
assert len(list(cell.imports)) == 1
- assert list(cell.imports)[0].definition == "foo"
- assert list(cell.imports)[0].imported_symbol is None
- assert list(cell.imports)[0].module == "foo"
- assert list(cell.imports)[0].namespace == "foo"
- assert list(cell.imports)[0].import_level is None
+ assert next(iter(cell.imports)).definition == "foo"
+ assert next(iter(cell.imports)).imported_symbol is None
+ assert next(iter(cell.imports)).module == "foo"
+ assert next(iter(cell.imports)).namespace == "foo"
+ assert next(iter(cell.imports)).import_level is None
@staticmethod
def test_dotted_import_statement() -> None:
code = "import foo.bar"
cell = compile_cell(code)
- assert cell.defs == set(["foo"])
+ assert cell.defs == {"foo"}
assert cell.import_workspace.is_import_block
assert not cell.import_workspace.imported_defs
assert len(list(cell.imports)) == 1
- assert list(cell.imports)[0].definition == "foo"
- assert list(cell.imports)[0].imported_symbol is None
- assert list(cell.imports)[0].module == "foo.bar"
- assert list(cell.imports)[0].namespace == "foo"
- assert list(cell.imports)[0].import_level is None
+ assert next(iter(cell.imports)).definition == "foo"
+ assert next(iter(cell.imports)).imported_symbol is None
+ assert next(iter(cell.imports)).module == "foo.bar"
+ assert next(iter(cell.imports)).namespace == "foo"
+ assert next(iter(cell.imports)).import_level is None
@staticmethod
def test_from_import() -> None:
code = "from foo.bar import baz"
cell = compile_cell(code)
- assert cell.defs == set(["baz"])
+ assert cell.defs == {"baz"}
assert cell.import_workspace.is_import_block
assert not cell.import_workspace.imported_defs
assert len(list(cell.imports)) == 1
- assert list(cell.imports)[0].definition == "baz"
- assert list(cell.imports)[0].imported_symbol == "foo.bar.baz"
- assert list(cell.imports)[0].module == "foo.bar"
- assert list(cell.imports)[0].namespace == "foo"
- assert list(cell.imports)[0].import_level == 0
+ assert next(iter(cell.imports)).definition == "baz"
+ assert next(iter(cell.imports)).imported_symbol == "foo.bar.baz"
+ assert next(iter(cell.imports)).module == "foo.bar"
+ assert next(iter(cell.imports)).namespace == "foo"
+ assert next(iter(cell.imports)).import_level == 0
@staticmethod
def test_multiple_imports() -> None:
code = "import foo; import foo.bar; from foo.bar import baz"
cell = compile_cell(code)
- assert cell.defs == set(["foo", "baz"])
+ assert cell.defs == {"foo", "baz"}
assert cell.import_workspace.is_import_block
assert not cell.import_workspace.imported_defs
assert len(list(cell.imports)) == 3
@@ -202,9 +202,9 @@ class TestImportWorkspace:
code = "import foo; import foo.bar; from foo.bar import baz"
cell = compile_cell(code, carried_imports=[foo])
- assert cell.defs == set(["foo", "baz"])
+ assert cell.defs == {"foo", "baz"}
assert cell.import_workspace.is_import_block
- assert cell.import_workspace.imported_defs == set(["foo"])
+ assert cell.import_workspace.imported_defs == {"foo"}
assert len(list(cell.imports)) == 3
assert foo in cell.imports
@@ -234,9 +234,9 @@ class TestImportWorkspace:
code = "import foo; import foo.bar; from foo.bar import baz"
cell = compile_cell(code, carried_imports=[foo, foo_bar, foo_bar_baz])
- assert cell.defs == set(["foo", "baz"])
+ assert cell.defs == {"foo", "baz"}
assert cell.import_workspace.is_import_block
- assert cell.import_workspace.imported_defs == set(["foo", "baz"])
+ assert cell.import_workspace.imported_defs == {"foo", "baz"}
assert len(list(cell.imports)) == 3
assert foo in cell.imports
@@ -255,7 +255,7 @@ class TestImportWorkspace:
)
code = "import foo.bar"
cell = compile_cell(code, carried_imports=[foo])
- assert cell.defs == set(["foo"])
+ assert cell.defs == {"foo"}
assert cell.import_workspace.is_import_block
assert not cell.import_workspace.imported_defs
@@ -268,8 +268,8 @@ class TestParseSQLCell:
cell = compile_cell(code)
assert cell.key == hash(code)
assert cell.code == code
- assert cell.defs == set(["t1"])
- assert cell.refs == set(["mo"])
+ assert cell.defs == {"t1"}
+ assert cell.refs == {"mo"}
assert cell.language == "sql"
assert cell.variable_data == {
"t1": [VariableData("table", qualified_name="t1")]
@@ -282,7 +282,7 @@ class TestParseSQLCell:
assert cell.key == hash(code)
assert cell.code == code
assert not cell.defs
- assert cell.refs == set(["mo", "t1"])
+ assert cell.refs == {"mo", "t1"}
assert cell.language == "sql"
assert not cell.variable_data
@@ -298,8 +298,8 @@ class TestParseSQLCell:
cell = compile_cell(code)
assert cell.key == hash(code)
assert cell.code == code
- assert cell.defs == set(["t1"])
- assert cell.refs == set(["duckdb"])
+ assert cell.defs == {"t1"}
+ assert cell.refs == {"duckdb"}
assert cell.language == "sql"
assert cell.variable_data == {
"t1": [VariableData("table", qualified_name="t1")]
@@ -318,7 +318,7 @@ class TestParseSQLCell:
assert cell.key == hash(code)
assert cell.code == code
assert not cell.defs
- assert cell.refs == set(["duckdb", "t1"])
+ assert cell.refs == {"duckdb", "t1"}
assert cell.language == "sql"
assert not cell.variable_data
diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.py
index 55eaba3c07..0a5a024fd3 100644
--- a/tests/_ast/test_visitor.py
+++ b/tests/_ast/test_visitor.py
@@ -23,7 +23,7 @@ def test_assign_simple() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["x"])
+ assert v.defs == {"x"}
assert v.refs == set()
assert v.variable_data == {"x": [VariableData(kind="variable")]}
@@ -33,7 +33,7 @@ def test_multiple_assign() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["x", "y"])
+ assert v.defs == {"x", "y"}
assert v.refs == set()
assert v.variable_data == {
"x": [VariableData(kind="variable")],
@@ -46,7 +46,7 @@ def test_assign_multiple_statements() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["x", "y"])
+ assert v.defs == {"x", "y"}
assert v.refs == set()
assert v.variable_data == {
"x": [VariableData(kind="variable")],
@@ -60,7 +60,7 @@ def test_assign_attr() -> None:
mod = ast.parse(expr)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["x"])
+ assert v.refs == {"x"}
assert not v.variable_data
@@ -70,7 +70,7 @@ def test_read_attr() -> None:
mod = ast.parse(expr)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["x"])
+ assert v.refs == {"x"}
assert not v.variable_data
@@ -79,7 +79,7 @@ def test_read_attr_of_defined_variable() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["x"])
+ assert v.defs == {"x"}
assert v.refs == set()
assert v.variable_data == {"x": [VariableData(kind="variable")]}
@@ -90,7 +90,7 @@ def test_assign_nested_attr() -> None:
mod = ast.parse(expr)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["x"])
+ assert v.refs == {"x"}
assert not v.variable_data
@@ -100,7 +100,7 @@ def test_read_nested_attr() -> None:
mod = ast.parse(expr)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["x"])
+ assert v.refs == {"x"}
assert not v.variable_data
@@ -109,8 +109,8 @@ def test_assign_same_name() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["x"])
- assert v.refs == set(["x"])
+ assert v.defs == {"x"}
+ assert v.refs == {"x"}
assert v.variable_data == {
"x": [VariableData(kind="variable", required_refs={"x"})]
}
@@ -119,7 +119,7 @@ def test_assign_same_name() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["x"])
+ assert v.defs == {"x"}
assert v.refs == set()
assert v.variable_data == {
"x": [
@@ -132,8 +132,8 @@ def test_assign_same_name() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["x"])
- assert v.refs == set(["x"])
+ assert v.defs == {"x"}
+ assert v.refs == {"x"}
assert v.variable_data == {
"x": [VariableData(kind="variable", required_refs={"x"})]
}
@@ -142,8 +142,8 @@ def test_assign_same_name() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["x"])
- assert v.refs == set(["x"])
+ assert v.defs == {"x"}
+ assert v.refs == {"x"}
assert v.variable_data == {
"x": [VariableData(kind="variable", required_refs={"x"})]
}
@@ -152,8 +152,8 @@ def test_assign_same_name() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["f"])
- assert v.refs == set(["x"])
+ assert v.defs == {"f"}
+ assert v.refs == {"x"}
assert v.variable_data == {
"f": [
VariableData(
@@ -166,8 +166,8 @@ def test_assign_same_name() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["F"])
- assert v.refs == set(["x"])
+ assert v.defs == {"F"}
+ assert v.refs == {"x"}
assert v.variable_data == {
"F": [
VariableData(
@@ -181,7 +181,7 @@ def test_assign_same_name() -> None:
mod = ast.parse(expr)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["x"])
+ assert v.refs == {"x"}
assert not v.variable_data
@@ -191,7 +191,7 @@ def test_load_attr() -> None:
mod = ast.parse(expr)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["x"])
+ assert v.refs == {"x"}
assert not v.variable_data
@@ -200,7 +200,7 @@ def test_structured_assignment() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- names = set(["a", "b", "c", "d", "e", "f", "g", "h"])
+ names = {"a", "b", "c", "d", "e", "f", "g", "h"}
assert v.defs == names
assert v.refs == set()
assert v.variable_data == {
@@ -220,7 +220,7 @@ def test_starred_assignment() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["a", "b"])
+ assert v.defs == {"a", "b"}
assert v.refs == set()
assert v.variable_data == {
"a": [VariableData(kind="variable")],
@@ -229,17 +229,11 @@ def test_starred_assignment() -> None:
def test_scope_does_not_leak() -> None:
- code = "\n".join(
- [
- "def foo():",
- " z = 0",
- "z",
- ]
- )
+ code = "def foo():\n z = 0\nz"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo"])
+ assert v.defs == {"foo"}
assert v.refs == set("z")
assert v.variable_data == {
"foo": [VariableData(kind="function")],
@@ -247,60 +241,42 @@ def test_scope_does_not_leak() -> None:
def test_nested_comprehensions() -> None:
- code = "\n".join(
- [
- "[(i, j) for i in range(10) for j in range(i)]",
- "{(i, j) for i in range(10) for j in range(i)}",
- "{i: j for i in range(10) for j in range(i)}",
- ]
- )
+ code = "[(i, j) for i in range(10) for j in range(i)]\n{(i, j) for i in range(10) for j in range(i)}\n{i: j for i in range(10) for j in range(i)}"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["range"])
+ assert v.refs == {"range"}
assert not v.variable_data
def test_comprehension_generator() -> None:
- code = "\n".join(
- [
- "[x for x in x]",
- ]
- )
+ code = "[x for x in x]"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["x"])
+ assert v.refs == {"x"}
assert not v.variable_data
def test_nested_comprehension_generator() -> None:
- code = "\n".join(
- [
- "[x for x in x for x in x]",
- ]
- )
+ code = "[x for x in x for x in x]"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["x"])
+ assert v.refs == {"x"}
assert not v.variable_data
def test_nested_comprehension_generator_with_named_expr() -> None:
- code = "\n".join(
- [
- "[(x := x) for x in x for x in x]",
- ]
- )
+ code = "[(x := x) for x in x for x in x]"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
# named expr kicks x out, evicting the ref
- assert v.defs == set(["x"])
+ assert v.defs == {"x"}
assert v.refs == set()
assert v.variable_data == {"x": [VariableData(kind="variable")]}
@@ -396,20 +372,13 @@ def test_shadowed_param_in_comprehension_not_required_ref() -> None:
def test_walrus_leaks_to_global_in_comprehension() -> None:
- code = "\n".join(
- [
- "def foo(): a",
- "[(a := (i, (b := j))) for i in range(10) for j in range(i)]",
- "{(c := (i, j)) for i in range(10) for j in range(i)}",
- "{i: (d := j) for i in range(10) for j in range(i)}",
- ]
- )
+ code = "def foo(): a\n[(a := (i, (b := j))) for i in range(10) for j in range(i)]\n{(c := (i, j)) for i in range(10) for j in range(i)}\n{i: (d := j) for i in range(10) for j in range(i)}"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["a", "b", "c", "d", "foo"])
+ assert v.defs == {"a", "b", "c", "d", "foo"}
# "a" should not be a ref!
- assert v.refs == set(["range"])
+ assert v.refs == {"range"}
assert v.variable_data == {
"a": [VariableData(kind="variable")],
"b": [VariableData(kind="variable")],
@@ -424,8 +393,8 @@ def test_nested_walrus_leaks_to_global_in_comprehension() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["a", "b"])
- assert v.refs == set(["range"])
+ assert v.defs == {"a", "b"}
+ assert v.refs == {"range"}
assert v.variable_data == {
"a": [VariableData(kind="variable")],
"b": [VariableData(kind="variable")],
@@ -437,8 +406,8 @@ def test_pep572_walrus_comprehension_examples() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["y"])
- assert v.refs == set(["input_data", "f"])
+ assert v.defs == {"y"}
+ assert v.refs == {"input_data", "f"}
assert v.variable_data == {
"y": [VariableData(kind="variable")],
}
@@ -447,43 +416,33 @@ def test_pep572_walrus_comprehension_examples() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["y"])
- assert v.refs == set(["f", "range"])
+ assert v.defs == {"y"}
+ assert v.refs == {"f", "range"}
assert v.variable_data == {
"y": [VariableData(kind="variable")],
}
def test_walrus_in_comp_in_fn_block_does_not_leak_to_global() -> None:
- code = "\n".join(
- ["def f():", " [(x := 0) for i in range(5)]", " y = x + 1"]
- )
+ code = "def f():\n [(x := 0) for i in range(5)]\n y = x + 1"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["f"]) # x should _not_ leak to global scope
- assert v.refs == set(["range"]) # x should leak to f's scope
+ assert v.defs == {"f"} # x should _not_ leak to global scope
+ assert v.refs == {"range"} # x should leak to f's scope
assert v.variable_data == {
"f": [VariableData(kind="function", required_refs={"range"})],
}
def test_assignments_in_multiple_scopes() -> None:
- code = "\n".join(
- [
- "a = 0",
- "def foo():",
- " b = 0",
- " c = 0",
- " def bar():",
- " d = 0",
- "e = 0",
- ]
+ code = (
+ "a = 0\ndef foo():\n b = 0\n c = 0\n def bar():\n d = 0\ne = 0"
)
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["a", "e", "foo"])
+ assert v.defs == {"a", "e", "foo"}
assert v.refs == set()
assert v.variable_data == {
"a": [VariableData(kind="variable")],
@@ -503,7 +462,7 @@ def test_function_with_args() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo"])
+ assert v.defs == {"foo"}
assert v.refs == set("z")
assert v.variable_data == {
"foo": [VariableData(kind="function", required_refs={"z"})],
@@ -519,8 +478,8 @@ def test_annotations_captured() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["x"])
- assert v.refs == set(["int", "CONSTANT"])
+ assert v.defs == {"x"}
+ assert v.refs == {"int", "CONSTANT"}
assert v.variable_data == {
"x": [
VariableData(
@@ -542,8 +501,8 @@ def test_function_with_defaults() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo"])
- assert v.refs == set(["x", "y", "a"])
+ assert v.defs == {"foo"}
+ assert v.refs == {"x", "y", "a"}
# TODO: Are these required refs?
assert v.variable_data == {
"foo": [
@@ -568,7 +527,7 @@ def test_async_function_def() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo", "x"])
+ assert v.defs == {"foo", "x"}
assert v.refs == set("z")
assert v.variable_data == {
"foo": [VariableData(kind="function", required_refs={"z"})],
@@ -587,7 +546,7 @@ def test_global_def() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo", "x"])
+ assert v.defs == {"foo", "x"}
assert v.refs == set()
assert v.variable_data == {
"foo": [VariableData(kind="function", required_refs={"x"})],
@@ -606,7 +565,7 @@ def test_global_not_ref() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo", "x"])
+ assert v.defs == {"foo", "x"}
assert v.refs == set()
@@ -621,7 +580,7 @@ def test_global_not_ref_define_later() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo", "x"])
+ assert v.defs == {"foo", "x"}
assert v.refs == set()
@@ -639,7 +598,7 @@ def test_global_after_scoped_def() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["f", "x"])
+ assert v.defs == {"f", "x"}
assert not v.refs
@@ -654,8 +613,8 @@ def test_global_ref() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo"])
- assert v.refs == set(["x", "print"])
+ assert v.defs == {"foo"}
+ assert v.refs == {"x", "print"}
assert v.variable_data == {
"foo": [VariableData(kind="function", required_refs={"x", "print"})],
}
@@ -672,8 +631,8 @@ def test_global_deleted_ref() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["f"])
- assert v.refs == set(["x"])
+ assert v.defs == {"f"}
+ assert v.refs == {"x"}
assert v.deleted_refs == {"x"}
@@ -690,8 +649,8 @@ def test_nested_local_def_and_global_ref() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo"])
- assert v.refs == set(["x", "print"])
+ assert v.defs == {"foo"}
+ assert v.refs == {"x", "print"}
assert v.variable_data == {
"foo": [VariableData(kind="function", required_refs={"x", "print"})],
}
@@ -703,22 +662,18 @@ def test_call_ref() -> None:
mod = ast.parse(code)
v.visit(mod)
assert v.defs == set()
- assert v.refs == set(["foo"])
+ assert v.refs == {"foo"}
assert not v.variable_data
def test_call_defined() -> None:
# fmt: off
- code = "\n".join([
- "def foo():",
- " pass",
- "foo()"
- ])
+ code = "def foo():\n pass\nfoo()"
# fmt: on
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["foo"])
+ assert v.defs == {"foo"}
assert v.refs == set()
assert v.variable_data == {
"foo": [VariableData(kind="function")],
@@ -730,7 +685,7 @@ def test_mutation_generates_def() -> None:
mod = ast.parse(code)
v = visitor.ScopedVisitor()
v.visit(mod)
- assert v.defs == set(["x"])
+ assert v.defs == {"x"}
assert v.refs == set()
assert v.variable_data == {
"x": [VariableData(kind="variable")],
@@ -749,8 +704,8 @@ def test_captured_variables() -> None:
mod = ast.parse(code)
v = visitor.ScopedVisitor()
v.visit(mod)
- assert v.defs == set(["f", "x"])
- assert v.refs == set([])
+ assert v.defs == {"f", "x"}
+ assert v.refs == set()
code = cleandoc(
"""
@@ -763,8 +718,8 @@ def test_captured_variables() -> None:
mod = ast.parse(code)
v = visitor.ScopedVisitor()
v.visit(mod)
- assert v.defs == set(["f", "x"])
- assert v.refs == set([])
+ assert v.defs == {"f", "x"}
+ assert v.refs == set()
code = cleandoc(
"""
@@ -778,8 +733,8 @@ def test_captured_variables() -> None:
mod = ast.parse(code)
v = visitor.ScopedVisitor()
v.visit(mod)
- assert v.defs == set(["f", "x"])
- assert v.refs == set([])
+ assert v.defs == {"f", "x"}
+ assert v.refs == set()
code = cleandoc(
"""
@@ -792,8 +747,8 @@ def test_captured_variables() -> None:
mod = ast.parse(code)
v = visitor.ScopedVisitor()
v.visit(mod)
- assert v.defs == set(["f"])
- assert v.refs == set([])
+ assert v.defs == {"f"}
+ assert v.refs == set()
code = cleandoc(
"""
@@ -808,8 +763,8 @@ def test_captured_variables() -> None:
mod = ast.parse(code)
v = visitor.ScopedVisitor()
v.visit(mod)
- assert v.defs == set(["f", "h"])
- assert v.refs == set(["x"])
+ assert v.defs == {"f", "h"}
+ assert v.refs == {"x"}
def test_matchas() -> None:
@@ -829,8 +784,8 @@ def test_matchas() -> None:
mod = ast.parse(code)
v = visitor.ScopedVisitor()
v.visit(mod)
- assert v.defs == set(["a", "b", "c", "d", "e", "f"])
- assert v.refs == set(["value"])
+ assert v.defs == {"a", "b", "c", "d", "e", "f"}
+ assert v.refs == {"value"}
assert v.variable_data == {
"a": [VariableData(kind="variable")],
"b": [VariableData(kind="variable")],
@@ -854,8 +809,8 @@ def test_matchstar() -> None:
mod = ast.parse(code)
v = visitor.ScopedVisitor()
v.visit(mod)
- assert v.defs == set(["rest"])
- assert v.refs == set(["value"])
+ assert v.defs == {"rest"}
+ assert v.refs == {"value"}
assert v.variable_data == {
"rest": [VariableData(kind="variable")],
}
@@ -876,8 +831,8 @@ def test_matchmapping() -> None:
mod = ast.parse(code)
v = visitor.ScopedVisitor()
v.visit(mod)
- assert v.defs == set(["a", "b"])
- assert v.refs == set(["value"])
+ assert v.defs == {"a", "b"}
+ assert v.refs == {"value"}
assert v.variable_data == {
"a": [VariableData(kind="variable")],
"b": [VariableData(kind="variable")],
@@ -889,7 +844,7 @@ def test_import_nested() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["a"])
+ assert v.defs == {"a"}
assert v.refs == set()
assert v.variable_data["a"] == [
VariableData(
@@ -906,7 +861,7 @@ def test_import_as() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["d"])
+ assert v.defs == {"d"}
assert v.refs == set()
assert v.variable_data["d"] == [
VariableData(
@@ -923,7 +878,7 @@ def test_import_multiple() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["a", "d"])
+ assert v.defs == {"a", "d"}
assert v.refs == set()
assert v.variable_data["a"] == [
VariableData(
@@ -948,7 +903,7 @@ def test_from_import() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["d"])
+ assert v.defs == {"d"}
assert v.refs == set()
assert v.variable_data["d"] == [
VariableData(
@@ -968,7 +923,7 @@ def test_relative_from_import() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["d"])
+ assert v.defs == {"d"}
assert v.refs == set()
assert v.variable_data["d"] == [
VariableData(
@@ -996,28 +951,7 @@ def test_from_import_star() -> None:
def test_try_block() -> None:
- code = "\n".join(
- [
- "f = 2",
- "try:",
- " v = 1 / 0",
- "except TypeError as e:",
- " err = e",
- " e = 0",
- " x = out_of_scope",
- " print(f'caught {type(e)} with nested {e.exceptions}')",
- "except OSError as f:",
- " err2 = f",
- " try:",
- " y = 1 / 0",
- " except ZeroDivisionError as g:",
- " err3 = g",
- "else:",
- " w = 1",
- "finally:",
- " z = 3",
- ]
- )
+ code = "f = 2\ntry:\n v = 1 / 0\nexcept TypeError as e:\n err = e\n e = 0\n x = out_of_scope\n print(f'caught {type(e)} with nested {e.exceptions}')\nexcept OSError as f:\n err2 = f\n try:\n y = 1 / 0\n except ZeroDivisionError as g:\n err3 = g\nelse:\n w = 1\nfinally:\n z = 3"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
@@ -1026,33 +960,17 @@ def test_try_block() -> None:
assert "e" not in v.refs
assert "f" not in v.refs
assert "g" not in v.refs
- assert v.defs == set(["f", "v", "w", "x", "y", "z", "err", "err2", "err3"])
+ assert v.defs == {"f", "v", "w", "x", "y", "z", "err", "err2", "err3"}
@pytest.mark.skipif("sys.version_info < (3, 11)")
def test_try_star_block() -> None:
- code = "\n".join(
- [
- "try:",
- (
- " raise ExceptionGroup('eg', "
- "[ValueError(1), TypeError(2), OSError(3)])"
- ),
- "except* TypeError as e:",
- " print(f'caught {type(e)} with nested {e.exceptions}')",
- "except* OSError as f:",
- " print(f'caught {type(f)} with nested {f.exceptions}')",
- "else:",
- " print('Type and Os not raised')",
- "finally:",
- " print('finally')",
- ]
- )
+ code = "try:\n raise ExceptionGroup('eg', [ValueError(1), TypeError(2), OSError(3)])\nexcept* TypeError as e:\n print(f'caught {type(e)} with nested {e.exceptions}')\nexcept* OSError as f:\n print(f'caught {type(f)} with nested {f.exceptions}')\nelse:\n print('Type and Os not raised')\nfinally:\n print('finally')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
# T should not be among the refs or defs
- assert v.defs == set([])
+ assert v.defs == set()
assert "e" not in v.refs
assert "f" not in v.refs
@@ -1064,8 +982,8 @@ def test_type_alias_scoped() -> None:
mod = ast.parse(expr)
v.visit(mod)
# T should not be among the refs or defs
- assert v.defs == set(["alias"])
- assert v.refs == set(["list"])
+ assert v.defs == {"alias"}
+ assert v.refs == {"list"}
@pytest.mark.skipif("sys.version_info < (3, 12)")
@@ -1081,7 +999,7 @@ def test_type_var_generic_class() -> None:
mod = ast.parse(expr)
v.visit(mod)
# T should not be among the refs or defs
- assert v.defs == set(["A"])
+ assert v.defs == {"A"}
assert v.refs == set()
@@ -1096,29 +1014,22 @@ def test_type_var_generic_function() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(expr)
v.visit(mod)
- assert v.defs == set(["test"])
+ assert v.defs == {"test"}
# U should not be a ref
assert v.refs == set()
def test_private_ref_requirement_caught() -> None:
- code = "\n".join(
- [
- "x = 1",
- "_x = 1",
- "def foo():",
- " z = _x + x + X",
- ]
- )
+ code = "x = 1\n_x = 1\ndef foo():\n z = _x + x + X"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert len(v.defs & set(["foo", "x"])) == 2
- assert len(v.defs - set(["foo", "x"])) == 1
- (private,) = v.defs - set(["foo", "x"])
+ assert len(v.defs & {"foo", "x"}) == 2
+ assert len(v.defs - {"foo", "x"}) == 1
+ (private,) = v.defs - {"foo", "x"}
assert private.startswith("_")
assert private.endswith("_x")
- assert v.refs == set(["X"])
+ assert v.refs == {"X"}
assert v.variable_data == {
private: [VariableData(kind="variable")],
"x": [VariableData(kind="variable")],
@@ -1209,30 +1120,22 @@ HAS_SQLGLOT = DependencyManager.sqlglot.has()
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_statement() -> None:
- code = "\n".join(
- [
- "df = mo.sql('select * from cars')",
- ]
- )
+ code = "df = mo.sql('select * from cars')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["df"])
- assert v.refs == set(["cars", "mo"])
+ assert v.defs == {"df"}
+ assert v.refs == {"cars", "mo"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_statement_with_marimo_sql() -> None:
- code = "\n".join(
- [
- "df = marimo.sql('select * from cars')",
- ]
- )
+ code = "df = marimo.sql('select * from cars')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["df"])
- assert v.refs == set(["cars", "marimo"])
+ assert v.defs == {"df"}
+ assert v.refs == {"cars", "marimo"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
@@ -1247,36 +1150,28 @@ def test_sql_statement_with_duckdb_sql(code: str) -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["df"])
- assert v.refs == set(["cars", "duckdb"])
+ assert v.defs == {"df"}
+ assert v.refs == {"cars", "duckdb"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_statement_with_f_string() -> None:
- code = "\n".join(
- [
- "df = mo.sql(f'select * from cars where name = {name}')",
- ]
- )
+ code = "df = mo.sql(f'select * from cars where name = {name}')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["df"])
- assert v.refs == set(["cars", "mo", "name"])
+ assert v.defs == {"df"}
+ assert v.refs == {"cars", "mo", "name"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_statement_with_rf_string() -> None:
- code = "\n".join(
- [
- "df = mo.sql(rf'select * from cars where name = {name}')",
- ]
- )
+ code = "df = mo.sql(rf'select * from cars where name = {name}')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["df"])
- assert v.refs == set(["cars", "mo", "name"])
+ assert v.defs == {"df"}
+ assert v.refs == {"cars", "mo", "name"}
def test_print_f_string() -> None:
@@ -1403,8 +1298,8 @@ def test_sql_empty_statement() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set([])
- assert v.refs == set(["mo"])
+ assert v.defs == set()
+ assert v.refs == {"mo"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
@@ -1413,55 +1308,41 @@ def test_sql_empty_statement_duckdb() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set([])
- assert v.refs == set(["duckdb"])
+ assert v.defs == set()
+ assert v.refs == {"duckdb"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_multiple_tables() -> None:
- code = "\n".join(
- [
- "df = mo.sql('select * from cars left join"
- " cars2 on cars.id = cars2.id')",
- ]
- )
+ code = "df = mo.sql('select * from cars left join cars2 on cars.id = cars2.id')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["df"])
- assert v.refs == set(["cars", "cars2", "mo"])
+ assert v.defs == {"df"}
+ assert v.refs == {"cars", "cars2", "mo"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_from_another_module() -> None:
- code = "\n".join(
- [
- "df = lib.sql('select * from cars')",
- ]
- )
+ code = "df = lib.sql('select * from cars')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["df"])
- assert v.refs == set(["lib"])
+ assert v.defs == {"df"}
+ assert v.refs == {"lib"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_statement_with_url() -> None:
- code = "\n".join(
- [
- 'mo.sql("CREATE OR replace TABLE cars as '
- "FROM 'https://datasets.marimo.app/cars.csv';\")",
- ]
- )
+ code = "mo.sql(\"CREATE OR replace TABLE cars as FROM 'https://datasets.marimo.app/cars.csv';\")"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["cars"])
+ assert v.defs == {"cars"}
assert v.variable_data == {
"cars": [VariableData("table", qualified_name="cars")]
}
- assert v.refs == set(["mo"])
+ assert v.refs == {"mo"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
@@ -1477,93 +1358,78 @@ def test_sql_statement_with_function() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["prompt_embeddings"])
- assert v.refs == set(["mo", "prompts"])
+ assert v.defs == {"prompt_embeddings"}
+ assert v.refs == {"mo", "prompts"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_unparsable_sql_doesnt_fail() -> None:
- code = "\n".join(
- [
- # duckdb will raise a BinderError, but codegen shouldnt fail.
- # sqlglot can still extract table refs even when duckdb can't
- # parse the SQL.
- "df = mo.sql('select * from cars where cars.foo = ANY({bar})')",
- ]
- )
+ code = "df = mo.sql('select * from cars where cars.foo = ANY({bar})')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["df"])
- assert v.refs == set(["mo", "cars"])
+ assert v.defs == {"df"}
+ assert v.refs == {"mo", "cars"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_attach() -> None:
- code = "\n".join(
- [
- "mo.sql(f\"ATTACH 'dbname=postgres user=postgres host=127.0.0.1 password=password' as db\")"
- ]
- )
+ code = "mo.sql(f\"ATTACH 'dbname=postgres user=postgres host=127.0.0.1 password=password' as db\")"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["db"])
- assert v.refs == set(["mo"])
+ assert v.defs == {"db"}
+ assert v.refs == {"mo"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_attach_f_string() -> None:
- code = "\n".join(
- [
- "mo.sql(f\"ATTACH 'dbname=postgres user=postgres host=127.0.0.1 password={PASSWORD}' as db\")"
- ]
- )
+ code = "mo.sql(f\"ATTACH 'dbname=postgres user=postgres host=127.0.0.1 password={PASSWORD}' as db\")"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set(["db"])
- assert v.refs == set(["mo", "PASSWORD"])
+ assert v.defs == {"db"}
+ assert v.refs == {"mo", "PASSWORD"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_int_f_string() -> None:
- code = "\n".join(["mo.sql(f'SELECT * FROM df LIMIT {lim}')"])
+ code = "mo.sql(f'SELECT * FROM df LIMIT {lim}')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
assert not v.defs
- assert v.refs == set(["mo", "df", "lim"])
+ assert v.refs == {"mo", "df", "lim"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_column_f_string() -> None:
- code = "\n".join(["mo.sql(f'SELECT {col} FROM df LIMIT {lim}')"])
+ code = "mo.sql(f'SELECT {col} FROM df LIMIT {lim}')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
assert not v.defs
- assert v.refs == set(["mo", "df", "lim", "col"])
+ assert v.refs == {"mo", "df", "lim", "col"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_value_f_string() -> None:
- code = "\n".join(["mo.sql(f'SELECT * FROM df WHERE {col} = {val}')"])
+ code = "mo.sql(f'SELECT * FROM df WHERE {col} = {val}')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
assert not v.defs
- assert v.refs == set(["mo", "df", "col", "val"])
+ assert v.refs == {"mo", "df", "col", "val"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_table_f_string() -> None:
- code = "\n".join(["mo.sql(f'SELECT * FROM {my_table} LIMIT {lim}')"])
+ code = "mo.sql(f'SELECT * FROM {my_table} LIMIT {lim}')"
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
assert not v.defs
- assert v.refs == set(["mo", "my_table", "lim"])
+ assert v.refs == {"mo", "my_table", "lim"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
@@ -1579,7 +1445,7 @@ def test_sql_join_using_f_string() -> None:
mod = ast.parse(code)
v.visit(mod)
assert not v.defs
- assert v.refs == set(["mo", "df1", "df2", "col"])
+ assert v.refs == {"mo", "df1", "df2", "col"}
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
@@ -1807,11 +1673,11 @@ def test_class_with_class_var_in_method_default() -> None:
v.visit(mod)
# K should be a def
- assert v.defs == set(["K"])
+ assert v.defs == {"K"}
# A should NOT be a ref (it's defined in class scope), but int is (type annotation)
- assert v.refs == set(["int"])
+ assert v.refs == {"int"}
# K should have unbounded_refs only for int, not A
- assert v.variable_data["K"][0].unbounded_refs == set(["int"])
+ assert v.variable_data["K"][0].unbounded_refs == {"int"}
def test_class_with_class_var_referencing_another() -> None:
@@ -1830,11 +1696,11 @@ def test_class_with_class_var_referencing_another() -> None:
v.visit(mod)
# K should be a def
- assert v.defs == set(["K"])
+ assert v.defs == {"K"}
# A should NOT be a ref (it's defined in class scope), but int is (type annotation)
- assert v.refs == set(["int"])
+ assert v.refs == {"int"}
# K should have unbounded_refs only for int, not A
- assert v.variable_data["K"][0].unbounded_refs == set(["int"])
+ assert v.variable_data["K"][0].unbounded_refs == {"int"}
def test_class_with_typealias_annotation() -> None:
@@ -1853,14 +1719,15 @@ def test_class_with_typealias_annotation() -> None:
v.visit(mod)
# EmbeddedTypeAlias should be a def
- assert v.defs == set(["EmbeddedTypeAlias"])
+ assert v.defs == {"EmbeddedTypeAlias"}
# MyEmbeddedTypeAlias should NOT be a ref (it's defined in class scope)
# TypeAlias and int are refs (type annotations)
- assert v.refs == set(["TypeAlias", "int"])
+ assert v.refs == {"TypeAlias", "int"}
# Should have unbounded_refs only for TypeAlias and int, not MyEmbeddedTypeAlias
- assert v.variable_data["EmbeddedTypeAlias"][0].unbounded_refs == set(
- ["TypeAlias", "int"]
- )
+ assert v.variable_data["EmbeddedTypeAlias"][0].unbounded_refs == {
+ "TypeAlias",
+ "int",
+ }
@pytest.mark.skipif("sys.version_info < (3, 12)")
@@ -1880,12 +1747,12 @@ def test_class_with_type_statement() -> None:
v.visit(mod)
# EmbeddedType should be a def
- assert v.defs == set(["EmbeddedType"])
+ assert v.defs == {"EmbeddedType"}
# MyEmbeddedType should NOT be a ref (it's defined in class scope via type statement)
# int is a ref (used in type statement)
- assert v.refs == set(["int"])
+ assert v.refs == {"int"}
# Should have unbounded_refs only for int, not MyEmbeddedType
- assert v.variable_data["EmbeddedType"][0].unbounded_refs == set(["int"])
+ assert v.variable_data["EmbeddedType"][0].unbounded_refs == {"int"}
def test_class_with_external_var_in_method_default() -> None:
@@ -1903,11 +1770,11 @@ def test_class_with_external_var_in_method_default() -> None:
v.visit(mod)
# K should be a def
- assert v.defs == set(["K"])
+ assert v.defs == {"K"}
# EXTERNAL should be a ref (not defined in class)
- assert v.refs == set(["int", "EXTERNAL"])
+ assert v.refs == {"int", "EXTERNAL"}
# K should have unbounded_refs for EXTERNAL, but not A
- assert v.variable_data["K"][0].unbounded_refs == set(["int", "EXTERNAL"])
+ assert v.variable_data["K"][0].unbounded_refs == {"int", "EXTERNAL"}
def test_class_with_external_var_in_class_var() -> None:
@@ -1926,11 +1793,11 @@ def test_class_with_external_var_in_class_var() -> None:
v.visit(mod)
# K should be a def
- assert v.defs == set(["K"])
+ assert v.defs == {"K"}
# EXTERNAL should be a ref (not defined in class)
- assert v.refs == set(["int", "EXTERNAL"])
+ assert v.refs == {"int", "EXTERNAL"}
# K should have unbounded_refs for EXTERNAL, but not A
- assert v.variable_data["K"][0].unbounded_refs == set(["int", "EXTERNAL"])
+ assert v.variable_data["K"][0].unbounded_refs == {"int", "EXTERNAL"}
def test_class_with_external_type_in_typealias() -> None:
@@ -1949,13 +1816,14 @@ def test_class_with_external_type_in_typealias() -> None:
v.visit(mod)
# K should be a def
- assert v.defs == set(["K"])
+ assert v.defs == {"K"}
# ExternalType and TypeAlias should be refs (not defined in class)
- assert v.refs == set(["TypeAlias", "ExternalType"])
+ assert v.refs == {"TypeAlias", "ExternalType"}
# K should have unbounded_refs for both TypeAlias and ExternalType, but not MyType
- assert v.variable_data["K"][0].unbounded_refs == set(
- ["TypeAlias", "ExternalType"]
- )
+ assert v.variable_data["K"][0].unbounded_refs == {
+ "TypeAlias",
+ "ExternalType",
+ }
@pytest.mark.skipif("sys.version_info < (3, 12)")
@@ -1975,11 +1843,11 @@ def test_class_with_external_type_in_type_statement() -> None:
v.visit(mod)
# K should be a def
- assert v.defs == set(["K"])
+ assert v.defs == {"K"}
# ExternalType should be a ref (not defined in class)
- assert v.refs == set(["ExternalType"])
+ assert v.refs == {"ExternalType"}
# K should have unbounded_refs for ExternalType, but not MyType
- assert v.variable_data["K"][0].unbounded_refs == set(["ExternalType"])
+ assert v.variable_data["K"][0].unbounded_refs == {"ExternalType"}
def test_class_with_method_using_external_var() -> None:
@@ -1996,15 +1864,13 @@ def test_class_with_method_using_external_var() -> None:
v.visit(mod)
# K should be a def
- assert v.defs == set(["K"])
+ assert v.defs == {"K"}
# EXTERNAL_VAR should be a ref (used in method body)
- assert v.refs == set(["EXTERNAL_VAR", "int"])
+ assert v.refs == {"EXTERNAL_VAR", "int"}
# K should have EXTERNAL_VAR in required_refs (method needs it)
- assert v.variable_data["K"][0].required_refs == set(
- ["EXTERNAL_VAR", "int"]
- )
+ assert v.variable_data["K"][0].required_refs == {"EXTERNAL_VAR", "int"}
# But not in unbounded_refs (it's in method body, not signature)
- assert v.variable_data["K"][0].unbounded_refs == set(["int"])
+ assert v.variable_data["K"][0].unbounded_refs == {"int"}
def test_class_with_forward_reference_to_method() -> None:
@@ -2022,7 +1888,7 @@ def test_class_with_forward_reference_to_method() -> None:
v.visit(mod)
# A should be a def
- assert v.defs == set(["A"])
+ assert v.defs == {"A"}
# No external refs - method is defined within class scope
assert v.refs == set()
# A should have no unbounded refs (forward reference is valid)
@@ -2044,8 +1910,8 @@ def test_class_with_backward_reference_to_method() -> None:
v.visit(mod)
# B should be a def
- assert v.defs == set(["B"])
+ assert v.defs == {"B"}
# method is referenced before it's defined, so it's an external ref
- assert v.refs == set(["method"])
+ assert v.refs == {"method"}
# B should have method in unbounded refs (backward reference is invalid)
- assert v.variable_data["B"][0].unbounded_refs == set(["method"])
+ assert v.variable_data["B"][0].unbounded_refs == {"method"}
diff --git a/tests/_data/mocks.py b/tests/_data/mocks.py
index 3f2ad1e9b8..42afb4fc29 100644
--- a/tests/_data/mocks.py
+++ b/tests/_data/mocks.py
@@ -30,9 +30,7 @@ def create_dataframes(
def should_include(lib: DFType) -> bool:
if include is not None and lib not in include:
return False
- if exclude is not None and lib in exclude:
- return False
- return True
+ return not (exclude is not None and lib in exclude)
if DependencyManager.pandas.has() and should_include("pandas"):
import pandas as pd
diff --git a/tests/_lint/test_validate_graph.py b/tests/_lint/test_validate_graph.py
index 05ef8911e4..8251f48044 100644
--- a/tests/_lint/test_validate_graph.py
+++ b/tests/_lint/test_validate_graph.py
@@ -22,13 +22,13 @@ def test_multiple_definition_error() -> None:
graph.register_cell("0", parse_cell("x = 0"))
graph.register_cell("1", parse_cell("x = 1"))
errors = check_for_errors(graph)
- assert set(errors.keys()) == set(["0", "1"])
+ assert set(errors.keys()) == {"0", "1"}
assert errors["0"] == (MultipleDefinitionError(name="x", cells=("1",)),)
assert errors["1"] == (MultipleDefinitionError(name="x", cells=("0",)),)
graph.register_cell("2", parse_cell("x = 1"))
errors = check_for_errors(graph)
- assert set(errors.keys()) == set(["0", "1", "2"])
+ assert set(errors.keys()) == {"0", "1", "2"}
assert errors["0"] == (
MultipleDefinitionError(name="x", cells=("1", "2")),
)
@@ -46,7 +46,7 @@ def test_overlapping_multiple_definition_errors() -> None:
graph.register_cell("1", parse_cell("x, y = 1, 2"))
graph.register_cell("2", parse_cell("y, z = 3, 4"))
errors = check_for_errors(graph)
- assert set(errors.keys()) == set(["0", "1", "2"])
+ assert set(errors.keys()) == {"0", "1", "2"}
assert errors["0"] == (MultipleDefinitionError(name="x", cells=("1",)),)
assert errors["1"] == (
MultipleDefinitionError(name="x", cells=("0",)),
@@ -74,7 +74,7 @@ def test_two_node_cycle() -> None:
graph.register_cell("0", parse_cell("x = y"))
graph.register_cell("1", parse_cell("y = x"))
errors = check_for_errors(graph)
- assert set(errors.keys()) == set(["0", "1"])
+ assert set(errors.keys()) == {"0", "1"}
# Edge ordering in returned error is not deterministic, so we list both
# possible cycles
expected_cycle = [
@@ -93,7 +93,7 @@ def test_three_node_cycle() -> None:
graph.register_cell("1", parse_cell("y = z"))
graph.register_cell("2", parse_cell("z = x"))
errors = check_for_errors(graph)
- assert set(errors.keys()) == set(["0", "1", "2"])
+ assert set(errors.keys()) == {"0", "1", "2"}
for t in errors.values():
assert len(t) == 1
assert isinstance(t[0], CycleError)
@@ -109,7 +109,7 @@ def test_cycle_and_multiple_def() -> None:
graph.register_cell("0", parse_cell("x, z = y, 0"))
graph.register_cell("1", parse_cell("y, z = x, 0"))
errors = check_for_errors(graph)
- assert set(errors.keys()) == set(["0", "1"])
+ assert set(errors.keys()) == {"0", "1"}
for cell, t in errors.items():
assert len(t) == 2
assert isinstance(t[0], CycleError) or isinstance(t[1], CycleError)
@@ -157,7 +157,7 @@ def test_setup_has_refs() -> None:
graph.register_cell(SETUP_CELL_NAME, parse_cell("z = y"))
graph.register_cell("0", parse_cell("y = 1"))
errors = check_for_errors(graph)
- assert set(errors.keys()) == set([SETUP_CELL_NAME])
+ assert set(errors.keys()) == {SETUP_CELL_NAME}
for t in errors.values():
assert len(t) == 1
assert isinstance(t[0], SetupRootError)
diff --git a/tests/_messaging/test_variables.py b/tests/_messaging/test_variables.py
index 9e00850ec9..218f8f0afe 100644
--- a/tests/_messaging/test_variables.py
+++ b/tests/_messaging/test_variables.py
@@ -76,7 +76,7 @@ def test_get_variable_preview() -> None:
assert get_variable_preview([]) == "[]"
assert get_variable_preview({}) == "{}"
assert get_variable_preview(set()) == "{}"
- assert get_variable_preview(tuple()) == "()"
+ assert get_variable_preview(()) == "()"
# Test single-element containers
assert get_variable_preview([1]) == "[1]"
diff --git a/tests/_output/formatters/test_ibis_formatters.py b/tests/_output/formatters/test_ibis_formatters.py
index 126f449c2e..8c4e994b04 100644
--- a/tests/_output/formatters/test_ibis_formatters.py
+++ b/tests/_output/formatters/test_ibis_formatters.py
@@ -126,10 +126,10 @@ def test_ibis_unbound_expressions() -> None:
# Create unbound tables like in smoke tests
t1 = ibis.table(
- dict(value1="float", key1="string", key2="string"), name="table1"
+ {"value1": "float", "key1": "string", "key2": "string"}, name="table1"
)
t2 = ibis.table(
- dict(value2="float", key3="string", key4="string"), name="table2"
+ {"value2": "float", "key3": "string", "key4": "string"}, name="table2"
)
joined = t1.left_join(t2, t1.key1 == t2.key3)
diff --git a/tests/_output/formatters/test_structures.py b/tests/_output/formatters/test_structures.py
index bb49c76f7d..807503e5a9 100644
--- a/tests/_output/formatters/test_structures.py
+++ b/tests/_output/formatters/test_structures.py
@@ -84,7 +84,7 @@ async def test_matplotlib_boxplot_dict_special_case(
formatter = executing_kernel.globals["formatter"]
boxplot_result = executing_kernel.globals["boxplot_result"]
assert formatter is not None
- mimetype, data = formatter(boxplot_result)
+ mimetype, _data = formatter(boxplot_result)
# Should be a single image, not JSON with multiple formatted artists
assert (
mimetype.startswith("image")
@@ -119,7 +119,7 @@ async def test_matplotlib_violinplot_dict_special_case(
formatter = executing_kernel.globals["formatter"]
violinplot_result = executing_kernel.globals["violinplot_result"]
assert formatter is not None
- mimetype, data = formatter(violinplot_result)
+ mimetype, _data = formatter(violinplot_result)
# Should be a single image, not JSON with multiple formatted artists
assert (
mimetype.startswith("image")
@@ -574,7 +574,7 @@ def test_function_like_objects_fallback_on_exception() -> None:
def test_is_structures_formatter() -> None:
- assert is_structures_formatter(get_formatter(tuple()))
+ assert is_structures_formatter(get_formatter(()))
assert is_structures_formatter(get_formatter([]))
assert is_structures_formatter(get_formatter({1: 2}))
diff --git a/tests/_output/formatters/test_sympy.py b/tests/_output/formatters/test_sympy.py
index 88d2e1f4ab..b696e48857 100644
--- a/tests/_output/formatters/test_sympy.py
+++ b/tests/_output/formatters/test_sympy.py
@@ -56,7 +56,7 @@ def test_sympy_formatters_power() -> None:
from sympy import symbols
- x, y, z = symbols("x y z")
+ x, _y, _z = symbols("x y z")
x_squared = x**2
# x^2
@@ -109,7 +109,7 @@ def test_sympy_formatters_Integral() -> None:
from sympy import Integral, sqrt, symbols
- x, y, z = symbols("x y z")
+ x, _y, _z = symbols("x y z")
out_exp = Integral(sqrt(1 / x), x)
# symbolic integral
diff --git a/tests/_output/test_try_format.py b/tests/_output/test_try_format.py
index f5c67557a2..91226943d1 100644
--- a/tests/_output/test_try_format.py
+++ b/tests/_output/test_try_format.py
@@ -97,10 +97,7 @@ def test_primitives():
assert try_format(1.0 + 1.0j).data == "<pre class='text-xs'>(1+1j)</pre>"
assert try_format([1, 2, 3]).data == "[1, 2, 3]"
assert try_format({"a": 1, "b": 2}).data == '{"a": 1, "b": 2}'
- assert (
- try_format(set([1, 2, 3])).data
- == "<pre class='text-xs'>{1, 2, 3}</pre>"
- )
+ assert try_format({1, 2, 3}).data == "<pre class='text-xs'>{1, 2, 3}</pre>"
def test_none_value():
diff --git a/tests/_plugins/core/test_json_encoder.py b/tests/_plugins/core/test_json_encoder.py
index c3da011445..62b14fa627 100644
--- a/tests/_plugins/core/test_json_encoder.py
+++ b/tests/_plugins/core/test_json_encoder.py
@@ -260,13 +260,13 @@ def test_memoryview_encoding() -> None:
def test_set_encoding() -> None:
- set_obj = set(["a", "b"])
+ set_obj = {"a", "b"}
encoded = encode_json_str(set_obj)
assert encoded == '["a","b"]' or encoded == '["b","a"]'
empty_set = set()
encoded_empty = encode_json_str(empty_set)
assert encoded_empty == "[]"
- number_set = set([1, 2])
+ number_set = {1, 2}
encoded_number = encode_json_str(number_set)
assert encoded_number == "[1,2]" or encoded_number == "[2,1]"
@@ -769,7 +769,7 @@ def test_superjson_with_bytes() -> None:
([1, 2, 3], "[1,2,3]"),
({"a": 1, "b": 2}, '{"a":1,"b":2}'),
((), "[]"),
- (set([1, 2, 3]), "[1,2,3]"),
+ ({1, 2, 3}, "[1,2,3]"),
(frozenset([1, 2, 3]), "[1,2,3]"),
(range(10), "[0,1,2,3,4,5,6,7,8,9]"),
(datetime.datetime(2023, 1, 1, 12, 30, 45), '"2023-01-01 12:30:45"'),
diff --git a/tests/_plugins/stateless/test_audio.py b/tests/_plugins/stateless/test_audio.py
index bc70fd8afb..fd07885530 100644
--- a/tests/_plugins/stateless/test_audio.py
+++ b/tests/_plugins/stateless/test_audio.py
@@ -39,7 +39,7 @@ async def test_audio_filename(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".wav")
@@ -57,7 +57,7 @@ async def test_audio_bytes_io(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".wav")
@@ -73,7 +73,7 @@ async def test_audio_bytes(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".wav")
@@ -92,7 +92,7 @@ async def test_audio_numpy_mono(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".wav")
@@ -113,7 +113,7 @@ async def test_audio_numpy_normalize(
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".wav")
diff --git a/tests/_plugins/stateless/test_image.py b/tests/_plugins/stateless/test_image.py
index 9506f0b287..826354bb97 100644
--- a/tests/_plugins/stateless/test_image.py
+++ b/tests/_plugins/stateless/test_image.py
@@ -44,7 +44,7 @@ async def test_image_filename(k: Kernel, exec_req: ExecReqProvider) -> None:
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
@@ -67,7 +67,7 @@ async def test_image_path(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
@@ -85,7 +85,7 @@ async def test_image_bytes_io(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
@@ -103,7 +103,7 @@ async def test_image_bytes(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
@@ -135,7 +135,7 @@ async def test_image_array(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
@@ -154,7 +154,7 @@ async def test_image_numpy(k: Kernel, exec_req: ExecReqProvider) -> None:
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
diff --git a/tests/_plugins/stateless/test_image_compare.py b/tests/_plugins/stateless/test_image_compare.py
index 085062b93b..6f045af1d3 100644
--- a/tests/_plugins/stateless/test_image_compare.py
+++ b/tests/_plugins/stateless/test_image_compare.py
@@ -114,7 +114,7 @@ async def test_image_compare_filename(
)
assert len(get_context().virtual_file_registry.registry) == 2
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
@@ -149,7 +149,7 @@ async def test_image_compare_path(
)
assert len(get_context().virtual_file_registry.registry) == 2
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
@@ -172,7 +172,7 @@ async def test_image_compare_bytes_io(
)
assert len(get_context().virtual_file_registry.registry) == 2
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
@@ -243,7 +243,7 @@ async def test_image_compare_array(
)
assert len(get_context().virtual_file_registry.registry) == 2
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
@@ -267,7 +267,7 @@ async def test_image_compare_numpy(
)
assert len(get_context().virtual_file_registry.registry) == 2
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".png")
diff --git a/tests/_plugins/ui/_core/test_registry.py b/tests/_plugins/ui/_core/test_registry.py
index fb6bb16742..e1491927aa 100644
--- a/tests/_plugins/ui/_core/test_registry.py
+++ b/tests/_plugins/ui/_core/test_registry.py
@@ -148,7 +148,7 @@ async def test_lens_not_bound(k: Kernel, exec_req: ExecReqProvider) -> None:
array = k.globals["array"]
registry = get_context().ui_element_registry
assert not registry.bound_names(array[0]._id)
- assert registry.bound_names(array._id) == set(["array"])
+ assert registry.bound_names(array._id) == {"array"}
async def test_parent_bound_to_view(
@@ -167,7 +167,7 @@ async def test_parent_bound_to_view(
)
array = k.globals["array"]
registry = get_context().ui_element_registry
- assert registry.bound_names(array._id) == set(["array", "child"])
+ assert registry.bound_names(array._id) == {"array", "child"}
async def test_dont_delete_element_with_wrong_python_id(
diff --git a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
index 480d7f7175..9634f00fa8 100644
--- a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
+++ b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
@@ -159,7 +159,7 @@ def test_to_marimo_inline_csv_large_dataset(df: IntoDataFrame):
# Verify the content of the inline CSV
base64_data = result["url"].split(",")[1]
decoded_data = base64.b64decode(base64_data).decode("utf-8")
- assert decoded_data.startswith('"A","B"') or decoded_data.startswith("A,B")
+ assert decoded_data.startswith(('"A","B"', "A,B"))
lines = decoded_data.strip().split("\n")
assert len(lines) == 10001 # header + 10000 data rows
diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
index 56abf7a4e1..2f459dc111 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
@@ -56,9 +56,7 @@ def df_length(df: IntoDataFrame | IntoLazyFrame) -> int:
def is_not_narwhals_dataframe(df: IntoDataFrame | IntoLazyFrame) -> bool:
- if is_narwhals_lazyframe(df) or is_narwhals_dataframe(df):
- return False
- return True
+ return not (is_narwhals_lazyframe(df) or is_narwhals_dataframe(df))
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index 5af0ce8d71..eab766605a 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -94,7 +94,7 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):
"category": pl.Series(
["cat", "dog", "mouse"], dtype=pl.Categorical
),
- "set": [set([1, 2]), set([3, 4]), set([5, 6])],
+ "set": [{1, 2}, {3, 4}, {5, 6}],
"imaginary": [1 + 2j, 3 + 4j, 5 + 6j],
"time": [
datetime.time(12, 30),
@@ -253,7 +253,7 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):
"D": [True, False, True],
"E": [1 + 2j, 3 + 4j, 5 + 6j],
"F": [None, None, None],
- "G": [set([1, 2]), set([3, 4]), set([5, 6])],
+ "G": [{1, 2}, {3, 4}, {5, 6}],
"H": [
datetime.datetime(2021, 1, 1),
datetime.datetime(2021, 1, 2),
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index a11412b79e..b183a6d6b5 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -181,7 +181,7 @@ class TestPandasTableManager(unittest.TestCase):
),
"nulls": pd.Series([None, "data", None]),
"category": pd.Categorical(["cat", "dog", "mouse"]),
- "set": [set([1, 2]), set([3, 4]), set([5, 6])],
+ "set": [{1, 2}, {3, 4}, {5, 6}],
"imaginary": [1 + 2j, 3 + 4j, 5 + 6j],
"time": [
datetime.time(12, 30),
@@ -722,7 +722,7 @@ class TestPandasTableManager(unittest.TestCase):
"D": [True, False, True],
"E": [1 + 2j, 3 + 4j, 5 + 6j],
"F": [None, None, None],
- "G": [set([1, 2]), set([3, 4]), set([5, 6])],
+ "G": [{1, 2}, {3, 4}, {5, 6}],
"H": [
pd.Timestamp("2021-01-01"),
pd.Timestamp("2021-01-02"),
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index 01a5dd010f..5e771dcfb2 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -90,7 +90,7 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
"category": pl.Series(
["cat", "dog", "mouse"], dtype=pl.Categorical
),
- "set": [set([1, 2]), set([3, 4]), set([5, 6])],
+ "set": [{1, 2}, {3, 4}, {5, 6}],
"imaginary": [1 + 2j, 3 + 4j, 5 + 6j],
"time": [
datetime.time(12, 30),
@@ -305,7 +305,7 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
"D": [True, False, True],
"E": [1 + 2j, 3 + 4j, 5 + 6j],
"F": [None, None, None],
- "G": [set([1, 2]), set([3, 4]), set([5, 6])],
+ "G": [{1, 2}, {3, 4}, {5, 6}],
"H": [
datetime.datetime(2021, 1, 1),
datetime.datetime(2021, 1, 2),
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index f819493101..22ff32f6a0 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -119,7 +119,7 @@ def test_normalize_data(executing_kernel: Kernel) -> None:
assert str(e.value) == "data must be a list or tuple or a dict of lists."
# Test with invalid data structure
- data3: Any = [set([1, 2, 3])]
+ data3: Any = [{1, 2, 3}]
with pytest.raises(ValueError) as e:
_normalize_data(data3)
assert (
diff --git a/tests/_pyodide/test_bootstrap.py b/tests/_pyodide/test_bootstrap.py
index 645bbf6617..d547691d90 100644
--- a/tests/_pyodide/test_bootstrap.py
+++ b/tests/_pyodide/test_bootstrap.py
@@ -186,7 +186,7 @@ async def test_message_callback_format(
"""Test that message_callback receives properly formatted JSON."""
received_messages: list[str] = []
- session, _ = create_session(
+ _session, _ = create_session(
filename=str(mock_app_file),
query_params={},
message_callback=lambda text: received_messages.append(text),
diff --git a/tests/_runtime/packages/test_module_registry.py b/tests/_runtime/packages/test_module_registry.py
index ca33f75071..7e4c359fef 100644
--- a/tests/_runtime/packages/test_module_registry.py
+++ b/tests/_runtime/packages/test_module_registry.py
@@ -32,4 +32,4 @@ def test_missing_modules() -> None:
graph.register_cell(
"1", parse_cell("import time; import super_fake_package")
)
- assert mgr.missing_modules() == set(["does", "super_fake_package"])
+ assert mgr.missing_modules() == {"does", "super_fake_package"}
diff --git a/tests/_runtime/reload/test_autoreload.py b/tests/_runtime/reload/test_autoreload.py
index f862c21c89..eabb942513 100644
--- a/tests/_runtime/reload/test_autoreload.py
+++ b/tests/_runtime/reload/test_autoreload.py
@@ -124,15 +124,15 @@ class TestModuleDependencyFinder:
from tests._runtime.reload.reload_data import a, b, c, d
finder = ModuleDependencyFinder()
- a_deps = set(list(finder.find_dependencies(a, excludes=set()).keys()))
- b_deps = set(list(finder.find_dependencies(b, excludes=set()).keys()))
- c_deps = set(list(finder.find_dependencies(c, excludes=set()).keys()))
- d_deps = set(list(finder.find_dependencies(d, excludes=set()).keys()))
-
- assert a_deps == set(["__main__", "reload_data", "reload_data.c"])
- assert b_deps == set(["__main__", "reload_data", "reload_data.d"])
- assert c_deps == set(["__main__"])
- assert d_deps == set(["__main__"])
+ a_deps = set(finder.find_dependencies(a, excludes=set()).keys())
+ b_deps = set(finder.find_dependencies(b, excludes=set()).keys())
+ c_deps = set(finder.find_dependencies(c, excludes=set()).keys())
+ d_deps = set(finder.find_dependencies(d, excludes=set()).keys())
+
+ assert a_deps == {"__main__", "reload_data", "reload_data.c"}
+ assert b_deps == {"__main__", "reload_data", "reload_data.d"}
+ assert c_deps == {"__main__"}
+ assert d_deps == {"__main__"}
def test_dependencies_cached(self):
from tests._runtime.reload.reload_data import a
diff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.py
index 4180ed9ae3..cb41f541b9 100644
--- a/tests/_runtime/test_complete.py
+++ b/tests/_runtime/test_complete.py
@@ -684,7 +684,7 @@ mixed_keys = {"static_key": "foo", str(random.randint(0, 10)): "bar"}
# from source code in variable `other_cells_code`
expected_keys = ["foo", "bar", "baz"]
else:
- RuntimeError(
+ raise RuntimeError(
f"Make sure you defined `expected_keys` for `{object_name}`"
" Currently, the test is improperly defined."
)
diff --git a/tests/_runtime/test_control_flow.py b/tests/_runtime/test_control_flow.py
index 620b2b06d5..c9f4e7260a 100644
--- a/tests/_runtime/test_control_flow.py
+++ b/tests/_runtime/test_control_flow.py
@@ -67,7 +67,7 @@ async def test_stop_output(execution_kernel: Kernel) -> None:
)
# Run the cell through the runner to get the output
runner = cell_runner.Runner(
- set(["0"]),
+ {"0"},
graph=k.graph,
glbls=k.globals,
debugger=k.debugger,
diff --git a/tests/_runtime/test_dataflow.py b/tests/_runtime/test_dataflow.py
index d9ef92071f..e859e9e6ba 100644
--- a/tests/_runtime/test_dataflow.py
+++ b/tests/_runtime/test_dataflow.py
@@ -42,10 +42,10 @@ def test_graph_two_chains() -> None:
# 0 --> 1 --> 2, 0 --> 2
assert graph.cells == {"0": first_cell, "1": second_cell, "2": third_cell}
- assert graph.parents == {"0": set(), "1": set(["0"]), "2": set(["0", "1"])}
+ assert graph.parents == {"0": set(), "1": {"0"}, "2": {"0", "1"}}
assert graph.children == {
- "0": set(["1", "2"]),
- "1": set(["2"]),
+ "0": {"1", "2"},
+ "1": {"2"},
"2": set(),
}
@@ -78,11 +78,9 @@ def test_graph_closure() -> None:
# 0 --> 1
assert graph.cells == {"0": first_cell, "1": second_cell}
- assert graph.parents == {"0": set(), "1": set(["0"])}
- assert graph.children == {"0": set(["1"]), "1": set()}
- assert dataflow.transitive_closure(graph, cell_ids=set(["0"])) == set(
- ["0", "1"]
- )
+ assert graph.parents == {"0": set(), "1": {"0"}}
+ assert graph.children == {"0": {"1"}, "1": set()}
+ assert dataflow.transitive_closure(graph, cell_ids={"0"}) == {"0", "1"}
def test_graph_closure_predicate() -> None:
@@ -94,7 +92,7 @@ def test_graph_closure_predicate() -> None:
code = "def foo():\n return x"
second_cell = parse_cell(code)
graph.register_cell("1", second_cell)
- graph.set_stale(set(["1"]))
+ graph.set_stale({"1"})
code = "x"
third_cell = parse_cell(code)
@@ -102,12 +100,12 @@ def test_graph_closure_predicate() -> None:
# 0 --> 1
assert graph.cells == {"0": first_cell, "1": second_cell, "2": third_cell}
- assert graph.parents == {"0": set(), "1": set(["0"]), "2": set(["0"])}
- assert graph.children == {"0": set(["1", "2"]), "1": set(), "2": set()}
+ assert graph.parents == {"0": set(), "1": {"0"}, "2": {"0"}}
+ assert graph.children == {"0": {"1", "2"}, "1": set(), "2": set()}
assert dataflow.transitive_closure(
- graph, cell_ids=set(["0"]), predicate=lambda cell: not cell.stale
- ) == set(["0", "2"])
+ graph, cell_ids={"0"}, predicate=lambda cell: not cell.stale
+ ) == {"0", "2"}
def test_graph_closure_inclusive() -> None:
@@ -126,33 +124,33 @@ def test_graph_closure_inclusive() -> None:
# 0 --> 1 --> 2
assert graph.cells == {"0": first_cell, "1": second_cell, "2": third_cell}
- assert graph.parents == {"0": set(), "1": set(["0"]), "2": set(["1"])}
- assert graph.children == {"0": set(["1"]), "1": set(["2"]), "2": set()}
+ assert graph.parents == {"0": set(), "1": {"0"}, "2": {"1"}}
+ assert graph.children == {"0": {"1"}, "1": {"2"}, "2": set()}
# Test inclusive=True (default)
- assert dataflow.transitive_closure(graph, cell_ids=set(["1"])) == set(
- ["1", "2"]
- )
+ assert dataflow.transitive_closure(graph, cell_ids={"1"}) == {"1", "2"}
# Test inclusive=False
assert dataflow.transitive_closure(
- graph, cell_ids=set(["1"]), inclusive=False
- ) == set(["2"])
+ graph, cell_ids={"1"}, inclusive=False
+ ) == {"2"}
# Test with multiple starting cells
- assert dataflow.transitive_closure(graph, cell_ids=set(["0", "1"])) == set(
- ["0", "1", "2"]
- )
+ assert dataflow.transitive_closure(graph, cell_ids={"0", "1"}) == {
+ "0",
+ "1",
+ "2",
+ }
# Test ancestors (children=False)
assert dataflow.transitive_closure(
- graph, cell_ids=set(["2"]), children=False
- ) == set(["0", "1", "2"])
+ graph, cell_ids={"2"}, children=False
+ ) == {"0", "1", "2"}
# Test ancestors with inclusive=False
assert dataflow.transitive_closure(
- graph, cell_ids=set(["2"]), children=False, inclusive=False
- ) == set(["0", "1"])
+ graph, cell_ids={"2"}, children=False, inclusive=False
+ ) == {"0", "1"}
def test_graph_closure_predicate_with_inclusive_false() -> None:
@@ -170,22 +168,22 @@ def test_graph_closure_predicate_with_inclusive_false() -> None:
graph.register_cell("2", third_cell)
result = dataflow.transitive_closure(
- graph, cell_ids=set(["0"]), inclusive=False
+ graph, cell_ids={"0"}, inclusive=False
)
- assert result == set(["1", "2"])
+ assert result == {"1", "2"}
result = dataflow.transitive_closure(
- graph, cell_ids=set(["1"]), inclusive=False
+ graph, cell_ids={"1"}, inclusive=False
)
- assert result == set(["2"])
+ assert result == {"2"}
result = dataflow.transitive_closure(
- graph, cell_ids=set(["0", "1"]), inclusive=False
+ graph, cell_ids={"0", "1"}, inclusive=False
)
- assert result == set(["2"])
+ assert result == {"2"}
result = dataflow.transitive_closure(
- graph, cell_ids=set(["0", "1", "2"]), inclusive=False
+ graph, cell_ids={"0", "1", "2"}, inclusive=False
)
assert result == set()
@@ -202,13 +200,9 @@ def test_graph_closure_empty() -> None:
graph.register_cell("0", first_cell)
# Test with single cell, no connections
- assert dataflow.transitive_closure(graph, cell_ids=set(["0"])) == set(
- ["0"]
- )
+ assert dataflow.transitive_closure(graph, cell_ids={"0"}) == {"0"}
assert (
- dataflow.transitive_closure(
- graph, cell_ids=set(["0"]), inclusive=False
- )
+ dataflow.transitive_closure(graph, cell_ids={"0"}, inclusive=False)
== set()
)
@@ -252,8 +246,8 @@ def test_set_stale() -> None:
assert not graph.get_stale()
# 0 and its children are stale
- graph.set_stale(set(["0"]))
- assert graph.get_stale() == set(["0", "1", "2"])
+ graph.set_stale({"0"})
+ assert graph.get_stale() == {"0", "1", "2"}
graph.cells["0"].set_stale(stale=False)
graph.cells["1"].set_stale(stale=False)
@@ -281,8 +275,8 @@ def test_ancestors() -> None:
graph.register_cell("3", fourth_cell)
assert not graph.ancestors("0")
- assert graph.ancestors("1") == set(["0"])
- assert graph.ancestors("2") == set(["0", "1"])
+ assert graph.ancestors("1") == {"0"}
+ assert graph.ancestors("2") == {"0", "1"}
assert not graph.ancestors("3")
@@ -305,8 +299,8 @@ def test_descendants() -> None:
fourth_cell = parse_cell(code)
graph.register_cell("3", fourth_cell)
- assert graph.descendants("0") == set(["1", "2"])
- assert graph.descendants("1") == set(["2"])
+ assert graph.descendants("0") == {"1", "2"}
+ assert graph.descendants("1") == {"2"}
assert not graph.descendants("2")
assert not graph.ancestors("3")
@@ -318,18 +312,18 @@ def test_register_with_stale_ancestor() -> None:
code = "x = 0"
first_cell = parse_cell(code)
graph.register_cell("0", first_cell)
- graph.set_stale(set(["0"]))
+ graph.set_stale({"0"})
code = "y = x"
second_cell = parse_cell(code)
graph.register_cell("1", second_cell)
- assert graph.get_stale() == set(["0", "1"])
+ assert graph.get_stale() == {"0", "1"}
# add a third cell not related to the others
code = "a = 0"
third_cell = parse_cell(code)
graph.register_cell("3", third_cell)
- assert graph.get_stale() == set(["0", "1"])
+ assert graph.get_stale() == {"0", "1"}
def test_topological_sort_single_node() -> None:
@@ -509,8 +503,8 @@ class TestSQL:
graph.register_cell("1", second_cell)
assert graph.cells == {"0": first_cell, "1": second_cell}
- assert graph.parents == {"0": set(), "1": set(["0"])}
- assert graph.children == {"0": set(["1"]), "1": set()}
+ assert graph.parents == {"0": set(), "1": {"0"}}
+ assert graph.children == {"0": {"1"}, "1": set()}
def test_sql_tree_with_declared_df(self) -> None:
graph = dataflow.DirectedGraph()
@@ -527,8 +521,8 @@ class TestSQL:
graph.register_cell("1", second_cell)
assert graph.cells == {"0": first_cell, "1": second_cell}
- assert graph.parents == {"0": set(), "1": set(["0"])}
- assert graph.children == {"0": set(["1"]), "1": set()}
+ assert graph.parents == {"0": set(), "1": {"0"}}
+ assert graph.children == {"0": {"1"}, "1": set()}
code = 'mo.sql("SELECT * from df")'
third_cell = parse_cell(code)
@@ -539,8 +533,8 @@ class TestSQL:
"1": second_cell,
"2": third_cell,
}
- assert graph.parents == {"0": set(), "1": set(["0"]), "2": set(["0"])}
- assert graph.children == {"0": set(["1", "2"]), "1": set(), "2": set()}
+ assert graph.parents == {"0": set(), "1": {"0"}, "2": {"0"}}
+ assert graph.children == {"0": {"1", "2"}, "1": set(), "2": set()}
code = "df"
fourth_cell = parse_cell(code)
@@ -554,12 +548,12 @@ class TestSQL:
}
assert graph.parents == {
"0": set(),
- "1": set(["0"]),
- "2": set(["0"]),
- "3": set(["0"]),
+ "1": {"0"},
+ "2": {"0"},
+ "3": {"0"},
}
assert graph.children == {
- "0": set(["1", "2", "3"]),
+ "0": {"1", "2", "3"},
"1": set(),
"2": set(),
"3": set(),
@@ -644,12 +638,12 @@ class TestSQL:
"1": second_cell,
"2": third_cell,
}
- assert graph.parents == {"0": set(), "1": set([]), "2": set(["0"])}
- assert graph.children == {"0": set(["2"]), "1": set(), "2": set([])}
+ assert graph.parents == {"0": set(), "1": set(), "2": {"0"}}
+ assert graph.children == {"0": {"2"}, "1": set(), "2": set()}
assert second_cell.language == "python"
- assert graph.get_referring_cells("t1", language="sql") == set([])
- assert graph.get_referring_cells("df", language="python") == set(["2"])
+ assert graph.get_referring_cells("t1", language="sql") == set()
+ assert graph.get_referring_cells("df", language="python") == {"2"}
def test_python_to_sql_ref(self):
graph = dataflow.DirectedGraph()
@@ -667,10 +661,10 @@ class TestSQL:
"0": first_cell,
"1": second_cell,
}
- assert graph.parents == {"0": set(), "1": set(["0"])}
- assert graph.children == {"0": set(["1"]), "1": set([])}
+ assert graph.parents == {"0": set(), "1": {"0"}}
+ assert graph.children == {"0": {"1"}, "1": set()}
- assert graph.get_referring_cells("df", language="python") == set(["1"])
+ assert graph.get_referring_cells("df", language="python") == {"1"}
def test_sql_creation_and_select_from_same_cell(self):
graph = dataflow.DirectedGraph()
@@ -687,9 +681,9 @@ class TestSQL:
"1": second_cell,
}
- assert graph.parents == {"0": set(), "1": set(["0"])}
- assert graph.children == {"0": set(["1"]), "1": set([])}
- assert graph.get_referring_cells("df", language="python") == set(["1"])
+ assert graph.parents == {"0": set(), "1": {"0"}}
+ assert graph.children == {"0": {"1"}, "1": set()}
+ assert graph.get_referring_cells("df", language="python") == {"1"}
def test_get_referring_cells_sql_and_python(self) -> None:
"""Test the get_referring_cells method."""
@@ -709,7 +703,7 @@ class TestSQL:
graph.register_cell("1", second_cell)
# Second cell should be in the referring cells for x
- assert graph.get_referring_cells("x", language="python") == set(["1"])
+ assert graph.get_referring_cells("x", language="python") == {"1"}
# Third cell refers to x in SQL
code = "mo.sql('SELECT * FROM x')"
@@ -717,10 +711,8 @@ class TestSQL:
graph.register_cell("2", third_cell)
# Both cells should be in the referring cells for x
- assert graph.get_referring_cells("x", language="python") == set(
- ["1", "2"]
- )
- assert graph.get_referring_cells("x", language="sql") == set(["2"])
+ assert graph.get_referring_cells("x", language="python") == {"1", "2"}
+ assert graph.get_referring_cells("x", language="sql") == {"2"}
# Test language filter (Python vars can leak to SQL, but not vice versa)
code = "mo.sql('CREATE TABLE t1 (i INTEGER)')"
@@ -736,13 +728,11 @@ class TestSQL:
graph.register_cell("5", sixth_cell)
# cell "5"'s t1 cannot possibly be a SQL variable
- assert graph.get_referring_cells("t1", language="sql") == set(["4"])
+ assert graph.get_referring_cells("t1", language="sql") == {"4"}
# t1 could potentially be a Python variable, so it is included in the
# reference set; even if t1 were not defined anywhere, it would still
# return "5"
- assert graph.get_referring_cells("t1", language="python") == set(
- ["4", "5"]
- )
+ assert graph.get_referring_cells("t1", language="python") == {"4", "5"}
# Python cell "5" is not a child of SQL cell "3", even though 5
# refs "t1" and 3 defines SQL variable t1
@@ -791,12 +781,12 @@ class TestSQL:
"1": second_cell,
"2": third_cell,
}
- assert graph.parents == {"0": set(), "1": set(["0"]), "2": set([])}
- assert graph.children == {"0": set(["1"]), "1": set([]), "2": set([])}
+ assert graph.parents == {"0": set(), "1": {"0"}, "2": set()}
+ assert graph.children == {"0": {"1"}, "1": set(), "2": set()}
# cell 2 shouldn't count as a referring cell because it isn't a SQL
# cell
- assert graph.get_referring_cells("my_db", language="sql") == set(["1"])
+ assert graph.get_referring_cells("my_db", language="sql") == {"1"}
def test_disable_enable_cell() -> None:
@@ -843,7 +833,7 @@ def test_disable_enable_cell() -> None:
assert not graph.cells["2"].disabled_transitively
# Cells to run should include all previously disabled cells and the stale one
- assert cells_to_run == set(["1"])
+ assert cells_to_run == {"1"}
# Test disabling a middle cell
graph.cells["1"].config.disabled = True
@@ -867,7 +857,7 @@ def test_disable_enable_cell() -> None:
assert not graph.cells["2"].disabled_transitively
# Only cells 1 and 2 need to be run
- assert cells_to_run == set(["1", "2"])
+ assert cells_to_run == {"1", "2"}
def test_is_disabled() -> None:
@@ -1017,11 +1007,11 @@ def test_runner_ancestors() -> None:
# Get ancestors of the third cell
ancestors = runner._get_ancestors(graph.cells["2"], {})
- assert ancestors == set(["0", "1"])
+ assert ancestors == {"0", "1"}
# When substituting y, only cell 0 should be an ancestor
ancestors = runner._get_ancestors(graph.cells["2"], {"y": 30})
- assert ancestors == set(["0"])
+ assert ancestors == {"0"}
# When substituting both x and y, there should be no ancestors
ancestors = runner._get_ancestors(graph.cells["2"], {"x": 40, "y": 30})
@@ -1076,7 +1066,7 @@ def test_del_del_cycle():
graph.register_cell("0", parse_cell("del x"))
graph.register_cell("1", parse_cell("del x"))
assert len(graph.cycles) == 1
- assert set(list(graph.cycles)[0]) == set((("0", "1"), ("1", "0")))
+ assert set(next(iter(graph.cycles))) == {("0", "1"), ("1", "0")}
def test_del_ref_cycle():
@@ -1087,7 +1077,7 @@ def test_del_ref_cycle():
graph.register_cell("1", parse_cell("del x; y = 1"))
graph.register_cell("2", parse_cell("z = x + y"))
assert len(graph.cycles) == 1
- assert set(list(graph.cycles)[0]) == set([("1", "2"), ("2", "1")])
+ assert set(next(iter(graph.cycles))) == {("1", "2"), ("2", "1")}
def test_del_child_of_ref():
@@ -1097,14 +1087,14 @@ def test_del_child_of_ref():
graph.register_cell("0", parse_cell("del x"))
graph.register_cell("1", parse_cell("x"))
graph.register_cell("2", parse_cell("x = 1"))
- assert graph.parents["0"] == set(["1", "2"])
+ assert graph.parents["0"] == {"1", "2"}
assert graph.children["0"] == set()
- assert graph.parents["1"] == set(["2"])
- assert graph.children["1"] == set(["0"])
+ assert graph.parents["1"] == {"2"}
+ assert graph.children["1"] == {"0"}
- assert graph.parents["2"] == set([])
- assert graph.children["2"] == set(["0", "1"])
+ assert graph.parents["2"] == set()
+ assert graph.children["2"] == {"0", "1"}
def test_get_path() -> None:
@@ -1186,7 +1176,7 @@ def test_import_block_relatives() -> None:
code = "import pandas as pd\nimport numpy as np"
first_cell = parse_cell(code)
first_cell.import_workspace.is_import_block = True
- first_cell.import_workspace.imported_defs = set(["pd", "np"])
+ first_cell.import_workspace.imported_defs = {"pd", "np"}
graph.register_cell("0", first_cell)
# Create cells that use the imports
@@ -1243,7 +1233,7 @@ result = func3()
graph.register_cell("1", second_cell)
# Get transitive references from result
- refs = graph.get_transitive_references(set(["result"]))
+ refs = graph.get_transitive_references({"result"})
# Should include all functions in the chain
assert "result" in refs
@@ -1252,7 +1242,7 @@ result = func3()
assert "func1" in refs
# Test with non-inclusive mode
- refs = graph.get_transitive_references(set(["result"]), inclusive=False)
+ refs = graph.get_transitive_references({"result"}, inclusive=False)
# Should include all except result
assert "result" not in refs
@@ -1267,11 +1257,11 @@ result = func3()
return data.kind == "function"
refs = graph.get_transitive_references(
- set(["result", "func3"]), predicate=is_function, inclusive=False
+ {"result", "func3"}, predicate=is_function, inclusive=False
)
# Should include only functions
- assert refs == set(["func2", "func1"])
+ assert refs == {"func2", "func1"}
# result is not a function, so it should be excluded even with inclusive=True
assert "result" not in refs
@@ -1303,7 +1293,7 @@ result = obj.method1()
graph.register_cell("1", second_cell)
# Get transitive references from result
- refs = graph.get_transitive_references(set(["result"]))
+ refs = graph.get_transitive_references({"result"})
# Should include all related symbols
assert "result" in refs
@@ -1331,7 +1321,7 @@ def public_func():
graph.register_cell("1", second_cell)
# Get transitive references
- refs = graph.get_transitive_references(set(["result"]))
+ refs = graph.get_transitive_references({"result"})
# Should include public_func
assert "public_func" in refs
diff --git a/tests/_runtime/test_edges.py b/tests/_runtime/test_edges.py
index 9007e000d1..99d7ee87f8 100644
--- a/tests/_runtime/test_edges.py
+++ b/tests/_runtime/test_edges.py
@@ -206,7 +206,7 @@ class TestEdgeComputer:
)
# Compute edges for cell3
- parents3, children3 = edges.compute_edges_for_cell(
+ parents3, _children3 = edges.compute_edges_for_cell(
"cell_3", cell3, self.topology, self.definitions
)
@@ -253,13 +253,13 @@ class TestEdgeComputer:
self.definitions.register_definition("cell_3", name, var_data)
# Check cell1's children (only direct children, not grandchildren)
- parents1, children1 = edges.compute_edges_for_cell(
+ _parents1, children1 = edges.compute_edges_for_cell(
"cell_1", cell1, self.topology, self.definitions
)
assert children1 == {"cell_2", "cell_3"}
# Check cell4's parents (it references b and c, not a directly)
- parents4, children4 = edges.compute_edges_for_cell(
+ parents4, _children4 = edges.compute_edges_for_cell(
"cell_4", cell4, self.topology, self.definitions
)
assert parents4 == {"cell_2", "cell_3"}
@@ -379,7 +379,7 @@ class TestEdgeComputer:
self.definitions.register_definition("cell_1", name, var_data)
# Compute edges for cell2 (Python cell)
- parents, children = edges.compute_edges_for_cell(
+ _parents, _children = edges.compute_edges_for_cell(
"cell_2", cell2, self.topology, self.definitions
)
@@ -406,7 +406,7 @@ class TestEdgeComputer:
self.definitions.register_definition("cell_2", name, var_data)
# Compute edges for cell3
- parents, children = edges.compute_edges_for_cell(
+ parents, _children = edges.compute_edges_for_cell(
"cell_3", cell3, self.topology, self.definitions
)
@@ -445,7 +445,7 @@ class TestEdgeComputer:
self.definitions.register_definition(cell_id, name, var_data)
# Compute edges for cell4
- parents4, children4 = edges.compute_edges_for_cell(
+ parents4, _children4 = edges.compute_edges_for_cell(
"cell_4", cell4, self.topology, self.definitions
)
@@ -488,7 +488,7 @@ class TestEdgeComputer:
self.definitions.register_definition("cell_1", name, var_data)
# Compute edges for cell2
- parents, children = edges.compute_edges_for_cell(
+ parents, _children = edges.compute_edges_for_cell(
"cell_2", cell2, self.topology, self.definitions
)
@@ -507,7 +507,7 @@ class TestEdgeComputer:
self.definitions.register_definition("cell_1", name, var_data)
# Compute edges for cell2
- parents, children = edges.compute_edges_for_cell(
+ parents, _children = edges.compute_edges_for_cell(
"cell_2", cell2, self.topology, self.definitions
)
@@ -526,7 +526,7 @@ class TestEdgeComputer:
self.definitions.register_definition("cell_1", name, var_data)
# Compute edges for cell2
- parents, children = edges.compute_edges_for_cell(
+ parents, _children = edges.compute_edges_for_cell(
"cell_2", cell2, self.topology, self.definitions
)
@@ -551,13 +551,13 @@ class TestEdgeComputer:
# All cells should depend on cell1
for cell_id in ["cell_2", "cell_3", "cell_4"]:
cell = self.topology.cells[cell_id]
- parents, children = edges.compute_edges_for_cell(
+ parents, _children = edges.compute_edges_for_cell(
cell_id, cell, self.topology, self.definitions
)
assert parents == {"cell_1"}
# Check that cell1 has all three as children
- parents1, children1 = edges.compute_edges_for_cell(
+ _parents1, children1 = edges.compute_edges_for_cell(
"cell_1", cell1, self.topology, self.definitions
)
assert children1 == {"cell_2", "cell_3", "cell_4"}
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index cebe66c8de..078fcab2bd 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -1119,7 +1119,7 @@ except NameError:
assert "1" in k.graph.cells
assert "x" not in k.globals
if k.lazy():
- assert k.graph.get_stale() == set([er.cell_id])
+ assert k.graph.get_stale() == {er.cell_id}
await k.run([er])
assert not k.graph.get_stale()
assert "y" not in k.globals
@@ -1131,7 +1131,7 @@ except NameError:
assert "1" in k.graph.cells
assert not k.errors
if k.lazy():
- assert k.graph.get_stale() == set([er.cell_id])
+ assert k.graph.get_stale() == {er.cell_id}
await k.run([er])
assert not k.graph.get_stale()
assert k.globals["y"] == 1
@@ -1156,7 +1156,7 @@ except NameError:
[ExecuteCellCommand(er_1.cell_id, "x = 0; raise RuntimeError")]
)
if k.lazy():
- assert graph.get_stale() == set([er_2.cell_id])
+ assert graph.get_stale() == {er_2.cell_id}
# running er_2 will redefine y; this is different from the
# behavior of a non-lazy kernel, which doesn't run er_2
# but instead invalidates it on exception raised
@@ -1203,7 +1203,7 @@ except NameError:
)
assert k.globals["defs"]["slider"].value == 5
if k.lazy():
- assert graph.get_stale() == set([er.cell_id])
+ assert graph.get_stale() == {er.cell_id}
await k.run([er])
assert not graph.get_stale()
assert k.globals["slider_value"] == 6
@@ -1778,7 +1778,7 @@ except NameError:
await k.rename_file("foo")
if k.lazy():
assert "pytest" in k.globals["x"]
- assert k.graph.get_stale() == set([er.cell_id])
+ assert k.graph.get_stale() == {er.cell_id}
await k.run([er])
assert k.globals["x"] == "foo"
@@ -2736,7 +2736,7 @@ class TestDisable:
)
assert k.globals["ns"].count == 10
- assert k.graph.get_stale() == set([er_2.cell_id])
+ assert k.graph.get_stale() == {er_2.cell_id}
# re-enable cell 2
await k.set_cell_config(
@@ -2745,7 +2745,7 @@ class TestDisable:
)
)
if k.lazy():
- assert k.graph.get_stale() == set([er_2.cell_id])
+ assert k.graph.get_stale() == {er_2.cell_id}
await k.run([er_2])
assert not k.graph.get_stale()
# cell 2 should have re-run
@@ -2783,13 +2783,14 @@ class TestDisable:
await k.run([ExecuteCellCommand(cell_id=er_1.cell_id, code="x = 2")])
assert k.globals["x"] == 2
if k.lazy():
- assert graph.get_stale() == set(
- [er_2.cell_id, er_3.cell_id, er_4.cell_id, er_5.cell_id]
- )
+ assert graph.get_stale() == {
+ er_2.cell_id,
+ er_3.cell_id,
+ er_4.cell_id,
+ er_5.cell_id,
+ }
await k.run([er_5])
- assert graph.get_stale() == set(
- [er_2.cell_id, er_3.cell_id, er_4.cell_id]
- )
+ assert graph.get_stale() == {er_2.cell_id, er_3.cell_id, er_4.cell_id}
assert k.globals["zzz"] == 3
# enable cell 2: should run stale cells as a side-effect
@@ -2801,9 +2802,11 @@ class TestDisable:
assert k.globals["x"] == 2
assert k.globals["zzz"] == 3
if k.lazy():
- assert graph.get_stale() == set(
- [er_2.cell_id, er_3.cell_id, er_4.cell_id]
- )
+ assert graph.get_stale() == {
+ er_2.cell_id,
+ er_3.cell_id,
+ er_4.cell_id,
+ }
# runs er_3 and er_2, which are stale ancestors
await k.run([er_4])
# stale cells **should have** updated
@@ -2836,7 +2839,7 @@ class TestDisable:
)
# update the code of cell 1 -- both cells stale
await k.run([er_1 := exec_req.get_with_id(er_1.cell_id, "x = 2")])
- assert graph.get_stale() == set([er_1.cell_id, er_2.cell_id])
+ assert graph.get_stale() == {er_1.cell_id, er_2.cell_id}
# enable cell 1, but 2 still disabled
await k.set_cell_config(
@@ -2845,11 +2848,11 @@ class TestDisable:
)
)
if k.lazy():
- assert graph.get_stale() == set([er_1.cell_id, er_2.cell_id])
+ assert graph.get_stale() == {er_1.cell_id, er_2.cell_id}
await k.run([er_1])
assert k.globals["x"] == 2
- assert graph.get_stale() == set([er_2.cell_id])
+ assert graph.get_stale() == {er_2.cell_id}
# enable cell 2
await k.set_cell_config(
@@ -2858,7 +2861,7 @@ class TestDisable:
)
)
if k.lazy():
- assert graph.get_stale() == set([er_2.cell_id])
+ assert graph.get_stale() == {er_2.cell_id}
await k.run([er_2])
assert not graph.get_stale()
@@ -3371,17 +3374,15 @@ class TestStateTransitions:
stream = MockStream(mocked_kernel.stream)
cell_notifications = stream.cell_notifications
- n_queued = sum(
- [1 for op in cell_notifications if op.status == "queued"]
- )
+ n_queued = sum(1 for op in cell_notifications if op.status == "queued")
assert n_queued == 1
n_running = sum(
- [1 for op in cell_notifications if op.status == "running"]
+ 1 for op in cell_notifications if op.status == "running"
)
assert n_running == 1
- n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
+ n_idle = sum(1 for op in cell_notifications if op.status == "idle")
assert n_idle == 1
async def test_statuses_not_repeated_on_stop(
@@ -3396,17 +3397,15 @@ class TestStateTransitions:
cell_notifications = mocked_kernel.stream.cell_notifications
- n_queued = sum(
- [1 for op in cell_notifications if op.status == "queued"]
- )
+ n_queued = sum(1 for op in cell_notifications if op.status == "queued")
assert n_queued == 1
n_running = sum(
- [1 for op in cell_notifications if op.status == "running"]
+ 1 for op in cell_notifications if op.status == "running"
)
assert n_running == 1
- n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
+ n_idle = sum(1 for op in cell_notifications if op.status == "idle")
assert n_idle == 1
async def test_statuses_not_repeated_on_interruption(
@@ -3424,17 +3423,15 @@ class TestStateTransitions:
stream = MockStream(mocked_kernel.stream)
cell_notifications = stream.cell_notifications
- n_queued = sum(
- [1 for op in cell_notifications if op.status == "queued"]
- )
+ n_queued = sum(1 for op in cell_notifications if op.status == "queued")
assert n_queued == 1
n_running = sum(
- [1 for op in cell_notifications if op.status == "running"]
+ 1 for op in cell_notifications if op.status == "running"
)
assert n_running == 1
- n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
+ n_idle = sum(1 for op in cell_notifications if op.status == "idle")
assert n_idle == 1
async def test_statuses_not_repeated_on_exception(
@@ -3450,17 +3447,15 @@ class TestStateTransitions:
stream = MockStream(mocked_kernel.stream)
cell_notifications = stream.cell_notifications
- n_queued = sum(
- [1 for op in cell_notifications if op.status == "queued"]
- )
+ n_queued = sum(1 for op in cell_notifications if op.status == "queued")
assert n_queued == 1
n_running = sum(
- [1 for op in cell_notifications if op.status == "running"]
+ 1 for op in cell_notifications if op.status == "running"
)
assert n_running == 1
- n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
+ n_idle = sum(1 for op in cell_notifications if op.status == "idle")
assert n_idle == 1
async def test_descendant_status_reset_to_idle_on_error(
@@ -3478,19 +3473,17 @@ class TestStateTransitions:
cell_notifications = stream.cell_notifications
# er_1 and er_2
- n_queued = sum(
- [1 for op in cell_notifications if op.status == "queued"]
- )
+ n_queued = sum(1 for op in cell_notifications if op.status == "queued")
assert n_queued == 2
# only er_1 runs
n_running = sum(
- [1 for op in cell_notifications if op.status == "running"]
+ 1 for op in cell_notifications if op.status == "running"
)
assert n_running == 1
# er_1 and er_2
- n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
+ n_idle = sum(1 for op in cell_notifications if op.status == "idle")
assert n_idle == 2
assert k.graph.cells[er_1.cell_id].runtime_state == "idle"
@@ -3518,19 +3511,17 @@ class TestStateTransitions:
cell_notifications = stream.cell_notifications
# er_1 and er_2
- n_queued = sum(
- [1 for op in cell_notifications if op.status == "queued"]
- )
+ n_queued = sum(1 for op in cell_notifications if op.status == "queued")
assert n_queued == 2
# only er_1 runs
n_running = sum(
- [1 for op in cell_notifications if op.status == "running"]
+ 1 for op in cell_notifications if op.status == "running"
)
assert n_running == 1
# er_1 and er_2
- n_idle = sum([1 for op in cell_notifications if op.status == "idle"])
+ n_idle = sum(1 for op in cell_notifications if op.status == "idle")
assert n_idle == 2
assert k.graph.cells[er_1.cell_id].runtime_state == "idle"
diff --git a/tests/_runtime/test_virtual_file.py b/tests/_runtime/test_virtual_file.py
index 837ef672b2..8d475d629e 100644
--- a/tests/_runtime/test_virtual_file.py
+++ b/tests/_runtime/test_virtual_file.py
@@ -31,7 +31,7 @@ async def test_virtual_file_creation(
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".pdf")
@@ -52,7 +52,7 @@ async def test_virtual_file_deletion(
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- for fname in get_context().virtual_file_registry.registry.keys():
+ for fname in get_context().virtual_file_registry.registry:
assert fname.endswith(".pdf")
await k.delete_cell(DeleteCellCommand(cell_id=er.cell_id))
@@ -161,7 +161,7 @@ async def test_vfile_refcount_incremented(
]
)
assert len(get_context().virtual_file_registry.registry) == 1
- vfile = list(get_context().virtual_file_registry.filenames())[0]
+ vfile = next(iter(get_context().virtual_file_registry.filenames()))
# 1 reference for the cached `mo.pdf`
# + 1 reference for the markdown
@@ -197,7 +197,7 @@ async def test_vfile_refcount_decremented(
)
ctx = get_context()
assert len(ctx.virtual_file_registry.registry) == 1
- vfile = list(ctx.virtual_file_registry.filenames())[0]
+ vfile = next(iter(ctx.virtual_file_registry.filenames()))
# 0 references because HTML not bound to a variable
# NB: this test may be flaky! refcount decremented when `__del__` is called
@@ -248,7 +248,7 @@ async def test_cached_vfile_disposal(
)
ctx = get_context()
assert len(ctx.virtual_file_registry.registry) == 1
- vfile = list(ctx.virtual_file_registry.filenames())[0]
+ vfile = next(iter(ctx.virtual_file_registry.filenames()))
# 1 reference, in the list
assert ctx.virtual_file_registry.refcount(vfile) == 1
diff --git a/tests/_save/store/test_store.py b/tests/_save/store/test_store.py
index 277dc6a44e..6f73631fdf 100644
--- a/tests/_save/store/test_store.py
+++ b/tests/_save/store/test_store.py
@@ -25,5 +25,5 @@ class TestStore:
from pathlib import Path
key = str(Path(f"mock/P_{cache._cache.key.hash}.pickle"))
- assert key in store._cache.keys()
+ assert key in store._cache
assert store._cache[key]
diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.py
index 49aea70143..1406a14e89 100644
--- a/tests/_save/test_cache.py
+++ b/tests/_save/test_cache.py
@@ -294,7 +294,7 @@ class TestScriptCache:
app.run()
except Exception as e:
if "--cov=marimo" not in sys.argv:
- raise e
+ raise
pytest.mark.xfail(
reason="Coverage conflict with cache introspection"
)
diff --git a/tests/_server/ai/test_mcp.py b/tests/_server/ai/test_mcp.py
index 1029855328..cd9eb80133 100644
--- a/tests/_server/ai/test_mcp.py
+++ b/tests/_server/ai/test_mcp.py
@@ -79,9 +79,9 @@ def mock_stdio_setup():
def create_test_server_definition(
name: str = "test_server",
command: str = "test",
- args: list = None,
- env: dict = None,
- timeout: float = None,
+ args: list | None = None,
+ env: dict | None = None,
+ timeout: float | None = None,
) -> MCPServerDefinition:
"""Create a test server definition with sensible defaults."""
if args is None:
@@ -101,11 +101,11 @@ def create_test_server_definition(
def create_test_server_connection(
name: str = "test_server",
command: str = "test",
- args: list = None,
- env: dict = None,
+ args: list | None = None,
+ env: dict | None = None,
status: MCPServerStatus = MCPServerStatus.DISCONNECTED,
session=None,
- timeout: float = None,
+ timeout: float | None = None,
) -> MCPServerConnection:
"""Create a test server connection with sensible defaults."""
server_def = create_test_server_definition(
@@ -121,8 +121,8 @@ def create_test_tool(
name: str = "test_tool",
description: str = "Test tool",
server_name: str = "test_server",
- namespaced_name: str = None,
- input_schema: dict = None,
+ namespaced_name: str | None = None,
+ input_schema: dict | None = None,
):
"""Create a test tool with sensible defaults."""
if DependencyManager.mcp.has():
@@ -1384,7 +1384,7 @@ class TestMCPClientConnectionManagement:
mock_read, mock_write, mock_stdio_context = mock_stdio_setup()
mock_stdio_client.return_value = mock_stdio_context
- mock_session, mock_session_context = mock_session_setup()
+ _mock_session, mock_session_context = mock_session_setup()
mock_session_class.return_value = mock_session_context
# Mock AsyncExitStack
diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.py
index 1b24434213..adce1b573a 100644
--- a/tests/_server/api/endpoints/test_execution.py
+++ b/tests/_server/api/endpoints/test_execution.py
@@ -224,8 +224,7 @@ class TestExecutionRoutes_EditMode:
}
# Check no marimo in headers
assert all(
- "marimo" not in header
- for header in app_meta_response["headers"].keys()
+ "marimo" not in header for header in app_meta_response["headers"]
)
# Check user is False
assert app_meta_response["user"] is True
@@ -392,8 +391,7 @@ class TestExecutionRoutes_RunMode:
}
# Check no marimo in headers
assert all(
- "marimo" not in header
- for header in app_meta_response["headers"].keys()
+ "marimo" not in header for header in app_meta_response["headers"]
)
# Check user is True
assert app_meta_response["user"] is True
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 1d31e717ca..54cbddb4d7 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -169,7 +169,9 @@ async def test_file_watcher_calls_reload(client: TestClient) -> None:
f.write("\n# test")
f.close()
assert session_manager._watcher_manager._watchers
- watcher = list(session_manager._watcher_manager._watchers.values())[0]
+ watcher = next(
+ iter(session_manager._watcher_manager._watchers.values())
+ )
await watcher.callback(Path(filename))
# Drain messages until we get the reload message
# (other messages like 'variables' may arrive first)
diff --git a/tests/_server/test_asgi.py b/tests/_server/test_asgi.py
index 9876236d88..ee62e66672 100644
--- a/tests/_server/test_asgi.py
+++ b/tests/_server/test_asgi.py
@@ -787,9 +787,7 @@ class TestDynamicDirectoryMiddleware(unittest.TestCase):
# Check the marimo app file as added to the scope prior.
file = scope["marimo_app_file"]
assert isinstance(file, str)
- assert file.endswith(str(allowed_file)) or file.endswith(
- str(blocked_file)
- )
+ assert file.endswith((str(allowed_file), str(blocked_file)))
if scope["type"] == "http":
diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.py
index 1f3eb2338c..c31cc9b0e9 100644
--- a/tests/_server/test_file_manager.py
+++ b/tests/_server/test_file_manager.py
@@ -389,7 +389,7 @@ if __name__ == "__main__":
# Initialize AppFileManager with the temp file
manager = AppFileManager(filename=str(temp_file))
- original_code = list(manager.app.cell_manager.codes())[0]
+ original_code = next(iter(manager.app.cell_manager.codes()))
assert "x = 1" in original_code
# Modify the file content
@@ -412,7 +412,7 @@ if __name__ == "__main__":
changed_cell_ids = manager.reload()
# Check that the code was updated
- reloaded_code = list(manager.app.cell_manager.codes())[0]
+ reloaded_code = next(iter(manager.app.cell_manager.codes()))
assert "x = 42" in reloaded_code
assert "x = 1" not in reloaded_code
assert changed_cell_ids == {"Hbol"}
diff --git a/tests/_session/state/test_serialize_session.py b/tests/_session/state/test_serialize_session.py
index 91058d9376..364e61b3ef 100644
--- a/tests/_session/state/test_serialize_session.py
+++ b/tests/_session/state/test_serialize_session.py
@@ -860,9 +860,7 @@ class TestSessionCacheManager:
manager = SessionCacheManager(view, doc, None, 0.1)
assert (
manager.read_session_view(
- SessionCacheKey(
- codes=tuple(), marimo_version="-1", cell_ids=tuple()
- )
+ SessionCacheKey(codes=(), marimo_version="-1", cell_ids=())
)
== view
)
@@ -876,9 +874,7 @@ class TestSessionCacheManager:
manager = SessionCacheManager(view, doc, path, 0.1)
assert (
manager.read_session_view(
- SessionCacheKey(
- codes=tuple(), marimo_version="-1", cell_ids=tuple()
- )
+ SessionCacheKey(codes=(), marimo_version="-1", cell_ids=())
)
== view
)
diff --git a/tests/_session/test_file_change_handler.py b/tests/_session/test_file_change_handler.py
index 0da1d2c267..c902429e35 100644
--- a/tests/_session/test_file_change_handler.py
+++ b/tests/_session/test_file_change_handler.py
@@ -450,20 +450,20 @@ _BASE_CELL = dedent(
def test_reload_detects_config_only_changes(tmp_path: Path) -> None:
modified = _BASE_CELL.replace("@app.cell", "@app.cell(hide_code=True)")
afm = _assert_reload_detects_change(tmp_path, _BASE_CELL, modified)
- assert list(afm.app.cell_manager.configs())[0].hide_code is True
+ assert next(iter(afm.app.cell_manager.configs())).hide_code is True
def test_reload_detects_disabled_config_change(tmp_path: Path) -> None:
modified = _BASE_CELL.replace("@app.cell", "@app.cell(disabled=True)")
afm = _assert_reload_detects_change(tmp_path, _BASE_CELL, modified)
- assert list(afm.app.cell_manager.configs())[0].disabled is True
+ assert next(iter(afm.app.cell_manager.configs())).disabled is True
def test_reload_detects_name_only_changes(tmp_path: Path) -> None:
initial = _BASE_CELL.replace("my_cell", "old_name")
modified = _BASE_CELL.replace("my_cell", "new_name")
afm = _assert_reload_detects_change(tmp_path, initial, modified)
- assert list(afm.app.cell_manager.names())[0] == "new_name"
+ assert next(iter(afm.app.cell_manager.names())) == "new_name"
def test_reload_no_changes_returns_empty(tmp_path: Path) -> None:
diff --git a/tests/_sql/test_sql_parse.py b/tests/_sql/test_sql_parse.py
index cd5f554447..c35d6fe838 100644
--- a/tests/_sql/test_sql_parse.py
+++ b/tests/_sql/test_sql_parse.py
@@ -460,7 +460,7 @@ class TestEdgeCases:
def test_query_with_semicolon(self):
"""Test parsing query with trailing semicolon."""
- result, error = parse_sql("SELECT 1;", "duckdb")
+ result, _error = parse_sql("SELECT 1;", "duckdb")
assert result is not None
assert result.success is True
@@ -470,7 +470,7 @@ class TestEdgeCases:
"""Test parsing multiple SQL statements."""
query = "SELECT 1; SELECT 2;"
- result, error = parse_sql(query, "duckdb")
+ result, _error = parse_sql(query, "duckdb")
# DuckDB might handle this differently, just ensure we get a result
assert isinstance(result, SqlParseResult)
@@ -547,7 +547,7 @@ class TestEdgeCases:
SELECT 1 as test_column; /* End line comment */
""",
]:
- result, error = parse_sql(query, "duckdb")
+ result, _error = parse_sql(query, "duckdb")
assert result is not None
assert result.success is True
assert result.errors == []
diff --git a/tests/_utils/test_flatten.py b/tests/_utils/test_flatten.py
index 083fce8bb4..93ab6ada13 100644
--- a/tests/_utils/test_flatten.py
+++ b/tests/_utils/test_flatten.py
@@ -65,7 +65,7 @@ def test_flat_empty_list() -> None:
def test_flat_empty_tuple() -> None:
- x: T = tuple()
+ x: T = ()
v, u = flatten(x)
assert v == []
assert u(v) == x
@@ -111,14 +111,14 @@ def test_nested_list() -> None:
def test_nested_tuple() -> None:
- x: T = (0, 1, tuple(), 2, (3, (4, 5)), (6,))
+ x: T = (0, 1, (), 2, (3, (4, 5)), (6,))
v, u = flatten(x)
assert v == [0, 1, 2, 3, 4, 5, 6]
assert u(v) == x
assert u([7, 8, 9, 10, 11, 12, 13]) == (
7,
8,
- tuple(),
+ (),
9,
(10, (11, 12)),
(13,),
@@ -129,7 +129,7 @@ def test_nested_dict() -> None:
x = {
"a": 0,
"b": 1,
- "c": dict(),
+ "c": {},
"d": 2,
"e": {"f": 3, "g": {"h": 4, "i": 5}},
"j": {"k": 6},
@@ -140,7 +140,7 @@ def test_nested_dict() -> None:
assert u([7, 8, 9, 10, 11, 12, 13]) == {
"a": 7,
"b": 8,
- "c": dict(),
+ "c": {},
"d": 9,
"e": {"f": 10, "g": {"h": 11, "i": 12}},
"j": {"k": 13},
@@ -181,13 +181,13 @@ def test_nested_mix_repack_objects() -> None:
v, u = flatten(x)
assert v == [0, 1, 2, 3, 4, 5, 6, 7, 8]
assert u(v) == x
- assert u([[], [], [], [], [], [], [], {}, tuple()]) == [
+ assert u([[], [], [], [], [], [], [], {}, ()]) == [
[],
[],
{"c": []},
([],),
{"d": [], "e": [[], []]},
- [[], ({}, tuple())],
+ [[], ({}, ())],
]
diff --git a/tests/_utils/test_formatter.py b/tests/_utils/test_formatter.py
index 66ebde6db6..92565a3901 100644
--- a/tests/_utils/test_formatter.py
+++ b/tests/_utils/test_formatter.py
@@ -507,5 +507,5 @@ class TestFormatterIntegration:
"""Test CellCodes type alias works as expected."""
codes: CellCodes = {"cell1": "code1", "cell2": "code2"}
assert isinstance(codes, dict)
- assert all(isinstance(k, str) for k in codes.keys())
+ assert all(isinstance(k, str) for k in codes)
assert all(isinstance(v, str) for v in codes.values())
diff --git a/tests/_utils/test_health_utils.py b/tests/_utils/test_health_utils.py
index d2013d5b3a..6e5322cdb3 100644
--- a/tests/_utils/test_health_utils.py
+++ b/tests/_utils/test_health_utils.py
@@ -33,7 +33,7 @@ def test_get_optional_modules_list():
def test_get_versions():
- assert isinstance(_get_versions(list(), False), dict)
+ assert isinstance(_get_versions([], False), dict)
def test_get_chrome_version():
diff --git a/tests/_utils/test_parse_dataclass.py b/tests/_utils/test_parse_dataclass.py
index 90e7d1995e..9476c230dd 100644
--- a/tests/_utils/test_parse_dataclass.py
+++ b/tests/_utils/test_parse_dataclass.py
@@ -137,11 +137,9 @@ class TestParseRaw:
configs: tuple[Config, ...]
nested = Nested(
- configs=tuple(
- [
- Config(disabled=True, gpu=False),
- Config(disabled=False, gpu=True),
- ]
+ configs=(
+ Config(disabled=True, gpu=False),
+ Config(disabled=False, gpu=True),
)
)