Skip to content

The agent that grows with you

fix(code-health): a parameter annotated as a process is an HX006 handle

Teknium8a0e27697c53
diff --git a/scripts/code_health/py_rules.py b/scripts/code_health/py_rules.py
index 29e951655c0..187418ac37c 100644
--- a/scripts/code_health/py_rules.py
+++ b/scripts/code_health/py_rules.py
@@ -618,14 +618,24 @@ class _HandleScope:
return None
+# A parameter annotated as a process is one (``proc: subprocess.Popen[str]``).
+_PROCESS_TYPES = {"subprocess.Popen": "sync", "asyncio.subprocess.Process": "async"}
+
+
+def _annotated_kind(annotation: ast.expr | None) -> str | None:
+ if isinstance(annotation, ast.Subscript):
+ annotation = annotation.value
+ return _PROCESS_TYPES.get(_dotted(annotation)) if annotation is not None else None
+
+
def _record_bindings(scope: _HandleScope, node: ast.AST, attrs: dict[tuple[int, str], str]) -> None:
- """Any binding of a plain name clears it (a parameter, a loop variable, ``proc = None``);
- a spawn makes it a handle once the value is computed. An attribute handle is shared by
+ """Any binding of a plain name clears it (a loop variable, ``proc = None``, a parameter
+ not annotated as a process); a spawn makes it a handle once the value is computed. An attribute handle is shared by
the class's methods, so it is keyed by the class, not by the function that assigns it."""
if isinstance(node, ast.Name) and not isinstance(node.ctx, ast.Load):
scope.names.setdefault(node.id, []).append((_pos(node), None))
elif isinstance(node, ast.arg):
- scope.names.setdefault(node.arg, []).append((_pos(node), None))
+ scope.names.setdefault(node.arg, []).append((_pos(node), _annotated_kind(node.annotation)))
for target, value in _binding_pairs(node):
kind = _spawn_kind(value)
if kind is None or value is None:
diff --git a/tests/scripts/test_code_health_rules.py b/tests/scripts/test_code_health_rules.py
index 74ee2f1fe39..b0a31863ecd 100644
--- a/tests/scripts/test_code_health_rules.py
+++ b/tests/scripts/test_code_health_rules.py
@@ -126,6 +126,12 @@ def test_process_handle_follows_reassignment():
# a parameter that merely shares the spelling is not the other function's process
param = unbounded + "\n\ndef stop(proc):\n return proc.wait()\n"
assert _hits("HX006", param) == [6]
+ # ...but one annotated as a process is a process
+ typed = param.replace("def stop(proc):", "def stop(proc: subprocess.Popen[str]):")
+ assert _hits("HX006", typed) == [6, 10]
+ typed_async = ("import asyncio\n\n\nasync def stop(proc: asyncio.subprocess.Process):\n"
+ " return await proc.wait()\n")
+ assert _hits("HX006", typed_async) == [5]
def test_process_handle_on_an_attribute_spans_the_class_methods():