Skip to content

Commit 40821bf

Browse files
authored
Use the fallback for ModuleSpec early if it can never be resolved (#20167)
Fixes #18237.
1 parent 1b7e717 commit 40821bf

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

mypy/semanal.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -750,7 +750,15 @@ def add_implicit_module_attrs(self, file_node: MypyFile) -> None:
750750
else:
751751
inst = self.named_type_or_none("importlib.machinery.ModuleSpec")
752752
if inst is None:
753-
if self.final_iteration:
753+
if (
754+
self.final_iteration
755+
or self.options.clone_for_module("importlib.machinery").follow_imports
756+
== "skip"
757+
):
758+
# If we are not allowed to resolve imports from `importlib.machinery`,
759+
# ModuleSpec will not be available at any iteration.
760+
# Use the fallback earlier.
761+
# (see https://github.com/python/mypy/issues/18237)
754762
inst = self.named_type_or_none("builtins.object")
755763
assert inst is not None, "Cannot find builtins.object"
756764
else:

test-data/unit/cmdline.test

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1393,3 +1393,21 @@ Ts = TypeVarTuple("Ts")
13931393
Warning: TypeVarTuple is already enabled by default
13941394
Warning: Unpack is already enabled by default
13951395
== Return code: 0
1396+
1397+
[case testImportlibImportCannotBeResolved]
1398+
# cmd: mypy a.py
1399+
# This test is here because it needs use_builtins_fixtures off.
1400+
1401+
[file a.py]
1402+
from typing import NamedTuple
1403+
1404+
class CodecKey(NamedTuple):
1405+
def foo(self) -> "CodecKey":
1406+
...
1407+
1408+
[file mypy.ini]
1409+
\[mypy]
1410+
1411+
\[mypy-importlib.*]
1412+
follow_imports = skip
1413+
follow_imports_for_stubs = True

0 commit comments

Comments
 (0)