Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/modutils.py: 25%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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
5"""Python modules manipulation utility functions.
7:var PY_SOURCE_EXTS: list of possible python source file extension
9:var STD_LIB_DIRS: directories where standard modules are located
11:var BUILTIN_MODULES: dictionary with builtin module names has key
12"""
14from __future__ import annotations
16import importlib
17import importlib.machinery
18import importlib.util
19import io
20import itertools
21import os
22import sys
23import sysconfig
24import types
25from collections.abc import Callable, Iterable, Sequence
26from contextlib import redirect_stderr, redirect_stdout
27from functools import lru_cache
28from sys import stdlib_module_names
30from astroid.const import IS_JYTHON
31from astroid.interpreter._import import spec, util
33if sys.platform.startswith("win"):
34 PY_SOURCE_EXTS: tuple[str, ...] = ("py", "pyw", "pyi")
35 PY_SOURCE_EXTS_STUBS_FIRST = ("pyi", "pyw", "py")
36 PY_COMPILED_EXTS = ("dll", "pyd")
37else:
38 PY_SOURCE_EXTS = ("py", "pyi")
39 PY_SOURCE_EXTS_STUBS_FIRST = ("pyi", "py")
40 PY_COMPILED_EXTS = ("so",)
42# Bytecode extensions are platform-independent, unlike PY_COMPILED_EXTS above.
43PY_BYTECODE_EXTS = ("pyc", "pyo")
46# TODO: Adding `platstdlib` is a fix for a workaround in virtualenv. At some point we should
47# revisit whether this is still necessary. See https://github.com/pylint-dev/astroid/pull/1323.
48STD_LIB_DIRS: set[str] = {
49 sysconfig.get_path("stdlib"),
50 sysconfig.get_path("platstdlib"),
51}
53if os.name == "nt":
54 STD_LIB_DIRS.add(os.path.join(sys.prefix, "dlls"))
55 try:
56 # real_prefix is defined when running inside virtual environments,
57 # created with the **virtualenv** library.
58 # Deprecated in virtualenv==16.7.9
59 # See: https://github.com/pypa/virtualenv/issues/1622
60 STD_LIB_DIRS.add(os.path.join(sys.real_prefix, "dlls")) # type: ignore[attr-defined]
61 except AttributeError:
62 # sys.base_exec_prefix is always defined, but in a virtual environment
63 # created with the stdlib **venv** module, it points to the original
64 # installation, if the virtual env is activated.
65 try:
66 STD_LIB_DIRS.add(os.path.join(sys.base_exec_prefix, "dlls"))
67 except AttributeError:
68 pass
70if os.name == "posix":
71 # Need the real prefix if we're in a virtualenv, otherwise
72 # the usual one will do.
73 # Deprecated in virtualenv==16.7.9
74 # See: https://github.com/pypa/virtualenv/issues/1622
75 try:
76 prefix: str = sys.real_prefix # type: ignore[attr-defined]
77 except AttributeError:
78 prefix = sys.prefix
80 def _posix_path(path: str) -> str:
81 base_python = f"python{sys.version_info.major}.{sys.version_info.minor}"
82 return os.path.join(prefix, path, base_python)
84 STD_LIB_DIRS.add(_posix_path("lib"))
85 if sys.maxsize > 2**32:
86 # This tries to fix a problem with /usr/lib64 builds,
87 # where systems are running both 32-bit and 64-bit code
88 # on the same machine, which reflects into the places where
89 # standard library could be found. More details can be found
90 # here http://bugs.python.org/issue1294959.
91 # An easy reproducing case would be
92 # https://github.com/pylint-dev/pylint/issues/712#issuecomment-163178753
93 STD_LIB_DIRS.add(_posix_path("lib64"))
95EXT_LIB_DIRS = {sysconfig.get_path("purelib"), sysconfig.get_path("platlib")}
96BUILTIN_MODULES: dict[str, bool] = dict.fromkeys(sys.builtin_module_names, True)
99class NoSourceFile(Exception):
100 """Exception raised when we are not able to get a python
101 source file for a precompiled file.
102 """
105def _normalize_path(path: str) -> str:
106 """Resolve symlinks in path and convert to absolute path.
108 Note that environment variables and ~ in the path need to be expanded in
109 advance.
111 This can be cached by using _cache_normalize_path.
112 """
113 return os.path.normcase(os.path.realpath(path))
116def _path_from_filename(filename: str, is_jython: bool = IS_JYTHON) -> str:
117 if not is_jython:
118 return filename
119 head, has_pyclass, _ = filename.partition("$py.class")
120 if has_pyclass:
121 return head + ".py"
122 return filename
125def _handle_blacklist(
126 blacklist: Sequence[str], dirnames: list[str], filenames: list[str]
127) -> None:
128 """Remove files/directories in the black list.
130 dirnames/filenames are usually from os.walk
131 """
132 for norecurs in blacklist:
133 if norecurs in dirnames:
134 dirnames.remove(norecurs)
135 elif norecurs in filenames:
136 filenames.remove(norecurs)
139@lru_cache
140def _cache_normalize_path_(path: str) -> str:
141 return _normalize_path(path)
144def _cache_normalize_path(path: str) -> str:
145 """Normalize path with caching."""
146 # _module_file calls abspath on every path in sys.path every time it's
147 # called; on a larger codebase this easily adds up to half a second just
148 # assembling path components. This cache alleviates that.
149 if not path: # don't cache result for ''
150 return _normalize_path(path)
151 return _cache_normalize_path_(path)
154def load_module_from_name(dotted_name: str) -> types.ModuleType:
155 """Load a Python module from its name.
157 :param dotted_name: python name of a module or package
159 :raise ImportError: if the module or package is not found
161 :return: the loaded module
162 """
163 try:
164 return sys.modules[dotted_name]
165 except KeyError:
166 pass
168 # Capture and log anything emitted during import to avoid
169 # contaminating JSON reports in pylint
170 with (
171 redirect_stderr(io.StringIO()) as stderr,
172 redirect_stdout(io.StringIO()) as stdout,
173 ):
174 module = importlib.import_module(dotted_name)
176 stderr_value = stderr.getvalue()
177 stdout_value = stdout.getvalue()
178 if stderr_value or stdout_value:
179 import logging # pylint: disable=import-outside-toplevel
181 logger = logging.getLogger(__name__)
182 if stderr_value:
183 logger.error(
184 "Captured stderr while importing %s:\n%s", dotted_name, stderr_value
185 )
186 if stdout_value:
187 logger.info(
188 "Captured stdout while importing %s:\n%s", dotted_name, stdout_value
189 )
191 return module
194def load_module_from_modpath(parts: Sequence[str]) -> types.ModuleType:
195 """Load a python module from its split name.
197 :param parts:
198 python name of a module or package split on '.'
200 :raise ImportError: if the module or package is not found
202 :return: the loaded module
203 """
204 return load_module_from_name(".".join(parts))
207def load_module_from_file(filepath: str) -> types.ModuleType:
208 """Load a Python module from it's path.
210 :param filepath: path to the python module or package
212 :raise ImportError: if the module or package is not found
214 :return: the loaded module
215 """
216 modpath = modpath_from_file(filepath)
217 return load_module_from_modpath(modpath)
220def check_modpath_has_init(path: str, mod_path: list[str]) -> bool:
221 """Check there are some __init__.py all along the way."""
222 modpath: list[str] = []
223 search_path = path
224 for part in mod_path:
225 modpath.append(part)
226 path = os.path.join(path, part)
227 if not _has_init(path):
228 old_namespace = util.is_namespace(".".join(modpath), search_path)
229 if not old_namespace:
230 return False
231 return True
234def _is_subpath(path: str, base: str) -> bool:
235 path = os.path.normcase(os.path.normpath(path))
236 base = os.path.normcase(os.path.normpath(base))
237 if not path.startswith(base):
238 return False
239 return (
240 (len(path) == len(base))
241 or (path[len(base)] == os.path.sep)
242 or (base.endswith(os.path.sep) and path[len(base) - 1] == os.path.sep)
243 )
246def _get_relative_base_path(filename: str, path_to_check: str) -> list[str] | None:
247 """Extracts the relative mod path of the file to import from.
249 Check if a file is within the passed in path and if so, returns the
250 relative mod path from the one passed in.
252 If the filename is no in path_to_check, returns None
254 Note this function will look for both abs and realpath of the file,
255 this allows to find the relative base path even if the file is a
256 symlink of a file in the passed in path
258 Examples:
259 _get_relative_base_path("/a/b/c/d.py", "/a/b") -> ["c","d"]
260 _get_relative_base_path("/a/b/c/d.py", "/dev") -> None
261 """
262 path_to_check = os.path.normcase(os.path.normpath(path_to_check))
264 abs_filename = os.path.abspath(filename)
265 if _is_subpath(abs_filename, path_to_check):
266 base_path = os.path.splitext(abs_filename)[0]
267 relative_base_path = base_path[len(path_to_check) :].lstrip(os.path.sep)
268 return [pkg for pkg in relative_base_path.split(os.sep) if pkg]
270 real_filename = os.path.realpath(filename)
271 if _is_subpath(real_filename, path_to_check):
272 base_path = os.path.splitext(real_filename)[0]
273 relative_base_path = base_path[len(path_to_check) :].lstrip(os.path.sep)
274 return [pkg for pkg in relative_base_path.split(os.sep) if pkg]
276 return None
279def modpath_from_file_with_callback(
280 filename: str,
281 path: list[str] | None = None,
282 is_package_cb: Callable[[str, list[str]], bool] | None = None,
283) -> list[str]:
284 filename = os.path.expanduser(_path_from_filename(filename))
285 paths_to_check = sys.path.copy()
286 if path:
287 paths_to_check = path + paths_to_check
288 for pathname in itertools.chain(
289 paths_to_check, map(_cache_normalize_path, paths_to_check)
290 ):
291 if not pathname:
292 continue
293 modpath = _get_relative_base_path(filename, pathname)
294 if not modpath:
295 continue
296 assert is_package_cb is not None
297 if is_package_cb(pathname, modpath[:-1]):
298 return modpath
300 raise ImportError(
301 "Unable to find module for {} in {}".format(
302 filename, ", \n".join(paths_to_check)
303 )
304 )
307def modpath_from_file(filename: str, path: list[str] | None = None) -> list[str]:
308 """Get the corresponding split module's name from a filename.
310 This function will return the name of a module or package split on `.`.
312 :param filename: file's path for which we want the module's name
314 :param path:
315 Optional list of paths where the module or package should be
316 searched, additionally to sys.path
318 :raise ImportError:
319 if the corresponding module's name has not been found
321 :return: the corresponding split module's name
322 """
323 return modpath_from_file_with_callback(filename, path, check_modpath_has_init)
326def file_from_modpath(
327 modpath: list[str],
328 path: Sequence[str] | None = None,
329 context_file: str | None = None,
330) -> str | None:
331 return file_info_from_modpath(modpath, path, context_file).location
334def file_info_from_modpath(
335 modpath: list[str],
336 path: Sequence[str] | None = None,
337 context_file: str | None = None,
338) -> spec.ModuleSpec:
339 """Given a mod path (i.e. split module / package name), return the
340 corresponding file.
342 Giving priority to source file over precompiled file if it exists.
344 :param modpath:
345 split module's name (i.e name of a module or package split
346 on '.')
347 (this means explicit relative imports that start with dots have
348 empty strings in this list!)
350 :param path:
351 optional list of path where the module or package should be
352 searched (use sys.path if nothing or None is given)
354 :param context_file:
355 context file to consider, necessary if the identifier has been
356 introduced using a relative import unresolvable in the actual
357 context (i.e. modutils)
359 :raise ImportError: if there is no such module in the directory
361 :return:
362 the path to the module's file or None if it's an integrated
363 builtin module such as 'sys'
364 """
365 if context_file is not None:
366 context: str | None = os.path.dirname(context_file)
367 else:
368 context = context_file
369 if modpath[0] == "xml":
370 # handle _xmlplus
371 try:
372 return _spec_from_modpath(["_xmlplus", *modpath[1:]], path, context)
373 except ImportError:
374 return _spec_from_modpath(modpath, path, context)
375 elif modpath == ["os", "path"]:
376 # FIXME: currently ignoring search_path...
377 return spec.ModuleSpec(
378 name="os.path",
379 location=os.path.__file__,
380 type=spec.ModuleType.PY_SOURCE,
381 )
382 return _spec_from_modpath(modpath, path, context)
385def get_module_part(dotted_name: str, context_file: str | None = None) -> str:
386 """Given a dotted name return the module part of the name :
388 >>> get_module_part('astroid.as_string.dump')
389 'astroid.as_string'
391 :param dotted_name: full name of the identifier we are interested in
393 :param context_file:
394 context file to consider, necessary if the identifier has been
395 introduced using a relative import unresolvable in the actual
396 context (i.e. modutils)
398 :raise ImportError: if there is no such module in the directory
400 :return:
401 the module part of the name or None if we have not been able at
402 all to import the given name
404 XXX: deprecated, since it doesn't handle package precedence over module
405 (see #10066)
406 """
407 # os.path trick
408 if dotted_name.startswith("os.path"):
409 return "os.path"
410 parts = dotted_name.split(".")
411 if context_file is not None:
412 # first check for builtin module which won't be considered latter
413 # in that case (path != None)
414 if parts[0] in BUILTIN_MODULES:
415 if len(parts) > 2:
416 raise ImportError(dotted_name)
417 return parts[0]
418 # don't use += or insert, we want a new list to be created !
419 path: list[str] | None = None
420 starti = 0
421 if parts[0] == "":
422 assert (
423 context_file is not None
424 ), "explicit relative import, but no context_file?"
425 path = [] # prevent resolving the import non-relatively
426 starti = 1
427 # for all further dots: change context
428 while starti < len(parts) and parts[starti] == "":
429 starti += 1
430 assert (
431 context_file is not None
432 ), "explicit relative import, but no context_file?"
433 context_file = os.path.dirname(context_file)
434 for i in range(starti, len(parts)):
435 try:
436 file_from_modpath(
437 parts[starti : i + 1], path=path, context_file=context_file
438 )
439 except ImportError:
440 if i < max(1, len(parts) - 2):
441 raise
442 return ".".join(parts[:i])
443 return dotted_name
446def get_module_files(
447 src_directory: str, blacklist: Sequence[str], list_all: bool = False
448) -> list[str]:
449 """Given a package directory return a list of all available python
450 module's files in the package and its subpackages.
452 :param src_directory:
453 path of the directory corresponding to the package
455 :param blacklist: iterable
456 list of files or directories to ignore.
458 :param list_all:
459 get files from all paths, including ones without __init__.py
461 :return:
462 the list of all available python module's files in the package and
463 its subpackages
464 """
465 files: list[str] = []
466 for directory, dirnames, filenames in os.walk(src_directory):
467 if directory in blacklist:
468 continue
469 _handle_blacklist(blacklist, dirnames, filenames)
470 # check for __init__.py
471 if not list_all and {"__init__.py", "__init__.pyi"}.isdisjoint(filenames):
472 dirnames[:] = ()
473 continue
474 for filename in filenames:
475 if _is_python_file(filename):
476 src = os.path.join(directory, filename)
477 files.append(src)
478 return files
481def _is_compiled_ext(ext: str) -> bool:
482 """Return whether ``ext`` (without leading dot) names a compiled module:
483 bytecode (.pyc/.pyo) or a binary extension module (.so/.pyd/.dll). Such
484 files are never source.
485 """
486 return ext in PY_BYTECODE_EXTS or ext in PY_COMPILED_EXTS
489def get_source_file(
490 filename: str, include_no_ext: bool = False, prefer_stubs: bool = False
491) -> str:
492 """Given a python module's file name return the matching source file
493 name (the filename will be returned identically if it's already an
494 absolute path to a python source file).
496 :param filename: python module's file name
498 :raise NoSourceFile: if no source file exists on the file system
500 :return: the absolute path of the source file if it exists
501 """
502 filename = os.path.abspath(_path_from_filename(filename))
503 base, orig_ext = os.path.splitext(filename)
504 orig_ext = orig_ext.lstrip(".")
505 extension_suffix = max(
506 (
507 suffix
508 for suffix in importlib.machinery.EXTENSION_SUFFIXES
509 if filename.endswith(suffix)
510 ),
511 key=len,
512 default=None,
513 )
514 if extension_suffix is not None:
515 base = filename[: -len(extension_suffix)]
516 # A non-standard extension (e.g. a custom suffix) is returned as-is, but a
517 # compiled file falls through to the lookup below so its .py/.pyi stub is
518 # found instead.
519 if (
520 orig_ext not in PY_SOURCE_EXTS
521 and not _is_compiled_ext(orig_ext)
522 and os.path.exists(f"{base}.{orig_ext}")
523 ):
524 return f"{base}.{orig_ext}"
525 for ext in PY_SOURCE_EXTS_STUBS_FIRST if prefer_stubs else PY_SOURCE_EXTS:
526 source_path = f"{base}.{ext}"
527 if os.path.exists(source_path):
528 return source_path
529 if include_no_ext and not orig_ext and os.path.exists(base):
530 return base
531 raise NoSourceFile(filename)
534def is_python_source(filename: str | None) -> bool:
535 """Return: True if the filename is a python source file."""
536 if not filename:
537 return False
538 return os.path.splitext(filename)[1][1:] in PY_SOURCE_EXTS
541def is_stdlib_module(modname: str) -> bool:
542 """Return: True if the modname is in the standard library"""
543 return modname.split(".")[0] in stdlib_module_names
546def is_stdlib_path(filename: str) -> bool:
547 """Return: True if the file is located in the standard library.
549 site-packages sits below one of the standard library directories in a
550 virtualenv, so external locations are rejected first.
551 """
552 filename = _normalize_path(filename)
553 if any(
554 filename.startswith(_cache_normalize_path(entry) + os.sep)
555 for entry in EXT_LIB_DIRS
556 ):
557 return False
558 return any(
559 filename.startswith(_cache_normalize_path(entry) + os.sep)
560 for entry in STD_LIB_DIRS
561 )
564def module_in_path(modname: str, path: str | Iterable[str]) -> bool:
565 """Try to determine if a module is imported from one of the specified paths
567 :param modname: name of the module
569 :param path: paths to consider
571 :return:
572 true if the module:
573 - is located on the path listed in one of the directory in `paths`
574 """
576 modname = modname.split(".")[0]
577 try:
578 filename = file_from_modpath([modname])
579 except ImportError:
580 # Import failed, we can't check path if we don't know it
581 return False
583 if filename is None:
584 # No filename likely means it's compiled in, or potentially a namespace
585 return False
586 filename = _normalize_path(filename)
588 if isinstance(path, str):
589 return _is_subpath(filename, _cache_normalize_path(path))
591 return any(_is_subpath(filename, _cache_normalize_path(entry)) for entry in path)
594def is_relative(modname: str, from_file: str) -> bool:
595 """Return true if the given module name is relative to the given
596 file name.
598 :param modname: name of the module we are interested in
600 :param from_file:
601 path of the module from which modname has been imported
603 :return:
604 true if the module has been imported relatively to `from_file`
605 """
606 if not os.path.isdir(from_file):
607 from_file = os.path.dirname(from_file)
608 if from_file in sys.path:
609 return False
610 return bool(
611 importlib.machinery.PathFinder.find_spec(
612 modname.split(".", maxsplit=1)[0], [from_file]
613 )
614 )
617@lru_cache(maxsize=1024)
618def cached_os_path_isfile(path: str | os.PathLike[str]) -> bool:
619 """A cached version of os.path.isfile that helps avoid repetitive I/O"""
620 return os.path.isfile(path)
623# internal only functions #####################################################
626def _spec_from_modpath(
627 modpath: list[str],
628 path: Sequence[str] | None = None,
629 context: str | None = None,
630) -> spec.ModuleSpec:
631 """Given a mod path (i.e. split module / package name), return the
632 corresponding spec.
634 this function is used internally, see `file_from_modpath`'s
635 documentation for more information
636 """
637 assert modpath
638 location = None
639 if context is not None:
640 try:
641 found_spec = spec.find_spec(modpath, [context])
642 location = found_spec.location
643 except ImportError:
644 found_spec = spec.find_spec(modpath, path)
645 location = found_spec.location
646 else:
647 found_spec = spec.find_spec(modpath, path)
648 if found_spec.type == spec.ModuleType.PY_COMPILED:
649 try:
650 assert found_spec.location is not None
651 location = get_source_file(found_spec.location)
652 return found_spec._replace(
653 location=location, type=spec.ModuleType.PY_SOURCE
654 )
655 except NoSourceFile:
656 return found_spec._replace(location=location)
657 elif found_spec.type == spec.ModuleType.C_BUILTIN:
658 # integrated builtin module
659 return found_spec._replace(location=None)
660 elif found_spec.type == spec.ModuleType.PKG_DIRECTORY:
661 assert found_spec.location is not None
662 location = _has_init(found_spec.location)
663 return found_spec._replace(location=location, type=spec.ModuleType.PY_SOURCE)
664 return found_spec
667def _is_python_file(filename: str) -> bool:
668 """Return true if the given filename should be considered as a python file.
670 .pyc and .pyo are ignored
671 """
672 return filename.endswith((".py", ".pyi", ".so", ".pyd", ".pyw"))
675@lru_cache(maxsize=1024)
676def _has_init(directory: str) -> str | None:
677 """If the given directory has a valid __init__ file, return its path,
678 else return None.
679 """
680 mod_or_pack = os.path.join(directory, "__init__")
681 for ext in (*PY_SOURCE_EXTS, *PY_BYTECODE_EXTS):
682 if os.path.exists(mod_or_pack + "." + ext):
683 return mod_or_pack + "." + ext
684 return None
687def is_namespace(specobj: spec.ModuleSpec) -> bool:
688 return specobj.type == spec.ModuleType.PY_NAMESPACE
691def is_directory(specobj: spec.ModuleSpec) -> bool:
692 return specobj.type == spec.ModuleType.PKG_DIRECTORY
695def is_module_name_part_of_extension_package_whitelist(
696 module_name: str, package_whitelist: set[str]
697) -> bool:
698 """
699 Returns True if one part of the module name is in the package whitelist.
701 >>> is_module_name_part_of_extension_package_whitelist('numpy.core.umath', {'numpy'})
702 True
703 """
704 parts = module_name.split(".")
705 return any(
706 ".".join(parts[:x]) in package_whitelist for x in range(1, len(parts) + 1)
707 )