diff --git a/.devcontainer/configure-host.py b/.devcontainer/configure-host.py index 7e8630274..00566210a 100644 --- a/.devcontainer/configure-host.py +++ b/.devcontainer/configure-host.py @@ -83,7 +83,11 @@ def ensure_native_image(image: str) -> None: def host_service(system: str, home: Path) -> dict: - """Use VM paths on macOS, never Unix sockets on the macOS shared filesystem.""" + """Use VM paths on macOS, never Unix sockets on the macOS shared filesystem. + + Returns: + The Compose service configuration for the development container. + """ service: dict = {"volumes": []} image = os.environ.get("PHLEX_DEV_IMAGE") if system == "Darwin": diff --git a/ci/promote_phlex_dependencies.py b/ci/promote_phlex_dependencies.py index 1886785e5..568b8e387 100644 --- a/ci/promote_phlex_dependencies.py +++ b/ci/promote_phlex_dependencies.py @@ -9,7 +9,11 @@ def promote_dependencies(env) -> list[str]: - """Register existing link/run dependencies as abstract and concrete roots.""" + """Register existing link/run dependencies as abstract and concrete roots. + + Returns: + Names of dependencies newly promoted to roots. + """ from spack.spec import Spec phlex_roots = [spec for spec in env.concrete_roots() if spec.name == "phlex"] diff --git a/ci/upgrade_repos.py b/ci/upgrade_repos.py index 7043a9365..39a1fb901 100644 --- a/ci/upgrade_repos.py +++ b/ci/upgrade_repos.py @@ -80,7 +80,7 @@ def clean_package_imports(repo_obj: Repo) -> None: for file in files: if file == "package.py": file_path = Path(root) / file - with open(file_path, "r", encoding="utf-8") as f: + with open(file_path, encoding="utf-8") as f: content = f.read() modified_content = content diff --git a/plugins/python/python/phlex/__init__.py b/plugins/python/python/phlex/__init__.py index 501afc841..1d1aaa42c 100644 --- a/plugins/python/python/phlex/__init__.py +++ b/plugins/python/python/phlex/__init__.py @@ -1,4 +1,4 @@ """Phlex Python support module.""" -from ._typing import * # noqa: F403 no names used in this file -from ._variant import * # noqa: F403 idem +from ._typing import * # noqa: F403 +from ._variant import * # noqa: F403 diff --git a/plugins/python/python/phlex/_typing.py b/plugins/python/python/phlex/_typing.py index 1027e02f8..ad5f820a3 100644 --- a/plugins/python/python/phlex/_typing.py +++ b/plugins/python/python/phlex/_typing.py @@ -10,8 +10,9 @@ import ctypes import inspect import typing +from collections.abc import Callable from types import UnionType -from typing import Any, Callable, Dict, Union +from typing import Any, Union import numpy as np @@ -133,7 +134,7 @@ def _build_ctypes_map() -> dict[type, str]: } -def normalize_type(tp: Any, globalns: Dict | None = None, localns: Dict | None = None) -> str: +def normalize_type(tp: Any, globalns: dict | None = None, localns: dict | None = None) -> str: """Recursively normalize any Python annotation to a canonical name. This normalization supports: diff --git a/plugins/python/python/phlex/_variant.py b/plugins/python/python/phlex/_variant.py index 77cd4830c..239b38f2b 100644 --- a/plugins/python/python/phlex/_variant.py +++ b/plugins/python/python/phlex/_variant.py @@ -25,8 +25,12 @@ def __init__(self, arg: str): self.arg = arg def __str__(self): - """Report the argument that is missing an annotation.""" - return "argument '%s' is not annotated" % self.arg + """Report the argument that is missing an annotation. + + Returns: + A message naming the argument without an annotation. + """ + return f"argument '{self.arg}' is not annotated" class Variant: @@ -107,6 +111,9 @@ def __call__(self, *args, **kwargs): Raises: AssertionError: To indicate incorrect usage, unless overridden. + + Returns: + The wrapped callable's result when direct calls are enabled. """ assert self._allow_call, ( f"Variant '{self.__name__}' was called directly. " diff --git a/pyproject.toml b/pyproject.toml index c73ac413a..c9d3d349b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,11 +71,17 @@ select = [ "B", # flake8-bugbear "C4", # flake8-comprehensions "D", # pydocstyle + "DOC201", # require Returns sections for documented return values "E", # pycodestyle errors "F", # pyflakes "I", # isort + "PGH004", # require specific noqa codes + "RUF100", # reject unused noqa directives + "UP", # pyupgrade "W", # pycodestyle warnings ] +preview = true +explicit-preview-rules = true ignore = [] extend-ignore = [ "E731", # do not assign a lambda expression, use a def @@ -103,6 +109,13 @@ known-first-party = [ "validate_clang_tidy_fixes", ] +[tool.ruff.lint.per-file-ignores] +# Ignore missing docstring requirements for test files and typing stubs +"test/**/*" = ["D", "DOC201"] +"scripts/test/**/*" = ["D", "DOC201"] +"test/python/test_typing.py" = ["UP006", "UP035"] +"*.pyi" = ["D", "DOC201"] + [tool.ruff.lint.pydocstyle] convention = "google" diff --git a/scripts/check_codeql_alerts.py b/scripts/check_codeql_alerts.py index 6fd14af7d..7e7e31ecb 100644 --- a/scripts/check_codeql_alerts.py +++ b/scripts/check_codeql_alerts.py @@ -13,7 +13,7 @@ import urllib.parse import urllib.request from dataclasses import dataclass -from datetime import datetime, timezone +from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -236,7 +236,7 @@ def _log(msg: str) -> None: try: _LOG_PATH.parent.mkdir(parents=True, exist_ok=True) # Use timezone-aware UTC timestamp to avoid deprecation warnings. - ts = datetime.now(timezone.utc).isoformat() + ts = datetime.now(UTC).isoformat() with open(_LOG_PATH, "a", encoding="utf-8") as fh: fh.write(f"{ts} {msg}\n") except Exception: @@ -254,7 +254,7 @@ def _init_log(log_path: Path) -> None: _LOG_PATH = log_path try: _LOG_PATH.parent.mkdir(parents=True, exist_ok=True) - ts = datetime.now(timezone.utc).isoformat() + ts = datetime.now(UTC).isoformat() with open(_LOG_PATH, "w", encoding="utf-8") as fh: fh.write(f"{ts} CodeQL alerts helper log (truncated for new run)\n") except Exception: @@ -281,8 +281,7 @@ def _paginate_alerts_api( raise GitHubAPIError("Unexpected response when listing alerts (expected list).") if not result: return - for alert in result: - yield alert + yield from result # GitHub returns fewer than per_page items on the last page if len(result) < per_page: return @@ -313,7 +312,11 @@ def _format_physical_location(phys: dict[str, Any]) -> str | None: def _to_alert_api(raw: dict) -> Alert: - """Convert a raw code-scanning alert object from the API into Alert dataclass.""" + """Convert a raw code-scanning alert object from the API into Alert dataclass. + + Returns: + The normalized alert representation. + """ rule = raw.get("rule") or {} rule_id = str(rule.get("id") or "(rule id unavailable)") instance = raw.get("most_recent_instance") or {} @@ -973,7 +976,11 @@ def set_outputs( def _compare_alerts_via_api( owner: str, repo: str, ref: str, *, min_level: str = "warning" ) -> APIAlertComparison: - """Compare alerts between a ref and the main branch using the GitHub API.""" + """Compare alerts between a ref and the main branch using the GitHub API. + + Returns: + The categorized alert comparison. + """ # Fetch PR metadata first so we can use the head SHA when querying PR alerts. # The Code Scanning API does not support synthetic merge refs such as # refs/pull/N/merge; using that ref returns zero results. The head SHA is @@ -1130,7 +1137,11 @@ def _build_multi_section_comment( *, pr_number: int | None = None, ) -> str: - """Build a detailed PR comment when multiple comparisons have been made.""" + """Build a detailed PR comment when multiple comparisons have been made. + + Returns: + Markdown containing the comparison sections. + """ lines: list[str] = [] # Matching summary (always include in PR comment) if api_comp.new_vs_base or api_comp.fixed_vs_base: diff --git a/scripts/clang_tidy_check_summary.py b/scripts/clang_tidy_check_summary.py index add6c106d..e6dc93f89 100755 --- a/scripts/clang_tidy_check_summary.py +++ b/scripts/clang_tidy_check_summary.py @@ -165,7 +165,11 @@ def format_checklist(counts: dict[str, int], *, links: bool = False) -> str: def build_arg_parser() -> argparse.ArgumentParser: - """Build and return the argument parser for this script.""" + """Build and return the argument parser for this script. + + Returns: + The configured command-line argument parser. + """ parser = argparse.ArgumentParser( prog="clang_tidy_check_summary.py", description=( diff --git a/scripts/clang_tidy_diff_issues.py b/scripts/clang_tidy_diff_issues.py index e53ebe57f..7b9608ff8 100644 --- a/scripts/clang_tidy_diff_issues.py +++ b/scripts/clang_tidy_diff_issues.py @@ -175,7 +175,11 @@ def filter_issues( def build_arg_parser() -> argparse.ArgumentParser: - """Build and return the argument parser.""" + """Build and return the argument parser. + + Returns: + The configured command-line argument parser. + """ parser = argparse.ArgumentParser( description=( "Report clang-tidy warnings and errors that fall on lines" @@ -216,7 +220,11 @@ def build_arg_parser() -> argparse.ArgumentParser: def main() -> int: - """Parse arguments, filter issues, and report results.""" + """Parse arguments, filter issues, and report results. + + Returns: + Zero on success, or a nonzero command-line error status. + """ args = build_arg_parser().parse_args() log_path = Path(args.log) diff --git a/scripts/clang_tidy_fixes_to_problems.py b/scripts/clang_tidy_fixes_to_problems.py index af7ab1ad4..1cd06fd74 100644 --- a/scripts/clang_tidy_fixes_to_problems.py +++ b/scripts/clang_tidy_fixes_to_problems.py @@ -100,7 +100,7 @@ class Diagnostic: level: str = "warning" file_path: str | None = None file_offset: int | None = None - notes: list["DiagnosticNote"] | None = None + notes: list[DiagnosticNote] | None = None @dataclass @@ -329,7 +329,11 @@ def choose_workspace_note( def build_arg_parser() -> argparse.ArgumentParser: - """Build and return the argument parser for this script.""" + """Build and return the argument parser for this script. + + Returns: + The configured command-line argument parser. + """ parser = argparse.ArgumentParser( prog="clang_tidy_fixes_to_problems.py", description=( diff --git a/scripts/codeql_reset_dismissed_alerts.py b/scripts/codeql_reset_dismissed_alerts.py index c8cea7926..c150ebd4d 100644 --- a/scripts/codeql_reset_dismissed_alerts.py +++ b/scripts/codeql_reset_dismissed_alerts.py @@ -175,8 +175,7 @@ def _paginate_alerts(owner: str, repo: str) -> Iterator[dict]: raise GitHubAPIError("Unexpected response when listing alerts (expected a JSON list).") if not result: return - for alert in result: - yield alert + yield from result page += 1 diff --git a/scripts/fix_header_guards.py b/scripts/fix_header_guards.py index 3db1f08e6..4aee6c7ef 100755 --- a/scripts/fix_header_guards.py +++ b/scripts/fix_header_guards.py @@ -18,7 +18,11 @@ def normalize_guard_component(component: str) -> str: - """Convert a path component to a non-reserved macro identifier token.""" + """Convert a path component to a non-reserved macro identifier token. + + Returns: + The normalized preprocessor identifier component. + """ normalized = re.sub(r"[^A-Z0-9_]", "_", component.upper()) normalized = re.sub(r"_+", "_", normalized) if not normalized or not normalized[0].isalpha(): @@ -27,7 +31,11 @@ def normalize_guard_component(component: str) -> str: def compute_expected_guard(file_path: Path, root: Path) -> str: - """Compute expected guard macro: X_Y_HEADER_EXT.""" + """Compute expected guard macro: X_Y_HEADER_EXT. + + Returns: + The expected header guard macro name. + """ rel = file_path.relative_to(root) # Include directory components only; a top-level header has none. parts = [normalize_guard_component(part) for part in rel.parts[:-1]] @@ -36,14 +44,22 @@ def compute_expected_guard(file_path: Path, root: Path) -> str: def leading_comment_lines(content: str) -> int: - """Count lines before the first token, ignoring whitespace and leading comments.""" + """Count lines before the first token, ignoring whitespace and leading comments. + + Returns: + The number of lines before the first non-comment token. + """ prefix = re.match(r"(?:\s+|//[^\n]*(?:\n|$)|/\*.*?\*/)*", content, re.DOTALL) assert prefix is not None return prefix.group().count("\n") def check_header_guard(file_path: Path, root: Path) -> tuple[bool, str | None]: - """Check if header guard is correct. Returns (is_valid, expected_guard).""" + """Check if header guard is correct. + + Returns: + A pair containing validity and the expected guard when invalid. + """ if file_path.name.endswith(LINKDEF_SUFFIXES): return True, None @@ -82,7 +98,11 @@ def check_header_guard(file_path: Path, root: Path) -> tuple[bool, str | None]: def fix_header_guard(file_path: Path, root: Path) -> bool: - """Fix header guard. Returns True if modified.""" + """Fix header guard. + + Returns: + Whether the file was modified. + """ if file_path.name.endswith(LINKDEF_SUFFIXES): return False diff --git a/scripts/sarif-alerts.py b/scripts/sarif-alerts.py index 896047fc2..471ec5cb2 100644 --- a/scripts/sarif-alerts.py +++ b/scripts/sarif-alerts.py @@ -16,6 +16,9 @@ def _collect_sarif_paths(inputs: list[Path]) -> list[Path]: """Expand any directory entries to the .sarif files they contain. Files are returned in a stable, sorted order so output is reproducible. + + Returns: + The input files and recursively discovered SARIF files. """ paths: list[Path] = [] for p in inputs: @@ -98,7 +101,11 @@ def _process_sarif( def _positive_int(value: str) -> int: - """Argparse type for --max-message: reject values less than 1.""" + """Argparse type for --max-message: reject values less than 1. + + Returns: + The validated positive integer. + """ n = int(value) if n < 1: raise argparse.ArgumentTypeError(f"N must be at least 1, got {n}") diff --git a/scripts/test/test_check_codeql_alerts.py b/scripts/test/test_check_codeql_alerts.py index 582136b93..541f3f32d 100644 --- a/scripts/test/test_check_codeql_alerts.py +++ b/scripts/test/test_check_codeql_alerts.py @@ -28,7 +28,7 @@ import pytest # sys.path is set up by scripts/test/conftest.py. -import check_codeql_alerts as M # noqa: E402 +import check_codeql_alerts as M # --------------------------------------------------------------------------- # Helpers / fixtures @@ -1025,7 +1025,7 @@ class TestCompareAlertsViaApi: def _mock_paginate(self, pages: dict[str | None, list[dict]]) -> MagicMock: """Return a side_effect callable that dispatches on the `ref` kwarg.""" - def _paginate(owner: str, repo: str, *, state: str = "open", ref: str | None = None): # noqa: ANN202 + def _paginate(owner: str, repo: str, *, state: str = "open", ref: str | None = None): yield from pages.get(ref, []) return MagicMock(side_effect=_paginate) @@ -1363,7 +1363,7 @@ def test_blank_lines_preserved_between_sections(self) -> None: lines = body.splitlines() h2_indices = [i for i, ln in enumerate(lines) if ln.startswith("##")] assert len(h2_indices) >= 2 - for a, b in zip(h2_indices, h2_indices[1:]): # noqa: B905 + for a, b in zip(h2_indices, h2_indices[1:], strict=False): assert b - a > 1, "H2 headings are directly adjacent (no blank line)" def test_code_scanning_link_present(self, monkeypatch: pytest.MonkeyPatch) -> None: @@ -1867,7 +1867,7 @@ def test_api_mode_pr_ref_produces_filtered_url( sarif_dir = self._empty_sarif_dir(tmp_path) pr_alert = _make_api_alert(number=1, severity="error", analysis_key="ak:1") - def _paginate(owner: str, repo: str, *, state: str = "open", ref: str | None = None): # noqa: ANN202 + def _paginate(owner: str, repo: str, *, state: str = "open", ref: str | None = None): if ref == "refs/pull/104/merge": yield pr_alert # main, base, and prev-commit refs return nothing diff --git a/scripts/test/test_clang_tidy_check_summary.py b/scripts/test/test_clang_tidy_check_summary.py index 7f5ed4b47..cee4f1245 100644 --- a/scripts/test/test_clang_tidy_check_summary.py +++ b/scripts/test/test_clang_tidy_check_summary.py @@ -21,7 +21,7 @@ import pytest # sys.path is set up by scripts/test/conftest.py. -import clang_tidy_check_summary as M # noqa: E402 +import clang_tidy_check_summary as M # --------------------------------------------------------------------------- # Helpers diff --git a/scripts/test/test_clang_tidy_diff_issues.py b/scripts/test/test_clang_tidy_diff_issues.py index 21b6e3fff..6663fa37e 100644 --- a/scripts/test/test_clang_tidy_diff_issues.py +++ b/scripts/test/test_clang_tidy_diff_issues.py @@ -3,7 +3,7 @@ from __future__ import annotations # sys.path is set up by scripts/test/conftest.py. -from clang_tidy_diff_issues import ( # noqa: E402 +from clang_tidy_diff_issues import ( filter_issues, filter_new_issues, parse_diff, diff --git a/scripts/test/test_clang_tidy_fixes_to_problems.py b/scripts/test/test_clang_tidy_fixes_to_problems.py index 7c60eba60..edb544a33 100644 --- a/scripts/test/test_clang_tidy_fixes_to_problems.py +++ b/scripts/test/test_clang_tidy_fixes_to_problems.py @@ -22,7 +22,7 @@ import yaml # sys.path is set up by scripts/test/conftest.py. -import clang_tidy_fixes_to_problems as M # noqa: E402 +import clang_tidy_fixes_to_problems as M # --------------------------------------------------------------------------- # Helpers diff --git a/scripts/test/test_codeql_reset_dismissed_alerts.py b/scripts/test/test_codeql_reset_dismissed_alerts.py index 730d84723..9bf392867 100644 --- a/scripts/test/test_codeql_reset_dismissed_alerts.py +++ b/scripts/test/test_codeql_reset_dismissed_alerts.py @@ -23,7 +23,7 @@ import json import urllib.error -import urllib.request +import urllib.request # noqa: F401 # patched by URL in these tests from io import BytesIO from typing import Any from unittest.mock import MagicMock, patch @@ -31,7 +31,7 @@ import pytest # sys.path is set up by scripts/test/conftest.py. -import codeql_reset_dismissed_alerts as M # noqa: E402 +import codeql_reset_dismissed_alerts as M # --------------------------------------------------------------------------- # Helpers diff --git a/scripts/test/test_coverage_scripts.py b/scripts/test/test_coverage_scripts.py index dc93d4e64..33d8c6b6b 100644 --- a/scripts/test/test_coverage_scripts.py +++ b/scripts/test/test_coverage_scripts.py @@ -20,10 +20,10 @@ import pytest # sys.path is set up by scripts/test/conftest.py. -import create_coverage_symlinks as ccs # noqa: E402 -import export_llvm_lcov as ell # noqa: E402 -import normalize_coverage_lcov as ncl # noqa: E402 -import normalize_coverage_xml as ncx # noqa: E402 +import create_coverage_symlinks as ccs +import export_llvm_lcov as ell +import normalize_coverage_lcov as ncl +import normalize_coverage_xml as ncx # =========================================================================== # normalize_coverage_lcov diff --git a/scripts/test/test_create_fix_patch.py b/scripts/test/test_create_fix_patch.py index 1aedc4870..5de283b18 100644 --- a/scripts/test/test_create_fix_patch.py +++ b/scripts/test/test_create_fix_patch.py @@ -1,6 +1,6 @@ """Tests for immutable, patch-only formatter output.""" -from __future__ import annotations # noqa: I001 +from __future__ import annotations import json import os diff --git a/scripts/test/test_fix_header_guards.py b/scripts/test/test_fix_header_guards.py index 21f3f07fe..a081c08e4 100644 --- a/scripts/test/test_fix_header_guards.py +++ b/scripts/test/test_fix_header_guards.py @@ -25,7 +25,7 @@ import pytest # sys.path is set up by scripts/test/conftest.py. -import fix_header_guards as M # noqa: E402 +import fix_header_guards as M # --------------------------------------------------------------------------- # Helpers diff --git a/scripts/test/test_workflow_cleanup.py b/scripts/test/test_workflow_cleanup.py index 2e466ed25..3f351537b 100644 --- a/scripts/test/test_workflow_cleanup.py +++ b/scripts/test/test_workflow_cleanup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """Tests for PR comment cleanup steps in GitHub workflows. The workflows add a marker comment and a cleanup step that removes stale diff --git a/scripts/validate_clang_tidy_fixes.py b/scripts/validate_clang_tidy_fixes.py index 38cb58dd8..9ed1bb7aa 100644 --- a/scripts/validate_clang_tidy_fixes.py +++ b/scripts/validate_clang_tidy_fixes.py @@ -23,7 +23,11 @@ class FixValidationError(ValueError): def _tracked_source_path(value: Any, source_root: Path) -> tuple[Path, int]: - """Resolve one replacement target and require a tracked C++ source file.""" + """Resolve one replacement target and require a tracked C++ source file. + + Returns: + The resolved path and its current byte size. + """ if not isinstance(value, str) or not value or "\x00" in value or "\\" in value: raise FixValidationError("replacement FilePath must be a non-empty POSIX path") @@ -75,7 +79,11 @@ def _tracked_source_path(value: Any, source_root: Path) -> tuple[Path, int]: def _replacement_entries(document: Any) -> list[dict[str, Any]]: - """Find all replacement lists without following YAML alias cycles.""" + """Find all replacement lists without following YAML alias cycles. + + Returns: + All replacement mappings reachable from the document. + """ pending = [document] visited: set[int] = set() entries: list[dict[str, Any]] = [] @@ -110,7 +118,11 @@ def _replacement_entries(document: Any) -> list[dict[str, Any]]: def validate_and_copy(fixes_file: Path, source_root: Path, output_dir: Path) -> int: - """Validate every replacement and copy the sole accepted YAML into staging.""" + """Validate replacements and copy the accepted YAML into staging. + + Returns: + The number of validated replacement entries. + """ source_root = source_root.resolve(strict=True) if fixes_file.is_symlink(): raise FixValidationError("fixes file must not be a symlink") @@ -173,7 +185,11 @@ def validate_and_copy(fixes_file: Path, source_root: Path, output_dir: Path) -> def main() -> int: - """Validate and stage a fixes document, failing closed on any ambiguity.""" + """Validate and stage a fixes document, failing closed on any ambiguity. + + Returns: + The process exit status. + """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("fixes_file", type=Path) parser.add_argument("--source-root", required=True, type=Path) diff --git a/test/python/adder.py b/test/python/adder.py index d28f8b2d4..19320e572 100644 --- a/test/python/adder.py +++ b/test/python/adder.py @@ -4,7 +4,7 @@ real. It serves as a "Hello, World" equivalent for running Python code. """ -from typing import Any, Protocol, TypeVar, cast +from typing import Any, Protocol, cast from phlex import Variant @@ -12,16 +12,13 @@ class AddableProtocol[T](Protocol): """Typer bound for any types that can be added.""" - def __add__(self, other: T) -> T: # noqa: D105 - ... # codeql[py/ineffectual-statement] + def __add__(self, other: T) -> T: ... # codeql[py/ineffectual-statement] -Addable = TypeVar("Addable", bound=AddableProtocol) - _DEFAULT_ADDABLE = cast(Any, 42) -def add(i: Addable, j: Addable = _DEFAULT_ADDABLE) -> Addable: +def add[Addable: AddableProtocol[Any]](i: Addable, j: Addable = _DEFAULT_ADDABLE) -> Addable: """Add the inputs together and return the sum total. Use the standard `+` operator to add the two inputs together diff --git a/test/python/all_config.py b/test/python/all_config.py index a4b86a550..5fb40410e 100644 --- a/test/python/all_config.py +++ b/test/python/all_config.py @@ -29,7 +29,7 @@ def __init__(self, config): None """ # builtin types - assert config["a_bool"] == False # noqa: E712 # we really want to check False + assert config["a_bool"] is False assert config["an_int"] == -37 assert config["a_uint"] == 18446744073709551616 assert config["a_float"] == 3.1415 @@ -60,7 +60,7 @@ def __init__(self, config): assert config["empty"] == () # verify caching: second access to the same keys returns the same values - assert config["a_bool"] == False # noqa: E712 # cache hit + assert config["a_bool"] is False # cache hit assert config["an_int"] == -37 # cache hit assert config["some_floats"] == (3.1415, 2.71828) # cache hit (array) assert config["some_objects"][0] == {"a": "b", "c": "d", "e": "f"} # cache hit (obj array) diff --git a/test/python/basic_types.py b/test/python/basic_types.py index e2a56df30..be5a5ae78 100644 --- a/test/python/basic_types.py +++ b/test/python/basic_types.py @@ -20,8 +20,9 @@ # ruff: noqa: E501 import math +from collections.abc import Callable from dataclasses import dataclass -from typing import Any, Callable +from typing import Any import numpy as np import numpy.typing as npt @@ -90,12 +91,12 @@ class OutputKind: ), OutputKind( "numpy", - lambda t: None if t.np_dtype is None else npt.NDArray[t.np_dtype], # type: ignore # noqa: F821 + lambda t: None if t.np_dtype is None else npt.NDArray[t.np_dtype], # type: ignore[name-defined] lambda t, a, b: np.array([a, b], dtype=t.np_dtype), ), OutputKind( "list", - lambda t: None if t.np_dtype is None else list[t.annotation], # type: ignore # noqa: F821 + lambda t: None if t.np_dtype is None else list[t.annotation], # type: ignore[name-defined] lambda t, a, b: [a, b], ), ] diff --git a/test/python/pyprovide.py b/test/python/pyprovide.py index f884c63b7..e5cb83e1c 100644 --- a/test/python/pyprovide.py +++ b/test/python/pyprovide.py @@ -5,8 +5,6 @@ algorithms. """ -from typing import Dict, List - import numpy as np import numpy.typing as npt @@ -106,7 +104,7 @@ def __call__(self, di): # annotations with ambiguous (union) type fail annotation processing try: - funky = List[int] | Dict[int, int] + funky = list[int] | dict[int, int] f = Variant(lambda di: 42, {"di": "data_cell_index", "return": funky}, "f") s.provide(f, {"creator": "a", "layer": "b", "suffix": "c"}) assert not "supposed to be here" diff --git a/test/python/reducer.py b/test/python/reducer.py index b0353a211..7fe076cf1 100644 --- a/test/python/reducer.py +++ b/test/python/reducer.py @@ -67,9 +67,9 @@ def PHLEX_REGISTER_ALGORITHMS(m, config): for i in range(4): m.transform( add, - name="reduce%d" % i, + name=f"reduce{i}", input_family=config["input"], - output_product_suffixes=["sum%d" % i], + output_product_suffixes=[f"sum{i}"], ) # now reduce them pair-wise diff --git a/test/python/suffix.py b/test/python/suffix.py index 558ee29f8..d55532e9b 100644 --- a/test/python/suffix.py +++ b/test/python/suffix.py @@ -152,7 +152,7 @@ def PHLEX_REGISTER_ALGORITHMS(m, config): ) assert not "supposed to be here" except TypeError: - pass # noqa + pass # observers with suffix m.observe( diff --git a/test/python/test_callbacks.py b/test/python/test_callbacks.py index 6d485a998..7154e5b52 100644 --- a/test/python/test_callbacks.py +++ b/test/python/test_callbacks.py @@ -20,13 +20,13 @@ def bad_bool(i: int) -> bool: # Invalid long return (float) -def bad_long(i: int) -> "long": # type: ignore # noqa: F821 +def bad_long(i: int) -> "long": # type: ignore # noqa: F821 """Return a float instead of an int.""" return 1.5 # type: ignore # Invalid uint return (negative) -def bad_uint(i: int) -> "unsigned int": # type: ignore # noqa: F722 +def bad_uint(i: int) -> "unsigned int": # type: ignore # noqa: F722 """Return a negative value for unsigned int.""" return -5 # type: ignore diff --git a/test/python/test_coverage.py b/test/python/test_coverage.py index 5f02e9377..8730b0cc0 100644 --- a/test/python/test_coverage.py +++ b/test/python/test_coverage.py @@ -1,7 +1,7 @@ """Test coverage for list input converters.""" -class double(float): # noqa: N801 +class double(float): """Dummy class for C++ double type.""" pass diff --git a/test/python/test_mismatch.py b/test/python/test_mismatch.py index 0ac3f7e3b..b1870b971 100644 --- a/test/python/test_mismatch.py +++ b/test/python/test_mismatch.py @@ -1,7 +1,5 @@ """Test mismatch between input labels and types.""" -from typing import Dict, List - from phlex import Variant @@ -13,7 +11,7 @@ def mismatch_func(a: int, b: int) -> int: def PHLEX_REGISTER_ALGORITHMS(m, config): """Register algorithms.""" # test a range of possible errors in the annotation and product specifications - funky1 = List[int] | Dict[int, int] + funky1 = list[int] | dict[int, int] funky2 = b"\x80".decode("gbk", errors="surrogateescape") funky3 = "" # empty string diff --git a/test/python/test_phlex.py b/test/python/test_phlex.py index 4fbba7e2a..57c65742b 100644 --- a/test/python/test_phlex.py +++ b/test/python/test_phlex.py @@ -7,7 +7,7 @@ class TestPYPHLEX: @classmethod def setup_class(cls): """Set up the test class.""" - import phlexpy # noqa: F401 # type: ignore[import-not-found] + import phlexpy # type: ignore[import-not-found] # noqa: F401 __all__ = ["phlexpy"] # noqa: F841 # For CodeQL diff --git a/test/python/test_typing.py b/test/python/test_typing.py index aa24a0b12..7f153aa48 100644 --- a/test/python/test_typing.py +++ b/test/python/test_typing.py @@ -82,7 +82,7 @@ def test_special_cases(self): assert normalize_type(None) == "None" # use of namespaces for evaluation - assert ("foo") == "foo" + assert "foo" == "foo" global foo # lgtm[py/unused-global-variable] foo = np.int64 assert normalize_type("foo", globals()) == "int64_t" @@ -97,7 +97,7 @@ def test_special_cases(self): raises(TypeError, normalize_type, ctypes.POINTER(ctypes.c_int)) # ctypes array - assert normalize_type((ctypes.c_int * 42)) == "array[int32_t]" + assert normalize_type(ctypes.c_int * 42) == "array[int32_t]" # something unknown class SomeType: diff --git a/test/python/vectypes.py b/test/python/vectypes.py index c3e0d3aca..54581ab30 100644 --- a/test/python/vectypes.py +++ b/test/python/vectypes.py @@ -22,8 +22,8 @@ def sum_array_int32(coll: npt.NDArray[np.int32]) -> int: def collectify_uint32( - u1: "unsigned int", # type: ignore # noqa: F722 # noqa: F821 - u2: "unsigned int", # type: ignore # noqa: F722 # noqa: F821 + u1: "unsigned int", # type: ignore # noqa: F722 + u2: "unsigned int", # type: ignore # noqa: F722 ) -> npt.NDArray[np.uint32]: """Create a uint32 array from two integers.""" return np.array([u1, u2], dtype=np.uint32) @@ -34,25 +34,28 @@ def sum_array_uint32(coll: npt.NDArray[np.uint32]) -> np.uint32: return np.uint32(sum(int(x) for x in coll)) -def collectify_int64(l1: "long", l2: "long") -> npt.NDArray[np.int64]: # type: ignore # noqa: F821 +def collectify_int64( + l1: "long", # type: ignore[name-defined] # noqa: F821 + l2: "long", # type: ignore[name-defined] # noqa: F821 +) -> npt.NDArray[np.int64]: # type: ignore """Create an int64 array from two integers.""" return np.array([l1, l2], dtype=np.int64) -def sum_array_int64(coll: npt.NDArray[np.int64]) -> "int64_t": # type: ignore # noqa: F821 +def sum_array_int64(coll: npt.NDArray[np.int64]) -> "int64_t": # type: ignore # noqa: F821 """Sum an int64 array.""" return np.int64(sum(int(x) for x in coll)) def collectify_uint64( - ul1: "unsigned long", # type: ignore # noqa: F722 # noqa: F821 - ul2: "unsigned long", # type: ignore # noqa: F722 # noqa: F821 + ul1: "unsigned long", # type: ignore # noqa: F722 + ul2: "unsigned long", # type: ignore # noqa: F722 ) -> npt.NDArray[np.uint64]: """Create a uint64 array from two integers.""" return np.array([ul1, ul2], dtype=np.uint64) -def sum_array_uint64(coll: npt.NDArray[np.uint64]) -> "uint64_t": # type: ignore # noqa: F821 +def sum_array_uint64(coll: npt.NDArray[np.uint64]) -> "uint64_t": # type: ignore # noqa: F821 """Sum a uint64 array.""" return np.uint64(sum(int(x) for x in coll)) @@ -67,7 +70,10 @@ def sum_array_float32(coll: npt.NDArray[np.float32]) -> np.float32: return np.float32(sum(coll)) -def collectify_float64(d1: "double", d2: "double") -> npt.NDArray[np.float64]: # type: ignore # noqa: F821 +def collectify_float64( + d1: "double", # type: ignore[name-defined] # noqa: F821 + d2: "double", # type: ignore[name-defined] # noqa: F821 +) -> npt.NDArray[np.float64]: # type: ignore """Create a float64 array from two floats.""" return np.array([d1, d2], dtype=np.float64) @@ -77,12 +83,15 @@ def collectify_float32_list(f1: float, f2: float) -> list[float]: return [f1, f2] -def collectify_float64_list(d1: "double", d2: "double") -> list["double"]: # type: ignore # noqa: F821 +def collectify_float64_list( + d1: "double", # type: ignore[name-defined] # noqa: F821 + d2: "double", # type: ignore[name-defined] # noqa: F821 +) -> list["double"]: # type: ignore # noqa: F821 """Create a float64 list from two floats.""" return [d1, d2] -def sum_array_float64(coll: npt.NDArray[np.float64]) -> "double": # type: ignore # noqa: F821 +def sum_array_float64(coll: npt.NDArray[np.float64]) -> "double": # type: ignore # noqa: F821 """Sum a float64 array.""" return float(sum(coll)) @@ -93,22 +102,25 @@ def collectify_int32_list(i: int, j: int) -> list[int]: def collectify_uint32_list( - u1: "unsigned int", # type: ignore # noqa: F722 # noqa: F821 - u2: "unsigned int", # type: ignore # noqa: F722 # noqa: F821 -) -> list["unsigned int"]: # type: ignore # noqa: F722 # noqa: F821 + u1: "unsigned int", # type: ignore # noqa: F722 + u2: "unsigned int", # type: ignore # noqa: F722 +) -> list["unsigned int"]: # type: ignore # noqa: F722 """Create a uint32 list from two integers.""" return [np.uint32(u1), np.uint32(u2)] -def collectify_int64_list(l1: "long", l2: "long") -> "list[int64_t]": # type: ignore # noqa: F821 +def collectify_int64_list( + l1: "long", # type: ignore[name-defined] # noqa: F821 + l2: "long", # type: ignore[name-defined] # noqa: F821 +) -> "list[int64_t]": # type: ignore # noqa: F821 """Create an int64 list from two integers.""" return [l1, l2] def collectify_uint64_list( - ul1: "unsigned long", # type: ignore # noqa: F722 # noqa: F821 - ul2: "unsigned long", # type: ignore # noqa: F722 # noqa: F821 -) -> "list[uint64_t]": # type: ignore # noqa: F821 + ul1: "unsigned long", # type: ignore # noqa: F722 + ul2: "unsigned long", # type: ignore # noqa: F722 +) -> "list[uint64_t]": # type: ignore # noqa: F821 """Create a uint64 list from two integers.""" return [np.uint64(ul1), np.uint64(ul2)] @@ -118,17 +130,17 @@ def sum_list_int32(coll: list[int]) -> int: return sum(coll) -def sum_list_uint32(coll: "list[uint32_t]") -> "uint32_t": # type: ignore # noqa: F821 +def sum_list_uint32(coll: "list[uint32_t]") -> "uint32_t": # type: ignore # noqa: F821 """Sum a list of uints.""" return sum(coll) -def sum_list_int64(coll: "list[int64_t]") -> "int64_t": # type: ignore # noqa: F821 +def sum_list_int64(coll: "list[int64_t]") -> "int64_t": # type: ignore # noqa: F821 """Sum a list of longs.""" return sum(coll) -def sum_list_uint64(coll: "list[uint64_t]") -> "uint64_t": # type: ignore # noqa: F821 +def sum_list_uint64(coll: "list[uint64_t]") -> "uint64_t": # type: ignore # noqa: F821 """Sum a list of ulongs.""" return sum(coll) @@ -138,7 +150,7 @@ def sum_list_float(coll: list[float]) -> np.float32: return np.float32(sum(coll)) -def sum_list_double(coll: list["double"]) -> "double": # type: ignore # noqa: F821 +def sum_list_double(coll: list["double"]) -> "double": # type: ignore # noqa: F821 """Sum a list of doubles.""" return sum(coll) diff --git a/test/python/verify_extended.py b/test/python/verify_extended.py index c456cde1a..08f71c3e7 100644 --- a/test/python/verify_extended.py +++ b/test/python/verify_extended.py @@ -24,7 +24,7 @@ def __init__(self, sum_total: int): """Initialize with expected sum.""" self._sum_total = sum_total - def __call__(self, value: "unsigned int") -> None: # type: ignore # noqa: F722 + def __call__(self, value: "unsigned int") -> None: # type: ignore # noqa: F722 """Check if value matches expected sum.""" assert value == self._sum_total @@ -38,7 +38,7 @@ def __init__(self, sum_total: int): """Initialize with expected sum.""" self._sum_total = sum_total - def __call__(self, value: "long") -> None: # type: ignore # noqa: F821 + def __call__(self, value: "long") -> None: # type: ignore # noqa: F821 """Check if value matches expected sum.""" assert value == self._sum_total @@ -52,7 +52,7 @@ def __init__(self, sum_total: int): """Initialize with expected sum.""" self._sum_total = sum_total - def __call__(self, value: "unsigned long") -> None: # type: ignore # noqa: F722 + def __call__(self, value: "unsigned long") -> None: # type: ignore # noqa: F722 """Check if value matches expected sum.""" assert value == self._sum_total @@ -80,7 +80,7 @@ def __init__(self, sum_total: float): """Initialize with expected sum.""" self._sum_total = sum_total - def __call__(self, value: "double") -> None: # type: ignore # noqa: F821 + def __call__(self, value: "double") -> None: # type: ignore # noqa: F821 """Check if value matches expected sum.""" assert abs(value - self._sum_total) < 1e-5