Skip to content

Commit 004cc0f

Browse files
committed
Prefer modules and packages to namespaces regardless of path order
1 parent 28c6ca7 commit 004cc0f

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

mypy/build.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -941,7 +941,11 @@ def _collect_paths(self, paths: List[str], last_comp: str) -> List[str]:
941941
path = os.path.join(path_item, last_comp + ext)
942942
ctx.maybe_add_path(path, ModuleType.module)
943943

944-
if self.namespaces_allowed:
944+
if self.namespaces_allowed and not ctx.paths:
945+
for path_item in paths:
946+
if is_pkg_path(path_item):
947+
path_item = dirname(path_item)
948+
945949
path = os.path.join(path_item, last_comp)
946950
ctx.maybe_add_path(path + os.sep, ModuleType.namespace)
947951

test-data/unit/check-namespaces.test

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,21 @@ mypy_path = ./tmp/dir:./tmp/other_dir
6464
main:3: error: Cannot find module named 'pkg_or_ns.b'
6565
main:3: note: (Perhaps setting MYPYPATH or using the "--ignore-missing-imports" flag would help)
6666

67+
[case testConflictingPackageAndNamespaceImportPackageLaterInPath]
68+
# flags: --config-file tmp/mypy.ini
69+
import pkg_or_ns.a
70+
import pkg_or_ns.b
71+
[file mypy.ini]
72+
[[mypy]
73+
namespace_packages = True
74+
mypy_path = ./tmp/other_dir:./tmp/dir
75+
[file dir/pkg_or_ns/__init__.py]
76+
[file dir/pkg_or_ns/a.py]
77+
[file other_dir/pkg_or_ns/b.py]
78+
[out]
79+
main:3: error: Cannot find module named 'pkg_or_ns.b'
80+
main:3: note: (Perhaps setting MYPYPATH or using the "--ignore-missing-imports" flag would help)
81+
6782
[case testConflictingModuleAndNamespace]
6883
# flags: --config-file tmp/mypy.ini
6984
from mod_or_ns import a
@@ -76,7 +91,19 @@ mypy_path = ./tmp/dir:./tmp/other_dir
7691
a = None
7792
[file other_dir/mod_or_ns/b.py]
7893

79-
[case testeNamespaceInsidePackage]
94+
[case testConflictingModuleAndNamespaceModuleLaterInPath]
95+
# flags: --config-file tmp/mypy.ini
96+
from mod_or_ns import a
97+
from mod_or_ns import b # E: Module 'mod_or_ns' has no attribute 'b'
98+
[file mypy.ini]
99+
[[mypy]
100+
namespace_packages = True
101+
mypy_path = ./tmp/other_dir:./tmp/dir
102+
[file dir/mod_or_ns.py]
103+
a = None
104+
[file other_dir/mod_or_ns/b.py]
105+
106+
[case testNamespaceInsidePackage]
80107
# flags: --config-file tmp/mypy.ini
81108
from pkg.ns import a
82109
[file mypy.ini]

0 commit comments

Comments
 (0)