Return imported module names that aren't in the Python stdlib.
(script: Path)
| 256 | |
| 257 | |
| 258 | def _non_stdlib_imports(script: Path) -> set[str]: |
| 259 | """Return imported module names that aren't in the Python stdlib.""" |
| 260 | try: |
| 261 | tree = ast.parse(script.read_text(encoding="utf-8")) |
| 262 | except SyntaxError: |
| 263 | return {"<syntax-error>"} |
| 264 | stdlib = set(sys.stdlib_module_names) if hasattr(sys, "stdlib_module_names") else set() |
| 265 | bad: set[str] = set() |
| 266 | for node in ast.walk(tree): |
| 267 | if isinstance(node, ast.Import): |
| 268 | for alias in node.names: |
| 269 | root = alias.name.split(".")[0] |
| 270 | if stdlib and root not in stdlib: |
| 271 | bad.add(root) |
| 272 | elif isinstance(node, ast.ImportFrom): |
| 273 | if node.module: |
| 274 | root = node.module.split(".")[0] |
| 275 | if stdlib and root not in stdlib: |
| 276 | bad.add(root) |
| 277 | return bad |