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, path: str | None = None) -> bool:
19 """Tell whether modname is a namespace package.
20
21 When path is given, modname is searched from that directory instead of
22 sys.path, so that a namespace package that also exists in site-packages is
23 still recognised from the directory it is resolved from.
24 """
25 from astroid.modutils import ( # pylint: disable=import-outside-toplevel
26 EXT_LIB_DIRS,
27 STD_LIB_DIRS,
28 )
29
30 STD_AND_EXT_LIB_DIRS = STD_LIB_DIRS.union(EXT_LIB_DIRS)
31
32 if modname in sys.builtin_module_names:
33 return False
34
35 found_spec = None
36
37 # find_spec() attempts to import parent packages when given dotted paths.
38 # That's unacceptable here, so we fallback to _find_spec_from_path(), which does
39 # not, but requires instead that each single parent ('astroid', 'nodes', etc.)
40 # be specced from left to right.
41 processed_components = []
42 last_submodule_search_locations: list[str] | _NamespacePath | None = (
43 None if path is None else [path]
44 )
45 for component in modname.split("."):
46 processed_components.append(component)
47 working_modname = ".".join(processed_components)
48 try:
49 # Both the modname and the path are built iteratively, with the
50 # path (e.g. ['a', 'a/b', 'a/b/c']) lagging the modname by one
51 found_spec = _find_spec_from_path(
52 working_modname, path=last_submodule_search_locations
53 )
54 except AttributeError:
55 return False
56 except ValueError:
57 if modname == "__main__":
58 return False
59 try:
60 # .pth files will be on sys.modules
61 # __spec__ is set inconsistently on PyPy so we can't really on the heuristic here
62 # See: https://foss.heptapod.net/pypy/pypy/-/issues/3736
63 # Check first fragment of modname, e.g. "astroid", not "astroid.interpreter"
64 # because of cffi's behavior
65 # See: https://github.com/pylint-dev/astroid/issues/1776
66 mod = sys.modules[processed_components[0]]
67 return (
68 mod.__spec__ is None
69 and getattr(mod, "__file__", None) is None
70 and hasattr(mod, "__path__")
71 and not IS_PYPY
72 )
73 except KeyError:
74 return False
75 except AttributeError:
76 # Workaround for "py" module
77 # https://github.com/pytest-dev/apipkg/issues/13
78 return False
79 # PY314: When dropping support for 3.14, replace with just
80 # except ModuleNotFoundError:
81 except (KeyError, ModuleNotFoundError):
82 # Intermediate steps might raise ModuleNotFoundError
83 # For tree a > b > c.py
84 # >>> from importlib.machinery import PathFinder
85 # >>> PathFinder.find_spec('a.b', ['a'])
86 # KeyError: 'a'
87
88 # Repair last_submodule_search_locations
89 if last_submodule_search_locations:
90 last_item = last_submodule_search_locations[-1]
91 # e.g. for failure example above, add 'a/b' and keep going
92 # so that find_spec('a.b.c', path=['a', 'a/b']) succeeds
93 assumed_location = pathlib.Path(last_item) / component
94 last_submodule_search_locations.append(str(assumed_location))
95 continue
96
97 # Update last_submodule_search_locations for next iteration
98 if found_spec and found_spec.submodule_search_locations:
99 # But immediately return False if we can detect we are in stdlib
100 # or external lib (e.g site-packages)
101 if any(
102 any(
103 str(location).startswith(lib_dir)
104 for lib_dir in STD_AND_EXT_LIB_DIRS
105 )
106 for location in found_spec.submodule_search_locations
107 ):
108 return False
109 last_submodule_search_locations = found_spec.submodule_search_locations
110
111 return (
112 found_spec is not None
113 and found_spec.submodule_search_locations is not None
114 and found_spec.origin is None
115 and (
116 found_spec.loader is None or isinstance(found_spec.loader, NamespaceLoader)
117 )
118 )