1# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5from __future__ import annotations
6
7import pathlib
8import sys
9from functools import lru_cache
10from importlib._bootstrap_external import _NamespacePath # type: ignore[attr-defined]
11from importlib.machinery import NamespaceLoader
12from importlib.util import _find_spec_from_path # type: ignore[attr-defined]
13
14from astroid.const import IS_PYPY
15
16
17@lru_cache(maxsize=4096)
18def is_namespace(modname: str) -> bool:
19 from astroid.modutils import ( # pylint: disable=import-outside-toplevel
20 EXT_LIB_DIRS,
21 STD_LIB_DIRS,
22 )
23
24 STD_AND_EXT_LIB_DIRS = STD_LIB_DIRS.union(EXT_LIB_DIRS)
25
26 if modname in sys.builtin_module_names:
27 return False
28
29 found_spec = None
30
31 # find_spec() attempts to import parent packages when given dotted paths.
32 # That's unacceptable here, so we fallback to _find_spec_from_path(), which does
33 # not, but requires instead that each single parent ('astroid', 'nodes', etc.)
34 # be specced from left to right.
35 processed_components = []
36 last_submodule_search_locations: _NamespacePath | None = None
37 for component in modname.split("."):
38 processed_components.append(component)
39 working_modname = ".".join(processed_components)
40 try:
41 # Both the modname and the path are built iteratively, with the
42 # path (e.g. ['a', 'a/b', 'a/b/c']) lagging the modname by one
43 found_spec = _find_spec_from_path(
44 working_modname, path=last_submodule_search_locations
45 )
46 except AttributeError:
47 return False
48 except ValueError:
49 if modname == "__main__":
50 return False
51 try:
52 # .pth files will be on sys.modules
53 # __spec__ is set inconsistently on PyPy so we can't really on the heuristic here
54 # See: https://foss.heptapod.net/pypy/pypy/-/issues/3736
55 # Check first fragment of modname, e.g. "astroid", not "astroid.interpreter"
56 # because of cffi's behavior
57 # See: https://github.com/pylint-dev/astroid/issues/1776
58 mod = sys.modules[processed_components[0]]
59 return (
60 mod.__spec__ is None
61 and getattr(mod, "__file__", None) is None
62 and hasattr(mod, "__path__")
63 and not IS_PYPY
64 )
65 except KeyError:
66 return False
67 except AttributeError:
68 # Workaround for "py" module
69 # https://github.com/pytest-dev/apipkg/issues/13
70 return False
71 # PY314: When dropping support for 3.14, replace with just
72 # except ModuleNotFoundError:
73 except (KeyError, ModuleNotFoundError):
74 # Intermediate steps might raise ModuleNotFoundError
75 # For tree a > b > c.py
76 # >>> from importlib.machinery import PathFinder
77 # >>> PathFinder.find_spec('a.b', ['a'])
78 # KeyError: 'a'
79
80 # Repair last_submodule_search_locations
81 if last_submodule_search_locations:
82 last_item = last_submodule_search_locations[-1]
83 # e.g. for failure example above, add 'a/b' and keep going
84 # so that find_spec('a.b.c', path=['a', 'a/b']) succeeds
85 assumed_location = pathlib.Path(last_item) / component
86 last_submodule_search_locations.append(str(assumed_location))
87 continue
88
89 # Update last_submodule_search_locations for next iteration
90 if found_spec and found_spec.submodule_search_locations:
91 # But immediately return False if we can detect we are in stdlib
92 # or external lib (e.g site-packages)
93 if any(
94 any(
95 str(location).startswith(lib_dir)
96 for lib_dir in STD_AND_EXT_LIB_DIRS
97 )
98 for location in found_spec.submodule_search_locations
99 ):
100 return False
101 last_submodule_search_locations = found_spec.submodule_search_locations
102
103 return (
104 found_spec is not None
105 and found_spec.submodule_search_locations is not None
106 and found_spec.origin is None
107 and (
108 found_spec.loader is None or isinstance(found_spec.loader, NamespaceLoader)
109 )
110 )