Skip to content

Commit 8bd9ff4

Browse files
More conservative interpretation of PathFinder.find_spec() failures (#1581)
1 parent 1ccb1c4 commit 8bd9ff4

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

astroid/interpreter/_import/util.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,17 @@ def is_namespace(modname: str) -> bool:
3434
working_modname, path=last_submodule_search_locations
3535
)
3636
except ValueError:
37-
# Assume it's a .pth file, unless it's __main__
38-
return modname != "__main__"
37+
if modname == "__main__":
38+
return False
39+
try:
40+
# .pth files will be on sys.modules
41+
return sys.modules[modname].__spec__ is None
42+
except KeyError:
43+
return False
44+
except AttributeError:
45+
# Workaround for "py" module
46+
# https://github.com/pytest-dev/apipkg/issues/13
47+
return False
3948
except KeyError:
4049
# Intermediate steps might raise KeyErrors
4150
# https://github.com/python/cpython/issues/93334

tests/unittest_manager.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,15 @@ def test_module_is_not_namespace(self) -> None:
129129
self.assertFalse(util.is_namespace("tests.testdata.python3.data.all"))
130130
self.assertFalse(util.is_namespace("__main__"))
131131

132+
def test_module_unexpectedly_missing_spec(self) -> None:
133+
astroid_module = sys.modules["astroid"]
134+
original_spec = astroid_module.__spec__
135+
del astroid_module.__spec__
136+
try:
137+
self.assertFalse(util.is_namespace("astroid"))
138+
finally:
139+
astroid_module.__spec__ = original_spec
140+
132141
def test_implicit_namespace_package(self) -> None:
133142
data_dir = os.path.dirname(resources.find("data/namespace_pep_420"))
134143
contribute = os.path.join(data_dir, "contribute_to_namespace")

0 commit comments

Comments
 (0)