Manually add implicit definitions of module '__name__' etc.
(self, file_node: MypyFile)
| 734 | self.all_exports = [] |
| 735 | |
| 736 | def add_implicit_module_attrs(self, file_node: MypyFile) -> None: |
| 737 | """Manually add implicit definitions of module '__name__' etc.""" |
| 738 | str_type: Type | None = self.named_type_or_none("builtins.str") |
| 739 | if str_type is None: |
| 740 | str_type = UnboundType("builtins.str") |
| 741 | inst: Type | None |
| 742 | for name, t in implicit_module_attrs.items(): |
| 743 | if name == "__doc__": |
| 744 | typ: Type = str_type |
| 745 | elif name == "__path__": |
| 746 | if not file_node.is_package_init_file(): |
| 747 | continue |
| 748 | # Need to construct the type ourselves, to avoid issues with __builtins__.list |
| 749 | # not being subscriptable or typing.List not getting bound |
| 750 | inst = self.named_type_or_none("builtins.list", [str_type]) |
| 751 | if inst is None: |
| 752 | assert not self.final_iteration, "Cannot find builtins.list to add __path__" |
| 753 | self.defer() |
| 754 | return |
| 755 | typ = inst |
| 756 | elif name == "__annotations__": |
| 757 | inst = self.named_type_or_none( |
| 758 | "builtins.dict", [str_type, AnyType(TypeOfAny.special_form)] |
| 759 | ) |
| 760 | if inst is None: |
| 761 | assert ( |
| 762 | not self.final_iteration |
| 763 | ), "Cannot find builtins.dict to add __annotations__" |
| 764 | self.defer() |
| 765 | return |
| 766 | typ = inst |
| 767 | elif name == "__spec__": |
| 768 | if self.options.use_builtins_fixtures: |
| 769 | inst = self.named_type_or_none("builtins.object") |
| 770 | else: |
| 771 | inst = self.named_type_or_none("importlib.machinery.ModuleSpec") |
| 772 | if inst is None: |
| 773 | if ( |
| 774 | self.final_iteration |
| 775 | or self.options.clone_for_module("importlib.machinery").follow_imports |
| 776 | == "skip" |
| 777 | ): |
| 778 | # If we are not allowed to resolve imports from `importlib.machinery`, |
| 779 | # ModuleSpec will not be available at any iteration. |
| 780 | # Use the fallback earlier. |
| 781 | # (see https://github.com/python/mypy/issues/18237) |
| 782 | inst = self.named_type_or_none("builtins.object") |
| 783 | assert inst is not None, "Cannot find builtins.object" |
| 784 | else: |
| 785 | self.defer() |
| 786 | return |
| 787 | if file_node.name == "__main__": |
| 788 | # https://docs.python.org/3/reference/import.html#main-spec |
| 789 | inst = UnionType.make_union([inst, NoneType()]) |
| 790 | typ = inst |
| 791 | else: |
| 792 | assert t is not None, f"type should be specified for {name}" |
| 793 | typ = UnboundType(t) |
no test coverage detected