Coverage for scripts/type_completeness.py: 100%

99 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Type completeness of the public library (V6.6.5, #346): every callable `aether_quant` exports, fully annotated. 

2 

3A callable counts as complete when every parameter (bar `self`/`cls`) and its return carry an annotation and none of them 

4is a bare container (`dict`, `list`, `tuple`, `set`, `Mapping`, `Sequence`, `Callable`, ... without parameters), which a 

5type checker reads as "of Unknown". A class counts through its public methods (and an explicit `__init__`); dataclass 

6fields are annotated by construction. Imports nothing heavy: the facades load as the lite install does. 

7 

8The score may only rise: `tests/data/type_completeness_floor.json` holds the floor and the names still incomplete, and 

9this exits 1 when the score falls below the floor or a new incomplete name appears. 

10 

11 python scripts/type_completeness.py # check against the floor 

12 python scripts/type_completeness.py --report FILE # also write every incomplete name and why 

13 python scripts/type_completeness.py --update-floor # after a fix: raise the floor, shrink the list 

14""" 

15 

16from __future__ import annotations 

17 

18import argparse 

19import dataclasses 

20import importlib 

21import inspect 

22import json 

23import re 

24import sys 

25from pathlib import Path 

26 

27ROOT = Path(__file__).resolve().parents[1] 

28sys.path.insert(0, str(ROOT)) 

29FLOOR = ROOT / "tests" / "data" / "type_completeness_floor.json" 

30BARE = re.compile(r"^(typing\.)?(dict|list|tuple|set|frozenset|Dict|List|Tuple|Set|FrozenSet|Mapping|MutableMapping|Sequence|Iterable|Iterator|Callable)$") 

31 

32 

33def facade_modules() -> list[str]: 

34 return sorted(path.stem for path in (ROOT / "aether_quant").glob("*.py") if not path.stem.startswith("_")) 

35 

36 

37def _annotation_text(annotation: object) -> str: 

38 if annotation is inspect.Parameter.empty: 

39 return "" 

40 return annotation if isinstance(annotation, str) else getattr(annotation, "__name__", None) or str(annotation) 

41 

42 

43def _problems_of_function(function: object) -> list[str]: 

44 try: 

45 signature = inspect.signature(function) # type: ignore[arg-type] 

46 except (TypeError, ValueError): 

47 return [] # a C builtin or an object without a signature: nothing to annotate 

48 problems = [] 

49 for name, parameter in signature.parameters.items(): 

50 if name in ("self", "cls"): 

51 continue 

52 text = _annotation_text(parameter.annotation).strip() 

53 if not text: 

54 problems.append(f"parameter {name} has no annotation") 

55 elif BARE.match(text.replace(" ", "")): 

56 problems.append(f"parameter {name} is a bare {text}") 

57 returned = _annotation_text(signature.return_annotation).strip() 

58 if not returned: 

59 problems.append("no return annotation") 

60 elif BARE.match(returned.replace(" ", "")): 

61 problems.append(f"return is a bare {returned}") 

62 return problems 

63 

64 

65def _problems_of_class(cls: type) -> list[str]: 

66 problems = [] 

67 # a dataclass's __init__ is generated from its annotated fields; a Protocol's is typing's placeholder 

68 generated_init = dataclasses.is_dataclass(cls) or bool(getattr(cls, "_is_protocol", False)) 

69 for name, member in vars(cls).items(): 

70 if name.startswith("_") and not (name == "__init__" and not generated_init): 

71 continue 

72 target = member.__func__ if isinstance(member, (classmethod, staticmethod)) else member 

73 if isinstance(target, property): 

74 target = target.fget 

75 if inspect.isfunction(target): 

76 problems += [f"{name}: {problem}" for problem in _problems_of_function(target)] 

77 return problems 

78 

79 

80def measure() -> dict[str, object]: 

81 """{"score", "complete", "total", "incomplete": {qualified name: [problems]}}, over every exported callable.""" 

82 seen: dict[int, str] = {} 

83 incomplete: dict[str, list[str]] = {} 

84 total = 0 

85 for module_name in facade_modules(): 

86 module = importlib.import_module(f"aether_quant.{module_name}") 

87 for name in getattr(module, "__all__", []): 

88 try: 

89 obj = getattr(module, name, None) 

90 except ImportError: # a lazy export whose optional dependency (torch) is not installed here 

91 continue 

92 if obj is None or not (inspect.isfunction(obj) or inspect.isclass(obj)) or id(obj) in seen: 

93 continue 

94 qualified = f"{getattr(obj, '__module__', '?')}.{getattr(obj, '__qualname__', name)}" 

95 seen[id(obj)] = qualified 

96 total += 1 

97 problems = _problems_of_class(obj) if inspect.isclass(obj) else _problems_of_function(obj) 

98 if problems: 

99 incomplete[qualified] = problems 

100 complete = total - len(incomplete) 

101 return {"score": round(complete / total, 4) if total else 1.0, "complete": complete, "total": total, "incomplete": dict(sorted(incomplete.items()))} 

102 

103 

104def main(argv: list[str] | None = None) -> int: 

105 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

106 parser.add_argument("--report", default=None, metavar="FILE") 

107 parser.add_argument("--update-floor", action="store_true") 

108 args = parser.parse_args(argv) 

109 result = measure() 

110 print(f"type completeness: {result['complete']}/{result['total']} exported callables fully annotated ({float(result['score']):.1%})") 

111 if args.report: 

112 Path(args.report).write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8") 

113 if args.update_floor: 

114 FLOOR.write_text(json.dumps({"floor": result["score"], "incomplete": sorted(result["incomplete"])}, indent=1) + "\n", encoding="utf-8", newline="\n") 

115 print(f"floor set to {float(result['score']):.1%} with {len(result['incomplete'])} names still incomplete") 

116 return 0 

117 floor = json.loads(FLOOR.read_text(encoding="utf-8")) if FLOOR.exists() else {"floor": 0.0, "incomplete": []} 

118 problems = [] 

119 if float(result["score"]) < float(floor["floor"]): 

120 problems.append(f"score {float(result['score']):.1%} fell below the floor {float(floor['floor']):.1%}") 

121 new = sorted(set(result["incomplete"]) - set(floor["incomplete"])) 

122 problems += [f"{name}: {'; '.join(result['incomplete'][name])}" for name in new] # type: ignore[index] 

123 fixed = sorted(set(floor["incomplete"]) - set(result["incomplete"])) 

124 if fixed: 

125 print(f"{len(fixed)} name(s) now complete: run with --update-floor to lock the gain") 

126 for problem in problems: 

127 print(f"type completeness: {problem}", file=sys.stderr) 

128 return 1 if problems else 0 

129 

130 

131if __name__ == "__main__": 

132 raise SystemExit(main())