Skip to content

Commit 4518b55

Browse files
authored
Don't use Python 3 stdlib stubs in Python 2 mode (#10422)
Previously we could find stubs both in `stdlib/@python2` and `stdlib` for the same top-level package, which could result in a mix of Python 2 and 3 stubs being used. Now if we find stubs for a package in the `@python2` directory, we skip the parent directory. Fixes #10421.
1 parent b484c6d commit 4518b55

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

mypy/modulefinder.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,10 @@ def get_toplevel_possibilities(self, lib_path: Tuple[str, ...], id: str) -> List
185185
name = os.path.splitext(name)[0]
186186
components.setdefault(name, []).append(dir)
187187

188+
if self.python2:
189+
components = {id: filter_redundant_py2_dirs(dirs)
190+
for id, dirs in components.items()}
191+
188192
self.initial_components[lib_path] = components
189193
return components.get(id, [])
190194

@@ -791,3 +795,19 @@ def typeshed_py_version(options: Options) -> Tuple[int, int]:
791795
return max(options.python_version, (3, 6))
792796
else:
793797
return options.python_version
798+
799+
800+
def filter_redundant_py2_dirs(dirs: List[str]) -> List[str]:
801+
"""If dirs has <dir>/@python2 followed by <dir>, filter out the latter."""
802+
if len(dirs) <= 1 or not any(d.endswith(PYTHON2_STUB_DIR) for d in dirs):
803+
# Fast path -- nothing to do
804+
return dirs
805+
seen = []
806+
result = []
807+
for d in dirs:
808+
if d.endswith(PYTHON2_STUB_DIR):
809+
seen.append(os.path.dirname(d))
810+
result.append(d)
811+
elif d not in seen:
812+
result.append(d)
813+
return result

test-data/unit/python2eval.test

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,3 +428,8 @@ def foo() -> None:
428428
reveal_type(x)
429429
[out]
430430
_testDefaultDictInference.py:5: note: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"
431+
432+
[case testIgnorePython3StdlibStubs_python2]
433+
from collections import abc
434+
[out]
435+
_testIgnorePython3StdlibStubs_python2.py:1: error: Module "collections" has no attribute "abc"

0 commit comments

Comments
 (0)