Skip to content

The agent that grows with you

fix(code-health): HX005 evaluates annotations when the interpreter does (F9)

Tekniumeb872c9ebba3
diff --git a/scripts/code_health/py_rules.py b/scripts/code_health/py_rules.py
index 202b71f118e..a6ccd4c36f7 100644
--- a/scripts/code_health/py_rules.py
+++ b/scripts/code_health/py_rules.py
@@ -412,12 +412,33 @@ def _import_time_statements(body: list[ast.stmt]) -> Iterator[ast.stmt]:
yield from _import_time_statements(block)
-def _import_time_exprs(stmt: ast.stmt) -> Iterator[ast.AST]:
- """What a statement evaluates at import, besides its nested blocks (walked separately)."""
+def _postponed_annotations(tree: ast.Module) -> bool:
+ return any(isinstance(stmt, ast.ImportFrom) and stmt.module == "__future__"
+ and any(alias.name == "annotations" for alias in stmt.names) for stmt in tree.body)
+
+
+def _annotations(func: ast.FunctionDef | ast.AsyncFunctionDef) -> list[ast.expr]:
+ args = func.args
+ params = [*args.posonlyargs, *args.args, *args.kwonlyargs, args.vararg, args.kwarg]
+ return [n for n in (*(p.annotation for p in params if p is not None), func.returns) if n is not None]
+
+
+def _import_time_exprs(stmt: ast.stmt, postponed: bool) -> Iterator[ast.AST]:
+ """What a statement evaluates at import, besides its nested blocks (walked separately).
+
+ Annotations of a def and of a module/class variable run at definition time on the
+ supported interpreters (3.11-3.13; 3.14 defers them, PEP 649) unless the module has
+ ``from __future__ import annotations``; an annotated assignment's value always runs."""
if isinstance(stmt, ast.ClassDef):
yield from (*stmt.decorator_list, *stmt.bases, *(kw.value for kw in stmt.keywords))
- elif isinstance(stmt, (ast.Assign, ast.AnnAssign, ast.AugAssign, *_FUNCS)):
+ elif isinstance(stmt, ast.AnnAssign):
+ yield from (n for n in (stmt.target, stmt.value) if n is not None)
+ if not postponed:
+ yield stmt.annotation
+ elif isinstance(stmt, (ast.Assign, ast.AugAssign, *_FUNCS)):
yield stmt # _eager keeps only a def's decorators and defaults
+ if isinstance(stmt, _FUNCS) and not postponed:
+ yield from _annotations(stmt)
elif isinstance(stmt, ast.Expr):
# A bare call is an action, not a capture; a walrus inside it binds a module name.
yield from (n for n in _eager(stmt.value) if isinstance(n, ast.NamedExpr))
@@ -433,8 +454,9 @@ def _import_time_exprs(stmt: ast.stmt) -> Iterator[ast.AST]:
def import_time_capture(tree: ast.Module, ctx: Ctx) -> Iterable[int]:
+ postponed = _postponed_annotations(tree)
for stmt in _import_time_statements(tree.body):
- for expr in _import_time_exprs(stmt):
+ for expr in _import_time_exprs(stmt, postponed):
yield from _capture_lines(expr)
diff --git a/tests/scripts/test_code_health_rules.py b/tests/scripts/test_code_health_rules.py
index 23e347ca250..7d6995f20e5 100644
--- a/tests/scripts/test_code_health_rules.py
+++ b/tests/scripts/test_code_health_rules.py
@@ -188,3 +188,24 @@ _GATHER = "import asyncio\n\n\nasync def run(awaitables, payloads):\n results
])
def test_gather_results_projection(ann, loop, flagged):
assert bool(_hits("HX009", _GATHER.format(ann=ann, loop=loop))) is flagged
+
+
+# --- HX005: annotations are evaluated at def time unless postponed ---
+
+_FUTURE = "from __future__ import annotations\n\n"
+
+
[email protected]("src, flagged", [
+ ("import os\n\n\ndef f(x: os.getenv('A')):\n return x\n", True),
+ ("import os\n\n\ndef f(x) -> os.getenv('A'):\n return x\n", True),
+ ("import os\n\n\nclass C:\n def f(self, *a: os.getenv('A')):\n return a\n", True),
+ (_FUTURE + "import os\n\n\ndef f(x: os.getenv('A')):\n return x\n", False),
+ (_FUTURE + "import os\n\n\ndef f(x) -> os.getenv('A'):\n return x\n", False),
+ (_FUTURE + "import os\n\nx: os.getenv('PATH')\n", False),
+ (_FUTURE + "import os\n\n\nclass C:\n x: os.getenv('PATH')\n", False),
+ (_FUTURE + "import os\n\nx: str = os.getenv('PATH')\n", True), # the value still runs
+ ("import os\n\nx: os.getenv('PATH')\n", True),
+ ("import os\n\n\ndef f():\n def g(x: os.getenv('A')):\n return x\n return g\n", False),
+])
+def test_annotation_evaluation_time(src, flagged):
+ assert bool(_hits("HX005", src)) is flagged, src