MCPcopy Index your code
hub / github.com/python/mypy / format_reachable_imports

Function format_reachable_imports

mypy/test/test_nativeparse.py:165–232  ·  view source on GitHub ↗

Format reachable imports from a MypyFile node. Returns a list of strings representing reachable imports with line numbers and flags.

(node: MypyFile)

Source from the content-addressed store, hash-verified

163
164
165def format_reachable_imports(node: MypyFile) -> list[str]:
166 """Format reachable imports from a MypyFile node.
167
168 Returns a list of strings representing reachable imports with line numbers and flags.
169 """
170 from mypy.nodes import Import, ImportAll, ImportFrom
171
172 output: list[str] = []
173
174 # Filter for reachable imports (is_unreachable == False)
175 reachable_imports = [imp for imp in node.imports if not imp.is_unreachable]
176
177 for imp in reachable_imports:
178 line_num = imp.line
179
180 # Collect flags (only show when flag is False/not set)
181 flags = []
182 if not imp.is_top_level:
183 flags.append("not top_level")
184 if imp.is_mypy_only:
185 flags.append("mypy_only")
186
187 flags_str = " [" + ", ".join(flags) + "]" if flags else ""
188
189 if isinstance(imp, Import):
190 # Format: line: import foo [as bar] [flags]
191 for module_id, as_id in imp.ids:
192 if as_id:
193 output.append(f"{line_num}: import {module_id} as {as_id}{flags_str}")
194 else:
195 output.append(f"{line_num}: import {module_id}{flags_str}")
196 elif isinstance(imp, ImportFrom):
197 # Format: line: from foo import bar, baz [as b] [flags]
198 # Handle relative imports
199 if imp.relative > 0:
200 prefix = "." * imp.relative
201 if imp.id:
202 module = f"{prefix}{imp.id}"
203 else:
204 module = prefix
205 else:
206 module = imp.id
207
208 # Group all names together
209 name_parts = []
210 for name, as_name in imp.names:
211 if as_name:
212 name_parts.append(f"{name} as {as_name}")
213 else:
214 name_parts.append(name)
215
216 names_str = ", ".join(name_parts)
217 output.append(f"{line_num}: from {module} import {names_str}{flags_str}")
218 elif isinstance(imp, ImportAll):
219 # Format: line: from foo import * [flags]
220 # Handle relative imports
221 if imp.relative > 0:
222 prefix = "." * imp.relative

Callers 1

test_parser_importsFunction · 0.85

Calls 3

isinstanceFunction · 0.85
appendMethod · 0.80
joinMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…