diff options
author | Daniƫl van Noord <13665637+DanielNoord@users.noreply.github.com> | 2022-09-21 21:14:50 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-09-21 21:14:50 +0200 |
commit | b867508d903719378e439ec48686565a497ec312 (patch) | |
tree | be101b9687c3729e17c2c647afb9e54a31929874 | |
parent | 61dc314c9daf74ebe76767feeb1a3eb857f67771 (diff) | |
download | astroid-git-b867508d903719378e439ec48686565a497ec312.tar.gz |
Finish typing of ``astroid.manager.py`` (#1806)
-rw-r--r-- | astroid/builder.py | 6 | ||||
-rw-r--r-- | astroid/exceptions.py | 2 | ||||
-rw-r--r-- | astroid/inference_tip.py | 2 | ||||
-rw-r--r-- | astroid/manager.py | 72 | ||||
-rw-r--r-- | astroid/raw_building.py | 2 |
5 files changed, 55 insertions, 29 deletions
diff --git a/astroid/builder.py b/astroid/builder.py index 24caa0c6..0b8755a3 100644 --- a/astroid/builder.py +++ b/astroid/builder.py @@ -13,6 +13,7 @@ from __future__ import annotations import os import textwrap import types +from collections.abc import Sequence from tokenize import detect_encoding from astroid import bases, modutils, nodes, raw_building, rebuilder, util @@ -261,8 +262,9 @@ class AstroidBuilder(raw_building.InspectBuilder): pass -def build_namespace_package_module(name: str, path: list[str]) -> nodes.Module: - return nodes.Module(name, path=path, package=True) +def build_namespace_package_module(name: str, path: Sequence[str]) -> nodes.Module: + # TODO: Typing: Remove the cast to list and just update typing to accept Sequence + return nodes.Module(name, path=list(path), package=True) def parse(code, module_name="", path=None, apply_transforms=True): diff --git a/astroid/exceptions.py b/astroid/exceptions.py index 0dac271d..87a8744d 100644 --- a/astroid/exceptions.py +++ b/astroid/exceptions.py @@ -87,7 +87,7 @@ class AstroidBuildingError(AstroidError): error: Exception | None = None, source: str | None = None, path: str | None = None, - cls: None = None, + cls: type | None = None, class_repr: str | None = None, **kws: Any, ) -> None: diff --git a/astroid/inference_tip.py b/astroid/inference_tip.py index 341efd63..e4c54822 100644 --- a/astroid/inference_tip.py +++ b/astroid/inference_tip.py @@ -23,7 +23,7 @@ InferOptions = typing.Union[ _cache: dict[tuple[InferFn, NodeNG], list[InferOptions] | None] = {} -def clear_inference_tip_cache(): +def clear_inference_tip_cache() -> None: """Clear the inference tips cache.""" _cache.clear() diff --git a/astroid/manager.py b/astroid/manager.py index 37c87005..e2f0d3fd 100644 --- a/astroid/manager.py +++ b/astroid/manager.py @@ -13,12 +13,14 @@ import collections import os import types import zipimport -from collections.abc import Callable +from collections.abc import Callable, Iterator, Sequence from importlib.util import find_spec, module_from_spec -from typing import TYPE_CHECKING, ClassVar +from typing import Any, ClassVar +from astroid import nodes from astroid._cache import CACHE_MANAGER from astroid.const import BRAIN_MODULES_DIRECTORY +from astroid.context import InferenceContext from astroid.exceptions import AstroidBuildingError, AstroidImportError from astroid.interpreter._import import spec, util from astroid.modutils import ( @@ -33,15 +35,12 @@ from astroid.modutils import ( modpath_from_file, ) from astroid.transforms import TransformVisitor -from astroid.typing import AstroidManagerBrain - -if TYPE_CHECKING: - from astroid import nodes +from astroid.typing import AstroidManagerBrain, InferenceResult ZIP_IMPORT_EXTS = (".zip", ".egg", ".whl", ".pyz", ".pyzw") -def safe_repr(obj): +def safe_repr(obj: Any) -> str: try: return repr(obj) except Exception: # pylint: disable=broad-except @@ -91,11 +90,17 @@ class AstroidManager: def builtins_module(self) -> nodes.Module: return self.astroid_cache["builtins"] - def visit_transforms(self, node): + def visit_transforms(self, node: nodes.NodeNG) -> InferenceResult: """Visit the transforms and apply them to the given *node*.""" return self._transform.visit(node) - def ast_from_file(self, filepath, modname=None, fallback=True, source=False): + def ast_from_file( + self, + filepath: str, + modname: str | None = None, + fallback: bool = True, + source: bool = False, + ) -> nodes.Module: """given a module name, return the astroid object""" try: filepath = get_source_file(filepath, include_no_ext=True) @@ -121,20 +126,24 @@ class AstroidManager: return self.ast_from_module_name(modname) raise AstroidBuildingError("Unable to build an AST for {path}.", path=filepath) - def ast_from_string(self, data, modname="", filepath=None): + def ast_from_string( + self, data: str, modname: str = "", filepath: str | None = None + ) -> nodes.Module: """Given some source code as a string, return its corresponding astroid object""" # pylint: disable=import-outside-toplevel; circular import from astroid.builder import AstroidBuilder return AstroidBuilder(self).string_build(data, modname, filepath) - def _build_stub_module(self, modname): + def _build_stub_module(self, modname: str) -> nodes.Module: # pylint: disable=import-outside-toplevel; circular import from astroid.builder import AstroidBuilder return AstroidBuilder(self).string_build("", modname) - def _build_namespace_module(self, modname: str, path: list[str]) -> nodes.Module: + def _build_namespace_module( + self, modname: str, path: Sequence[str] + ) -> nodes.Module: # pylint: disable=import-outside-toplevel; circular import from astroid.builder import build_namespace_package_module @@ -184,14 +193,14 @@ class AstroidManager: ): return self._build_stub_module(modname) try: - module = load_module_from_name(modname) + named_module = load_module_from_name(modname) except Exception as e: raise AstroidImportError( "Loading {modname} failed with:\n{error}", modname=modname, path=found_spec.location, ) from e - return self.ast_from_module(module, modname) + return self.ast_from_module(named_module, modname) elif found_spec.type == spec.ModuleType.PY_COMPILED: raise AstroidImportError( @@ -202,7 +211,7 @@ class AstroidManager: elif found_spec.type == spec.ModuleType.PY_NAMESPACE: return self._build_namespace_module( - modname, found_spec.submodule_search_locations + modname, found_spec.submodule_search_locations or [] ) elif found_spec.type == spec.ModuleType.PY_FROZEN: if found_spec.location is None: @@ -228,7 +237,7 @@ class AstroidManager: if context_file: os.chdir(old_cwd) - def zip_import_data(self, filepath): + def zip_import_data(self, filepath: str) -> nodes.Module | None: if zipimport is None: return None @@ -255,7 +264,9 @@ class AstroidManager: continue return None - def file_from_module_name(self, modname, contextfile): + def file_from_module_name( + self, modname: str, contextfile: str | None + ) -> spec.ModuleSpec: try: value = self._mod_file_cache[(modname, contextfile)] except KeyError: @@ -277,7 +288,9 @@ class AstroidManager: raise value.with_traceback(None) # pylint: disable=no-member return value - def ast_from_module(self, module: types.ModuleType, modname: str | None = None): + def ast_from_module( + self, module: types.ModuleType, modname: str | None = None + ) -> nodes.Module: """given an imported module, return the astroid object""" modname = modname or module.__name__ if modname in self.astroid_cache: @@ -286,7 +299,8 @@ class AstroidManager: # some builtin modules don't have __file__ attribute filepath = module.__file__ if is_python_source(filepath): - return self.ast_from_file(filepath, modname) + # Type is checked in is_python_source + return self.ast_from_file(filepath, modname) # type: ignore[arg-type] except AttributeError: pass @@ -295,7 +309,7 @@ class AstroidManager: return AstroidBuilder(self).module_build(module, modname) - def ast_from_class(self, klass, modname=None): + def ast_from_class(self, klass: type, modname: str | None = None) -> nodes.ClassDef: """get astroid for the given class""" if modname is None: try: @@ -308,14 +322,24 @@ class AstroidManager: modname=modname, ) from exc modastroid = self.ast_from_module_name(modname) - return modastroid.getattr(klass.__name__)[0] # XXX + ret = modastroid.getattr(klass.__name__)[0] + assert isinstance(ret, nodes.ClassDef) + return ret - def infer_ast_from_something(self, obj, context=None): + def infer_ast_from_something( + self, obj: object, context: InferenceContext | None = None + ) -> Iterator[InferenceResult]: """infer astroid for the given class""" if hasattr(obj, "__class__") and not isinstance(obj, type): klass = obj.__class__ - else: + elif isinstance(obj, type): klass = obj + else: + raise AstroidBuildingError( # pragma: no cover + "Unable to get type for {class_repr}.", + cls=None, + class_repr=safe_repr(obj), + ) try: modname = klass.__module__ except AttributeError as exc: @@ -364,7 +388,7 @@ class AstroidManager: """ self._failed_import_hooks.append(hook) - def cache_module(self, module): + def cache_module(self, module: nodes.Module) -> None: """Cache a module if no module with the same name is known yet.""" self.astroid_cache.setdefault(module.name, module) diff --git a/astroid/raw_building.py b/astroid/raw_building.py index 8cff41d3..a18e7188 100644 --- a/astroid/raw_building.py +++ b/astroid/raw_building.py @@ -486,7 +486,7 @@ def _set_proxied(const): return _CONST_PROXY[const.value.__class__] -def _astroid_bootstrapping(): +def _astroid_bootstrapping() -> None: """astroid bootstrapping the builtins module""" # this boot strapping is necessary since we need the Const nodes to # inspect_build builtins, and then we can proxy Const |