Skip to content

Commit 2ec8d2b

Browse files
chore: ruff auto-fix PLR6201 — tuple → set in membership tests (#23937)
Replace with for all literal-tuple membership tests. Set lookup is O(1) vs O(n) for tuple — consistent micro-optimization across the codebase. 608 instances fixed via `ruff --fix --unsafe-fixes`, 0 remaining. 133 files, +626/-626 (net zero).
1 parent 8c11710 commit 2ec8d2b

133 files changed

Lines changed: 626 additions & 626 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

acp_adapter/tools.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -769,8 +769,8 @@ def _build_patch_mode_content(patch_text: str) -> List[Any]:
769769
old_chunks: list[str] = []
770770
new_chunks: list[str] = []
771771
for hunk in op.hunks:
772-
old_lines = [line.content for line in hunk.lines if line.prefix in (" ", "-")]
773-
new_lines = [line.content for line in hunk.lines if line.prefix in (" ", "+")]
772+
old_lines = [line.content for line in hunk.lines if line.prefix in {" ", "-"}]
773+
new_lines = [line.content for line in hunk.lines if line.prefix in {" ", "+"}]
774774
if old_lines or new_lines:
775775
old_chunks.append("\n".join(old_lines))
776776
new_chunks.append("\n".join(new_lines))

agent/account_usage.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def _title_case_slug(value: Optional[str]) -> Optional[str]:
4747

4848

4949
def _parse_dt(value: Any) -> Optional[datetime]:
50-
if value in (None, ""):
50+
if value in {None, ""}:
5151
return None
5252
if isinstance(value, (int, float)):
5353
return datetime.fromtimestamp(float(value), tz=timezone.utc)

agent/anthropic_adapter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1537,7 +1537,7 @@ def convert_messages_to_anthropic(
15371537
# downgraded to a spurious text block on the last assistant message.
15381538
reasoning_content = m.get("reasoning_content")
15391539
_already_has_thinking = any(
1540-
isinstance(b, dict) and b.get("type") in ("thinking", "redacted_thinking")
1540+
isinstance(b, dict) and b.get("type") in {"thinking", "redacted_thinking"}
15411541
for b in blocks
15421542
)
15431543
if isinstance(reasoning_content, str) and not _already_has_thinking:
@@ -1688,7 +1688,7 @@ def convert_messages_to_anthropic(
16881688
if isinstance(m["content"], list):
16891689
m["content"] = [
16901690
b for b in m["content"]
1691-
if not (isinstance(b, dict) and b.get("type") in ("thinking", "redacted_thinking"))
1691+
if not (isinstance(b, dict) and b.get("type") in {"thinking", "redacted_thinking"})
16921692
]
16931693
prev_blocks = fixed[-1]["content"]
16941694
curr_blocks = m["content"]

agent/auxiliary_client.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ def _normalize_aux_provider(provider: Optional[str]) -> str:
175175
# Resolve to the user's actual main provider so named custom providers
176176
# and non-aggregator providers (DeepSeek, Alibaba, etc.) work correctly.
177177
main_prov = (_read_main_provider() or "").strip().lower()
178-
if main_prov and main_prov not in ("auto", "main", ""):
178+
if main_prov and main_prov not in {"auto", "main", ""}:
179179
normalized = main_prov
180180
else:
181181
return "custom"
@@ -578,7 +578,7 @@ def _convert_content_for_responses(content: Any) -> Any:
578578
if detail:
579579
entry["detail"] = detail
580580
converted.append(entry)
581-
elif ptype in ("input_text", "input_image"):
581+
elif ptype in {"input_text", "input_image"}:
582582
# Already in Responses format — pass through
583583
converted.append(part)
584584
else:
@@ -798,7 +798,7 @@ def _item_get(obj: Any, key: str, default: Any = None) -> Any:
798798
if item_type == "message":
799799
for part in (_item_get(item, "content") or []):
800800
ptype = _item_get(part, "type")
801-
if ptype in ("output_text", "text"):
801+
if ptype in {"output_text", "text"}:
802802
text_parts.append(_item_get(part, "text", ""))
803803
elif item_type == "function_call":
804804
tool_calls_raw.append(SimpleNamespace(
@@ -1960,7 +1960,7 @@ def _is_payment_error(exc: Exception) -> bool:
19601960
err_lower = str(exc).lower()
19611961
# OpenRouter and other providers include "credits" or "afford" in 402 bodies,
19621962
# but sometimes wrap them in 429 or other codes.
1963-
if status in (402, 429, None):
1963+
if status in {402, 429, None}:
19641964
if any(kw in err_lower for kw in ("credits", "insufficient funds",
19651965
"can only afford", "billing",
19661966
"payment required")):
@@ -2157,7 +2157,7 @@ def _pool_cache_hint(
21572157
if normalized == "auto":
21582158
runtime = _normalize_main_runtime(main_runtime)
21592159
normalized = _normalize_aux_provider(runtime.get("provider") or _read_main_provider())
2160-
if normalized in ("", "auto", "custom"):
2160+
if normalized in {"", "auto", "custom"}:
21612161
return ""
21622162
entry = _peek_pool_entry(normalized)
21632163
if entry is None:
@@ -2179,7 +2179,7 @@ def _pool_error_context(exc: Exception) -> Dict[str, Any]:
21792179
def _recoverable_pool_provider(resolved_provider: str, client: Any) -> Optional[str]:
21802180
"""Infer which provider pool can recover the current auxiliary client."""
21812181
normalized = _normalize_aux_provider(resolved_provider)
2182-
if normalized not in ("", "auto", "custom"):
2182+
if normalized not in {"", "auto", "custom"}:
21832183
return normalized
21842184
base = str(getattr(client, "base_url", "") or "")
21852185
if base_url_host_matches(base, "chatgpt.com"):
@@ -2496,7 +2496,7 @@ def _resolve_auto(main_runtime: Optional[Dict[str, Any]] = None) -> Tuple[Option
24962496
main_provider = runtime_provider or _read_main_provider()
24972497
main_model = runtime_model or _read_main_model()
24982498
if (main_provider and main_model
2499-
and main_provider not in ("auto", "")):
2499+
and main_provider not in {"auto", ""}):
25002500
resolved_provider = main_provider
25012501
explicit_base_url = None
25022502
explicit_api_key = None
@@ -3157,7 +3157,7 @@ def _wrap_if_needed(client_obj, final_model_str: str, base_url_str: str = "",
31573157
return (_to_async_client(client, final_model, is_vision=is_vision) if async_mode
31583158
else (client, final_model))
31593159

3160-
elif pconfig.auth_type in ("oauth_device_code", "oauth_external"):
3160+
elif pconfig.auth_type in {"oauth_device_code", "oauth_external"}:
31613161
# OAuth providers — route through their specific try functions
31623162
if provider == "nous":
31633163
return resolve_provider_client("nous", model, async_mode)
@@ -3266,7 +3266,7 @@ def get_available_vision_backends() -> List[str]:
32663266
available: List[str] = []
32673267
# 1. Active provider — if the user configured a provider, try it first.
32683268
main_provider = _read_main_provider()
3269-
if main_provider and main_provider not in ("auto", ""):
3269+
if main_provider and main_provider not in {"auto", ""}:
32703270
if main_provider in _VISION_AUTO_PROVIDER_ORDER:
32713271
if _strict_vision_backend_available(main_provider):
32723272
available.append(main_provider)
@@ -3312,7 +3312,7 @@ def _finalize(resolved_provider: str, sync_client: Any, default_model: Optional[
33123312

33133313
if resolved_base_url:
33143314
provider_for_base_override = (
3315-
requested if requested and requested not in ("", "auto") else "custom"
3315+
requested if requested and requested not in {"", "auto"} else "custom"
33163316
)
33173317
client, final_model = resolve_provider_client(
33183318
provider_for_base_override,
@@ -3340,7 +3340,7 @@ def _finalize(resolved_provider: str, sync_client: Any, default_model: Optional[
33403340
# 4. Stop
33413341
main_provider = _read_main_provider()
33423342
main_model = _read_main_model()
3343-
if main_provider and main_provider not in ("auto", ""):
3343+
if main_provider and main_provider not in {"auto", ""}:
33443344
vision_model = _PROVIDER_VISION_MODELS.get(main_provider, main_model)
33453345
if main_provider == "nous":
33463346
sync_client, default_model = _resolve_strict_vision_backend(
@@ -4146,7 +4146,7 @@ def call_llm(
41464146
# credentials were found, fail fast instead of silently routing
41474147
# through OpenRouter (which causes confusing 404s).
41484148
_explicit = (resolved_provider or "").strip().lower()
4149-
if _explicit and _explicit not in ("auto", "openrouter", "custom"):
4149+
if _explicit and _explicit not in {"auto", "openrouter", "custom"}:
41504150
raise RuntimeError(
41514151
f"Provider '{_explicit}' is set in config.yaml but no API key "
41524152
f"was found. Set the {_explicit.upper()}_API_KEY environment "
@@ -4276,7 +4276,7 @@ def call_llm(
42764276

42774277
# ── Auth refresh retry ───────────────────────────────────────
42784278
if (_is_auth_error(first_err)
4279-
and resolved_provider not in ("auto", "", None)
4279+
and resolved_provider not in {"auto", "", None}
42804280
and not client_is_nous):
42814281
if _refresh_provider_credentials(resolved_provider):
42824282
logger.info(
@@ -4359,7 +4359,7 @@ def call_llm(
43594359
# Only try alternative providers when the user didn't explicitly
43604360
# configure this task's provider. Explicit provider = hard constraint;
43614361
# auto (the default) = best-effort fallback chain. (#7559)
4362-
is_auto = resolved_provider in ("auto", "", None)
4362+
is_auto = resolved_provider in {"auto", "", None}
43634363
if should_fallback and is_auto:
43644364
if _is_payment_error(first_err):
43654365
reason = "payment error"
@@ -4515,7 +4515,7 @@ async def async_call_llm(
45154515
)
45164516
if client is None:
45174517
_explicit = (resolved_provider or "").strip().lower()
4518-
if _explicit and _explicit not in ("auto", "openrouter", "custom"):
4518+
if _explicit and _explicit not in {"auto", "openrouter", "custom"}:
45194519
raise RuntimeError(
45204520
f"Provider '{_explicit}' is set in config.yaml but no API key "
45214521
f"was found. Set the {_explicit.upper()}_API_KEY environment "
@@ -4626,7 +4626,7 @@ async def async_call_llm(
46264626

46274627
# ── Auth refresh retry (mirrors sync call_llm) ───────────────
46284628
if (_is_auth_error(first_err)
4629-
and resolved_provider not in ("auto", "", None)
4629+
and resolved_provider not in {"auto", "", None}
46304630
and not client_is_nous):
46314631
if _refresh_provider_credentials(resolved_provider):
46324632
logger.info(
@@ -4688,7 +4688,7 @@ async def async_call_llm(
46884688
or _is_connection_error(first_err)
46894689
or _is_rate_limit_error(first_err)
46904690
)
4691-
is_auto = resolved_provider in ("auto", "", None)
4691+
is_auto = resolved_provider in {"auto", "", None}
46924692
if should_fallback and is_auto:
46934693
if _is_payment_error(first_err):
46944694
reason = "payment error"

agent/context_compressor.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ def _strip_image_parts_from_parts(parts: Any) -> Any:
167167
out.append(part)
168168
continue
169169
ptype = part.get("type")
170-
if ptype in ("image", "image_url", "input_image"):
170+
if ptype in {"image", "image_url", "input_image"}:
171171
had_image = True
172172
out.append({"type": "text", "text": "[screenshot removed to save context]"})
173173
else:
@@ -274,8 +274,8 @@ def _summarize_tool_result(tool_name: str, tool_args: str, tool_content: str) ->
274274
mode = args.get("mode", "replace")
275275
return f"[patch] {mode} in {path} ({content_len:,} chars result)"
276276

277-
if tool_name in ("browser_navigate", "browser_click", "browser_snapshot",
278-
"browser_type", "browser_scroll", "browser_vision"):
277+
if tool_name in {"browser_navigate", "browser_click", "browser_snapshot",
278+
"browser_type", "browser_scroll", "browser_vision"}:
279279
url = args.get("url", "")
280280
ref = args.get("ref", "")
281281
detail = f" {url}" if url else (f" ref={ref}" if ref else "")
@@ -304,7 +304,7 @@ def _summarize_tool_result(tool_name: str, tool_args: str, tool_content: str) ->
304304
code_preview += "..."
305305
return f"[execute_code] `{code_preview}` ({line_count} lines output)"
306306

307-
if tool_name in ("skill_view", "skills_list", "skill_manage"):
307+
if tool_name in {"skill_view", "skills_list", "skill_manage"}:
308308
name = args.get("name", "?")
309309
return f"[{tool_name}] name={name} ({content_len:,} chars)"
310310

@@ -979,13 +979,13 @@ def _generate_summary(self, turns_to_summarize: List[Dict[str, Any]], focus_topi
979979
_status = getattr(e, "status_code", None) or getattr(getattr(e, "response", None), "status_code", None)
980980
_err_str = str(e).lower()
981981
_is_model_not_found = (
982-
_status in (404, 503)
982+
_status in {404, 503}
983983
or "model_not_found" in _err_str
984984
or "does not exist" in _err_str
985985
or "no available channel" in _err_str
986986
)
987987
_is_timeout = (
988-
_status in (408, 429, 502, 504)
988+
_status in {408, 429, 502, 504}
989989
or "timeout" in _err_str
990990
)
991991
# Non-JSON / malformed-body responses from misconfigured providers
@@ -1479,7 +1479,7 @@ def compress(self, messages: List[Dict[str, Any]], current_tokens: int = None, f
14791479
first_tail_role = messages[compress_end].get("role", "user") if compress_end < n_messages else "user"
14801480
# Pick a role that avoids consecutive same-role with both neighbors.
14811481
# Priority: avoid colliding with head (already committed), then tail.
1482-
if last_head_role in ("assistant", "tool"):
1482+
if last_head_role in {"assistant", "tool"}:
14831483
summary_role = "user"
14841484
else:
14851485
summary_role = "assistant"

agent/credential_pool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ def to_dict(self) -> Dict[str, Any]:
149149
}
150150
result: Dict[str, Any] = {}
151151
for field_def in fields(self):
152-
if field_def.name in ("provider", "extra"):
152+
if field_def.name in {"provider", "extra"}:
153153
continue
154154
value = getattr(self, field_def.name)
155155
if value is not None or field_def.name in _ALWAYS_EMIT:

agent/error_classifier.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class ClassifiedError:
8383

8484
@property
8585
def is_auth(self) -> bool:
86-
return self.reason in (FailoverReason.auth, FailoverReason.auth_permanent)
86+
return self.reason in {FailoverReason.auth, FailoverReason.auth_permanent}
8787

8888

8989

@@ -688,10 +688,10 @@ def _classify_by_status(
688688
result_fn=result_fn,
689689
)
690690

691-
if status_code in (500, 502):
691+
if status_code in {500, 502}:
692692
return result_fn(FailoverReason.server_error, retryable=True)
693693

694-
if status_code in (503, 529):
694+
if status_code in {503, 529}:
695695
return result_fn(FailoverReason.overloaded, retryable=True)
696696

697697
# Other 4xx — non-retryable
@@ -810,7 +810,7 @@ def _classify_400(
810810
# Responses API (and some providers) use flat body: {"message": "..."}
811811
if not err_body_msg:
812812
err_body_msg = str(body.get("message") or "").strip().lower()
813-
is_generic = len(err_body_msg) < 30 or err_body_msg in ("error", "")
813+
is_generic = len(err_body_msg) < 30 or err_body_msg in {"error", ""}
814814
# Absolute token/message-count thresholds are only a proxy for smaller
815815
# context windows. Large-context sessions can have many messages while
816816
# still being far below their actual token budget.
@@ -841,29 +841,29 @@ def _classify_by_error_code(
841841
"""Classify by structured error codes from the response body."""
842842
code_lower = error_code.lower()
843843

844-
if code_lower in ("resource_exhausted", "throttled", "rate_limit_exceeded"):
844+
if code_lower in {"resource_exhausted", "throttled", "rate_limit_exceeded"}:
845845
return result_fn(
846846
FailoverReason.rate_limit,
847847
retryable=True,
848848
should_rotate_credential=True,
849849
)
850850

851-
if code_lower in ("insufficient_quota", "billing_not_active", "payment_required"):
851+
if code_lower in {"insufficient_quota", "billing_not_active", "payment_required"}:
852852
return result_fn(
853853
FailoverReason.billing,
854854
retryable=False,
855855
should_rotate_credential=True,
856856
should_fallback=True,
857857
)
858858

859-
if code_lower in ("model_not_found", "model_not_available", "invalid_model"):
859+
if code_lower in {"model_not_found", "model_not_available", "invalid_model"}:
860860
return result_fn(
861861
FailoverReason.model_not_found,
862862
retryable=False,
863863
should_fallback=True,
864864
)
865865

866-
if code_lower in ("context_length_exceeded", "max_tokens_exceeded"):
866+
if code_lower in {"context_length_exceeded", "max_tokens_exceeded"}:
867867
return result_fn(
868868
FailoverReason.context_overflow,
869869
retryable=True,

agent/gemini_cloudcode_adapter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def _coerce_content_to_text(content: Any) -> str:
7777
if p.get("type") == "text" and isinstance(p.get("text"), str):
7878
pieces.append(p["text"])
7979
# Multimodal (image_url, etc.) — stub for now; log and skip
80-
elif p.get("type") in ("image_url", "input_audio"):
80+
elif p.get("type") in {"image_url", "input_audio"}:
8181
logger.debug("Dropping multimodal part (not yet supported): %s", p.get("type"))
8282
return "\n".join(pieces)
8383
return str(content)

agent/image_routing.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def _explicit_aux_vision_override(cfg: Optional[Dict[str, Any]]) -> bool:
7676
base_url = str(vision.get("base_url") or "").strip()
7777

7878
# "auto" / "" / blank = not explicit
79-
if provider in ("", "auto") and not model and not base_url:
79+
if provider in {"", "auto"} and not model and not base_url:
8080
return False
8181
return True
8282

@@ -163,7 +163,7 @@ def _sniff_mime_from_bytes(raw: bytes) -> Optional[str]:
163163
if raw.startswith(b"\xff\xd8\xff"):
164164
return "image/jpeg"
165165
# GIF87a / GIF89a
166-
if raw[:6] in (b"GIF87a", b"GIF89a"):
166+
if raw[:6] in {b"GIF87a", b"GIF89a"}:
167167
return "image/gif"
168168
# WEBP: "RIFF" .... "WEBP"
169169
if len(raw) >= 12 and raw[:4] == b"RIFF" and raw[8:12] == b"WEBP":
@@ -172,9 +172,9 @@ def _sniff_mime_from_bytes(raw: bytes) -> Optional[str]:
172172
if raw.startswith(b"BM"):
173173
return "image/bmp"
174174
# HEIC/HEIF: ftypheic / ftypheix / ftypmif1 / ftypmsf1 etc.
175-
if len(raw) >= 12 and raw[4:8] == b"ftyp" and raw[8:12] in (
175+
if len(raw) >= 12 and raw[4:8] == b"ftyp" and raw[8:12] in {
176176
b"heic", b"heix", b"hevc", b"hevx", b"mif1", b"msf1", b"heim", b"heis",
177-
):
177+
}:
178178
return "image/heic"
179179
return None
180180

agent/memory_manager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -470,11 +470,11 @@ def _provider_memory_write_metadata_mode(provider: MemoryProvider) -> str:
470470

471471
accepted = [
472472
p for p in params
473-
if p.kind in (
473+
if p.kind in {
474474
inspect.Parameter.POSITIONAL_ONLY,
475475
inspect.Parameter.POSITIONAL_OR_KEYWORD,
476476
inspect.Parameter.KEYWORD_ONLY,
477-
)
477+
}
478478
]
479479
if len(accepted) >= 4:
480480
return "positional"

0 commit comments

Comments
 (0)