Parse deterministic Python import aliases from one source file. Supported forms: from helper import transform from helper import transform as tx from .helper import transform The function deliberately does not resolve plain ``import helper`` member calls because
(path: Path)
| 146 | |
| 147 | |
| 148 | def parse_python_import_aliases(path: Path) -> dict[str, ImportedSymbol]: |
| 149 | """Parse deterministic Python import aliases from one source file. |
| 150 | |
| 151 | Supported forms: |
| 152 | from helper import transform |
| 153 | from helper import transform as tx |
| 154 | from .helper import transform |
| 155 | |
| 156 | The function deliberately does not resolve plain ``import helper`` member |
| 157 | calls because current raw call records do not preserve the receiver name from |
| 158 | ``helper.transform()``. That can be added later only after raw call facts are |
| 159 | extended to include the receiver expression. |
| 160 | """ |
| 161 | |
| 162 | try: |
| 163 | source = _read_source_text(path, warn=False) |
| 164 | tree = ast.parse(source) |
| 165 | except (OSError, SyntaxError): |
| 166 | return {} |
| 167 | |
| 168 | aliases: dict[str, ImportedSymbol] = {} |
| 169 | source_file = str(path) |
| 170 | |
| 171 | # Only top-level `from ... import ...` statements count as file-wide |
| 172 | # evidence. Nested/function-local imports do NOT — they're only valid |
| 173 | # inside their lexical scope, and our raw-call records don't currently |
| 174 | # carry enough scope info to match the import site safely. Walking |
| 175 | # ast.walk(tree) would incorrectly justify calls in other scopes. |
| 176 | for node in tree.body: |
| 177 | if not isinstance(node, ast.ImportFrom): |
| 178 | continue |
| 179 | module_stem = _module_stem(node.module) |
| 180 | if not module_stem: |
| 181 | continue |
| 182 | for alias in node.names: |
| 183 | if alias.name == "*": |
| 184 | continue |
| 185 | local_name = alias.asname or alias.name |
| 186 | aliases[local_name] = ImportedSymbol( |
| 187 | local_name=local_name, |
| 188 | imported_name=alias.name, |
| 189 | module_stem=module_stem, |
| 190 | source_file=source_file, |
| 191 | source_location=f"L{getattr(node, 'lineno', 1)}", |
| 192 | ) |
| 193 | |
| 194 | return aliases |
| 195 | |
| 196 | |
| 197 | def _node_source_stem(node: dict[str, Any]) -> str: |