The list of required import lines (as strings with python code). In order for a module be included in this output, an identifier must be both 'required' via require_name() and 'imported' via add_import_from() or add_import()
(self)
| 529 | self.reexports.add(name) |
| 530 | |
| 531 | def import_lines(self) -> list[str]: |
| 532 | """The list of required import lines (as strings with python code). |
| 533 | |
| 534 | In order for a module be included in this output, an identifier must be both |
| 535 | 'required' via require_name() and 'imported' via add_import_from() |
| 536 | or add_import() |
| 537 | """ |
| 538 | result = [] |
| 539 | |
| 540 | # To summarize multiple names imported from a same module, we collect those |
| 541 | # in the `module_map` dictionary, mapping a module path to the list of names that should |
| 542 | # be imported from it. the names can also be alias in the form 'original as alias' |
| 543 | module_map: Mapping[str, list[str]] = defaultdict(list) |
| 544 | |
| 545 | for name in sorted( |
| 546 | self.required_names, |
| 547 | key=lambda n: (self.reverse_alias[n], n) if n in self.reverse_alias else (n, ""), |
| 548 | ): |
| 549 | # If we haven't seen this name in an import statement, ignore it |
| 550 | if name not in self.module_for: |
| 551 | continue |
| 552 | |
| 553 | m = self.module_for[name] |
| 554 | if m is not None: |
| 555 | # This name was found in a from ... import ... |
| 556 | # Collect the name in the module_map |
| 557 | if name in self.reverse_alias: |
| 558 | name = f"{self.reverse_alias[name]} as {name}" |
| 559 | elif name in self.reexports: |
| 560 | name = f"{name} as {name}" |
| 561 | module_map[m].append(name) |
| 562 | else: |
| 563 | # This name was found in an import ... |
| 564 | # We can already generate the import line |
| 565 | if name in self.reverse_alias: |
| 566 | source = self.reverse_alias[name] |
| 567 | result.append(f"import {source} as {name}\n") |
| 568 | elif name in self.reexports: |
| 569 | assert "." not in name # Because reexports only has nonqualified names |
| 570 | result.append(f"import {name} as {name}\n") |
| 571 | else: |
| 572 | result.append(f"import {name}\n") |
| 573 | |
| 574 | # Now generate all the from ... import ... lines collected in module_map |
| 575 | for module, names in sorted(module_map.items()): |
| 576 | result.append(f"from {module} import {', '.join(sorted(names))}\n") |
| 577 | return result |
| 578 | |
| 579 | |
| 580 | @mypyc_attr(allow_interpreted_subclasses=True) |
no test coverage detected