From 1e06ce2d7083721792faf02c97ba0344f2590772 Mon Sep 17 00:00:00 2001 From: Jacob Walls Date: Sat, 30 Sep 2023 11:50:47 -0400 Subject: [PATCH 1/3] Make manager required in AstroidBuilder/InspectBuilder --- ChangeLog | 2 + astroid/brain/brain_nose.py | 4 +- astroid/builder.py | 21 +- astroid/interpreter/_import/spec.py | 6 +- astroid/manager.py | 19 +- astroid/raw_building.py | 14 +- astroid/rebuilder.py | 456 ++++++++++++++++------------ tests/resources.py | 3 +- tests/test_builder.py | 5 +- tests/test_inference.py | 3 +- tests/test_nodes.py | 2 +- tests/test_python3.py | 3 +- tests/test_raw_building.py | 9 +- tests/test_regrtest.py | 17 +- tests/test_scoped_nodes.py | 9 +- tests/test_transforms.py | 6 +- 16 files changed, 327 insertions(+), 252 deletions(-) diff --git a/ChangeLog b/ChangeLog index ccb9e7493c..6d34bf5b04 100644 --- a/ChangeLog +++ b/ChangeLog @@ -10,6 +10,8 @@ Release date: TBA * Removed internal functions ``infer_numpy_member``, ``name_looks_like_numpy_member``, and ``attribute_looks_like_numpy_member`` from ``astroid.brain.brain_numpy_utils``. +* To alleviate circular imports, the ``manager`` argument to ``AstroidBuilder()`` is now required. + * Constants now have a parent of ``nodes.SYNTHETIC_ROOT``. * Fix crashes with large positive and negative list multipliers. diff --git a/astroid/brain/brain_nose.py b/astroid/brain/brain_nose.py index 742418f2d5..b194414d2a 100644 --- a/astroid/brain/brain_nose.py +++ b/astroid/brain/brain_nose.py @@ -23,7 +23,7 @@ def _pep8(name, caps=CAPITALS): def _nose_tools_functions(): """Get an iterator of names and bound methods.""" - module = AstroidBuilder().string_build( + module = AstroidBuilder(AstroidManager()).string_build( textwrap.dedent( """ import unittest @@ -54,7 +54,7 @@ def _nose_tools_transform(node): def _nose_tools_trivial_transform(): """Custom transform for the nose.tools module.""" - stub = AstroidBuilder().string_build("""__all__ = []""") + stub = AstroidBuilder(AstroidManager()).string_build("""__all__ = []""") all_entries = ["ok_", "eq_"] for pep8_name, method in _nose_tools_functions(): diff --git a/astroid/builder.py b/astroid/builder.py index b80090b516..6fa7be683e 100644 --- a/astroid/builder.py +++ b/astroid/builder.py @@ -19,12 +19,15 @@ from collections.abc import Iterator, Sequence from io import TextIOWrapper from tokenize import detect_encoding +from typing import TYPE_CHECKING from astroid import bases, modutils, nodes, raw_building, rebuilder, util from astroid._ast import ParserModule, get_parser_module from astroid.const import PY312_PLUS from astroid.exceptions import AstroidBuildingError, AstroidSyntaxError, InferenceError -from astroid.manager import AstroidManager + +if TYPE_CHECKING: + from astroid.manager import AstroidManager # The name of the transient function that is used to # wrap expressions to be extracted when calling @@ -62,20 +65,17 @@ def _can_assign_attr(node: nodes.ClassDef, attrname: str | None) -> bool: class AstroidBuilder(raw_building.InspectBuilder): """Class for building an astroid tree from source code or from a live module. - The param *manager* specifies the manager class which should be used. - If no manager is given, then the default one will be used. The + The param *manager* specifies the manager class which should be used. The param *apply_transforms* determines if the transforms should be applied after the tree was built from source or from a live object, by default being True. """ - def __init__( - self, manager: AstroidManager | None = None, apply_transforms: bool = True - ) -> None: + def __init__(self, manager: AstroidManager, apply_transforms: bool = True) -> None: super().__init__(manager) self._apply_transforms = apply_transforms if not raw_building.InspectBuilder.bootstrapped: - raw_building._astroid_bootstrapping() + manager.bootstrap() def module_build( self, module: types.ModuleType, modname: str | None = None @@ -292,10 +292,11 @@ def parse( Apply the transforms for the give code. Use it if you don't want the default transforms to be applied. """ + # pylint: disable-next=import-outside-toplevel + from astroid.manager import AstroidManager + code = textwrap.dedent(code) - builder = AstroidBuilder( - manager=AstroidManager(), apply_transforms=apply_transforms - ) + builder = AstroidBuilder(AstroidManager(), apply_transforms=apply_transforms) return builder.string_build(code, modname=module_name, path=path) diff --git a/astroid/interpreter/_import/spec.py b/astroid/interpreter/_import/spec.py index 48a012a882..1e4073ecf6 100644 --- a/astroid/interpreter/_import/spec.py +++ b/astroid/interpreter/_import/spec.py @@ -21,7 +21,6 @@ from typing import Literal, NamedTuple, Protocol from astroid.const import PY310_PLUS -from astroid.modutils import EXT_LIB_DIRS, cached_os_path_isfile from . import util @@ -134,6 +133,9 @@ def find_module( processed: tuple[str, ...], submodule_path: tuple[str, ...] | None, ) -> ModuleSpec | None: + # pylint: disable-next=import-outside-toplevel + from astroid.modutils import cached_os_path_isfile + # Although we should be able to use `find_spec` this doesn't work on PyPy for builtins. # Therefore, we use the `builtin_module_nams` heuristic for these. if submodule_path is None and modname in sys.builtin_module_names: @@ -225,6 +227,8 @@ def contribute_to_path( if spec.location is None: # Builtin. return None + # pylint: disable-next=import-outside-toplevel + from astroid.modutils import EXT_LIB_DIRS if _is_setuptools_namespace(Path(spec.location)): # extend_path is called, search sys.path for module/packages diff --git a/astroid/manager.py b/astroid/manager.py index 87420585c4..e1827ab88d 100644 --- a/astroid/manager.py +++ b/astroid/manager.py @@ -17,6 +17,7 @@ from typing import Any, ClassVar from astroid import nodes +from astroid.builder import AstroidBuilder, build_namespace_package_module from astroid.context import InferenceContext, _invalidate_cache from astroid.exceptions import AstroidBuildingError, AstroidImportError from astroid.interpreter._import import spec, util @@ -161,9 +162,6 @@ def ast_from_file( ): return self.astroid_cache[modname] if source: - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import AstroidBuilder - return AstroidBuilder(self).file_build(filepath, modname) if fallback and modname: return self.ast_from_module_name(modname) @@ -175,23 +173,14 @@ def ast_from_string( """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: 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: Sequence[str] ) -> nodes.Module: - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import build_namespace_package_module - return build_namespace_package_module(modname, path) def _can_load_extension(self, modname: str) -> bool: @@ -290,9 +279,6 @@ def zip_import_data(self, filepath: str) -> nodes.Module | None: if zipimport is None: return None - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import AstroidBuilder - builder = AstroidBuilder(self) for ext in ZIP_IMPORT_EXTS: try: @@ -351,9 +337,6 @@ def ast_from_module( except AttributeError: pass - # pylint: disable=import-outside-toplevel; circular import - from astroid.builder import AstroidBuilder - return AstroidBuilder(self).module_build(module, modname) def ast_from_class(self, klass: type, modname: str | None = None) -> nodes.ClassDef: diff --git a/astroid/raw_building.py b/astroid/raw_building.py index c1f7ec158d..2d872b943b 100644 --- a/astroid/raw_building.py +++ b/astroid/raw_building.py @@ -22,7 +22,6 @@ from astroid import bases, nodes from astroid.const import _EMPTY_OBJECT_MARKER, IS_PYPY -from astroid.manager import AstroidManager from astroid.nodes import node_classes logger = logging.getLogger(__name__) @@ -37,8 +36,6 @@ types.ClassMethodDescriptorType, ] -# the keys of CONST_CLS eg python builtin types -_CONSTANTS = tuple(node_classes.CONST_CLS) TYPE_NONE = type(None) TYPE_NOTIMPLEMENTED = type(NotImplemented) TYPE_ELLIPSIS = type(...) @@ -424,8 +421,8 @@ class InspectBuilder: bootstrapped: bool = False - def __init__(self, manager_instance: AstroidManager | None = None) -> None: - self._manager = manager_instance or AstroidManager() + def __init__(self, manager_instance) -> None: + self._manager = manager_instance self._done: dict[types.ModuleType | type, nodes.Module | nodes.ClassDef] = {} self._module: types.ModuleType @@ -502,7 +499,7 @@ def object_build( child: nodes.NodeNG = object_build_methoddescriptor(node, member) elif inspect.isdatadescriptor(member): child = object_build_datadescriptor(node, member) - elif isinstance(member, _CONSTANTS): + elif isinstance(member, tuple(node_classes.CONST_CLS)): if alias in node.special_attributes: continue child = nodes.const_factory(member) @@ -595,7 +592,10 @@ 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 - builder = InspectBuilder() + # pylint: disable-next=import-outside-toplevel + from astroid.manager import AstroidManager + + builder = InspectBuilder(AstroidManager()) astroid_builtin = builder.inspect_build(builtins) for cls, node_cls in node_classes.CONST_CLS.items(): diff --git a/astroid/rebuilder.py b/astroid/rebuilder.py index 4c77906e02..b208754c07 100644 --- a/astroid/rebuilder.py +++ b/astroid/rebuilder.py @@ -19,12 +19,24 @@ from astroid import nodes from astroid._ast import ParserModule, get_parser_module, parse_function_type_comment from astroid.const import PY312_PLUS, Context -from astroid.manager import AstroidManager -from astroid.nodes import NodeNG -from astroid.nodes.node_classes import AssignName from astroid.nodes.utils import Position from astroid.typing import InferenceResult +if TYPE_CHECKING: + from astroid.manager import AstroidManager + + T_Doc = TypeVar( + "T_Doc", + "ast.Module", + "ast.ClassDef", + Union["ast.FunctionDef", "ast.AsyncFunctionDef"], + ) + _FunctionT = TypeVar("_FunctionT", nodes.FunctionDef, nodes.AsyncFunctionDef) + _ForT = TypeVar("_ForT", nodes.For, nodes.AsyncFor) + _WithT = TypeVar("_WithT", nodes.With, nodes.AsyncWith) + NodesWithDocsType = Union[nodes.Module, nodes.ClassDef, nodes.FunctionDef] + + REDIRECT: Final[dict[str, str]] = { "arguments": "Arguments", "comprehension": "Comprehension", @@ -36,18 +48,6 @@ } -T_Doc = TypeVar( - "T_Doc", - "ast.Module", - "ast.ClassDef", - Union["ast.FunctionDef", "ast.AsyncFunctionDef"], -) -_FunctionT = TypeVar("_FunctionT", nodes.FunctionDef, nodes.AsyncFunctionDef) -_ForT = TypeVar("_ForT", nodes.For, nodes.AsyncFor) -_WithT = TypeVar("_WithT", nodes.With, nodes.AsyncWith) -NodesWithDocsType = Union[nodes.Module, nodes.ClassDef, nodes.FunctionDef] - - # noinspection PyMethodMayBeStatic class TreeRebuilder: """Rebuilds the _ast tree to become an Astroid tree.""" @@ -63,7 +63,9 @@ def __init__( self._global_names: list[dict[str, list[nodes.Global]]] = [] self._import_from_nodes: list[nodes.ImportFrom] = [] self._delayed_assattr: list[nodes.AssignAttr] = [] - self._visit_meths: dict[type[ast.AST], Callable[[ast.AST, NodeNG], NodeNG]] = {} + self._visit_meths: dict[ + type[ast.AST], Callable[[ast.AST, nodes.NodeNG], nodes.NodeNG] + ] = {} if parser_module is None: self._parser_module = get_parser_module() @@ -176,265 +178,303 @@ def visit_module( if TYPE_CHECKING: # noqa: C901 @overload - def visit(self, node: ast.arg, parent: NodeNG) -> nodes.AssignName: ... + def visit(self, node: ast.arg, parent: nodes.NodeNG) -> nodes.AssignName: ... @overload - def visit(self, node: ast.arguments, parent: NodeNG) -> nodes.Arguments: ... + def visit( + self, node: ast.arguments, parent: nodes.NodeNG + ) -> nodes.Arguments: ... @overload - def visit(self, node: ast.Assert, parent: NodeNG) -> nodes.Assert: ... + def visit(self, node: ast.Assert, parent: nodes.NodeNG) -> nodes.Assert: ... @overload def visit( - self, node: ast.AsyncFunctionDef, parent: NodeNG + self, node: ast.AsyncFunctionDef, parent: nodes.NodeNG ) -> nodes.AsyncFunctionDef: ... @overload - def visit(self, node: ast.AsyncFor, parent: NodeNG) -> nodes.AsyncFor: ... + def visit(self, node: ast.AsyncFor, parent: nodes.NodeNG) -> nodes.AsyncFor: ... @overload - def visit(self, node: ast.Await, parent: NodeNG) -> nodes.Await: ... + def visit(self, node: ast.Await, parent: nodes.NodeNG) -> nodes.Await: ... @overload - def visit(self, node: ast.AsyncWith, parent: NodeNG) -> nodes.AsyncWith: ... + def visit( + self, node: ast.AsyncWith, parent: nodes.NodeNG + ) -> nodes.AsyncWith: ... @overload - def visit(self, node: ast.Assign, parent: NodeNG) -> nodes.Assign: ... + def visit(self, node: ast.Assign, parent: nodes.NodeNG) -> nodes.Assign: ... @overload - def visit(self, node: ast.AnnAssign, parent: NodeNG) -> nodes.AnnAssign: ... + def visit( + self, node: ast.AnnAssign, parent: nodes.NodeNG + ) -> nodes.AnnAssign: ... @overload - def visit(self, node: ast.AugAssign, parent: NodeNG) -> nodes.AugAssign: ... + def visit( + self, node: ast.AugAssign, parent: nodes.NodeNG + ) -> nodes.AugAssign: ... @overload - def visit(self, node: ast.BinOp, parent: NodeNG) -> nodes.BinOp: ... + def visit(self, node: ast.BinOp, parent: nodes.NodeNG) -> nodes.BinOp: ... @overload - def visit(self, node: ast.BoolOp, parent: NodeNG) -> nodes.BoolOp: ... + def visit(self, node: ast.BoolOp, parent: nodes.NodeNG) -> nodes.BoolOp: ... @overload - def visit(self, node: ast.Break, parent: NodeNG) -> nodes.Break: ... + def visit(self, node: ast.Break, parent: nodes.NodeNG) -> nodes.Break: ... @overload - def visit(self, node: ast.Call, parent: NodeNG) -> nodes.Call: ... + def visit(self, node: ast.Call, parent: nodes.NodeNG) -> nodes.Call: ... @overload - def visit(self, node: ast.ClassDef, parent: NodeNG) -> nodes.ClassDef: ... + def visit(self, node: ast.ClassDef, parent: nodes.NodeNG) -> nodes.ClassDef: ... @overload - def visit(self, node: ast.Continue, parent: NodeNG) -> nodes.Continue: ... + def visit(self, node: ast.Continue, parent: nodes.NodeNG) -> nodes.Continue: ... @overload - def visit(self, node: ast.Compare, parent: NodeNG) -> nodes.Compare: ... + def visit(self, node: ast.Compare, parent: nodes.NodeNG) -> nodes.Compare: ... @overload def visit( - self, node: ast.comprehension, parent: NodeNG + self, node: ast.comprehension, parent: nodes.NodeNG ) -> nodes.Comprehension: ... @overload - def visit(self, node: ast.Delete, parent: NodeNG) -> nodes.Delete: ... + def visit(self, node: ast.Delete, parent: nodes.NodeNG) -> nodes.Delete: ... @overload - def visit(self, node: ast.Dict, parent: NodeNG) -> nodes.Dict: ... + def visit(self, node: ast.Dict, parent: nodes.NodeNG) -> nodes.Dict: ... @overload - def visit(self, node: ast.DictComp, parent: NodeNG) -> nodes.DictComp: ... + def visit(self, node: ast.DictComp, parent: nodes.NodeNG) -> nodes.DictComp: ... @overload - def visit(self, node: ast.Expr, parent: NodeNG) -> nodes.Expr: ... + def visit(self, node: ast.Expr, parent: nodes.NodeNG) -> nodes.Expr: ... @overload def visit( - self, node: ast.ExceptHandler, parent: NodeNG + self, node: ast.ExceptHandler, parent: nodes.NodeNG ) -> nodes.ExceptHandler: ... @overload - def visit(self, node: ast.For, parent: NodeNG) -> nodes.For: ... + def visit(self, node: ast.For, parent: nodes.NodeNG) -> nodes.For: ... @overload - def visit(self, node: ast.ImportFrom, parent: NodeNG) -> nodes.ImportFrom: ... + def visit( + self, node: ast.ImportFrom, parent: nodes.NodeNG + ) -> nodes.ImportFrom: ... @overload - def visit(self, node: ast.FunctionDef, parent: NodeNG) -> nodes.FunctionDef: ... + def visit( + self, node: ast.FunctionDef, parent: nodes.NodeNG + ) -> nodes.FunctionDef: ... @overload def visit( - self, node: ast.GeneratorExp, parent: NodeNG + self, node: ast.GeneratorExp, parent: nodes.NodeNG ) -> nodes.GeneratorExp: ... @overload - def visit(self, node: ast.Attribute, parent: NodeNG) -> nodes.Attribute: ... + def visit( + self, node: ast.Attribute, parent: nodes.NodeNG + ) -> nodes.Attribute: ... @overload - def visit(self, node: ast.Global, parent: NodeNG) -> nodes.Global: ... + def visit(self, node: ast.Global, parent: nodes.NodeNG) -> nodes.Global: ... @overload - def visit(self, node: ast.If, parent: NodeNG) -> nodes.If: ... + def visit(self, node: ast.If, parent: nodes.NodeNG) -> nodes.If: ... @overload - def visit(self, node: ast.IfExp, parent: NodeNG) -> nodes.IfExp: ... + def visit(self, node: ast.IfExp, parent: nodes.NodeNG) -> nodes.IfExp: ... @overload - def visit(self, node: ast.Import, parent: NodeNG) -> nodes.Import: ... + def visit(self, node: ast.Import, parent: nodes.NodeNG) -> nodes.Import: ... @overload - def visit(self, node: ast.JoinedStr, parent: NodeNG) -> nodes.JoinedStr: ... + def visit( + self, node: ast.JoinedStr, parent: nodes.NodeNG + ) -> nodes.JoinedStr: ... @overload def visit( - self, node: ast.FormattedValue, parent: NodeNG + self, node: ast.FormattedValue, parent: nodes.NodeNG ) -> nodes.FormattedValue: ... @overload - def visit(self, node: ast.NamedExpr, parent: NodeNG) -> nodes.NamedExpr: ... + def visit( + self, node: ast.NamedExpr, parent: nodes.NodeNG + ) -> nodes.NamedExpr: ... @overload - def visit(self, node: ast.keyword, parent: NodeNG) -> nodes.Keyword: ... + def visit(self, node: ast.keyword, parent: nodes.NodeNG) -> nodes.Keyword: ... @overload - def visit(self, node: ast.Lambda, parent: NodeNG) -> nodes.Lambda: ... + def visit(self, node: ast.Lambda, parent: nodes.NodeNG) -> nodes.Lambda: ... @overload - def visit(self, node: ast.List, parent: NodeNG) -> nodes.List: ... + def visit(self, node: ast.List, parent: nodes.NodeNG) -> nodes.List: ... @overload - def visit(self, node: ast.ListComp, parent: NodeNG) -> nodes.ListComp: ... + def visit(self, node: ast.ListComp, parent: nodes.NodeNG) -> nodes.ListComp: ... @overload def visit( - self, node: ast.Name, parent: NodeNG + self, node: ast.Name, parent: nodes.NodeNG ) -> nodes.Name | nodes.Const | nodes.AssignName | nodes.DelName: ... @overload - def visit(self, node: ast.Nonlocal, parent: NodeNG) -> nodes.Nonlocal: ... + def visit(self, node: ast.Nonlocal, parent: nodes.NodeNG) -> nodes.Nonlocal: ... @overload - def visit(self, node: ast.Constant, parent: NodeNG) -> nodes.Const: ... + def visit(self, node: ast.Constant, parent: nodes.NodeNG) -> nodes.Const: ... if sys.version_info >= (3, 12): @overload - def visit(self, node: ast.ParamSpec, parent: NodeNG) -> nodes.ParamSpec: ... + def visit( + self, node: ast.ParamSpec, parent: nodes.NodeNG + ) -> nodes.ParamSpec: ... @overload - def visit(self, node: ast.Pass, parent: NodeNG) -> nodes.Pass: ... + def visit(self, node: ast.Pass, parent: nodes.NodeNG) -> nodes.Pass: ... @overload - def visit(self, node: ast.Raise, parent: NodeNG) -> nodes.Raise: ... + def visit(self, node: ast.Raise, parent: nodes.NodeNG) -> nodes.Raise: ... @overload - def visit(self, node: ast.Return, parent: NodeNG) -> nodes.Return: ... + def visit(self, node: ast.Return, parent: nodes.NodeNG) -> nodes.Return: ... @overload - def visit(self, node: ast.Set, parent: NodeNG) -> nodes.Set: ... + def visit(self, node: ast.Set, parent: nodes.NodeNG) -> nodes.Set: ... @overload - def visit(self, node: ast.SetComp, parent: NodeNG) -> nodes.SetComp: ... + def visit(self, node: ast.SetComp, parent: nodes.NodeNG) -> nodes.SetComp: ... @overload def visit(self, node: ast.Slice, parent: nodes.Subscript) -> nodes.Slice: ... @overload - def visit(self, node: ast.Subscript, parent: NodeNG) -> nodes.Subscript: ... + def visit( + self, node: ast.Subscript, parent: nodes.NodeNG + ) -> nodes.Subscript: ... @overload - def visit(self, node: ast.Starred, parent: NodeNG) -> nodes.Starred: ... + def visit(self, node: ast.Starred, parent: nodes.NodeNG) -> nodes.Starred: ... @overload - def visit(self, node: ast.Try, parent: NodeNG) -> nodes.Try: ... + def visit(self, node: ast.Try, parent: nodes.NodeNG) -> nodes.Try: ... if sys.version_info >= (3, 11): @overload - def visit(self, node: ast.TryStar, parent: NodeNG) -> nodes.TryStar: ... + def visit( + self, node: ast.TryStar, parent: nodes.NodeNG + ) -> nodes.TryStar: ... @overload - def visit(self, node: ast.Tuple, parent: NodeNG) -> nodes.Tuple: ... + def visit(self, node: ast.Tuple, parent: nodes.NodeNG) -> nodes.Tuple: ... if sys.version_info >= (3, 12): @overload - def visit(self, node: ast.TypeAlias, parent: NodeNG) -> nodes.TypeAlias: ... + def visit( + self, node: ast.TypeAlias, parent: nodes.NodeNG + ) -> nodes.TypeAlias: ... @overload - def visit(self, node: ast.TypeVar, parent: NodeNG) -> nodes.TypeVar: ... + def visit( + self, node: ast.TypeVar, parent: nodes.NodeNG + ) -> nodes.TypeVar: ... @overload def visit( - self, node: ast.TypeVarTuple, parent: NodeNG + self, node: ast.TypeVarTuple, parent: nodes.NodeNG ) -> nodes.TypeVarTuple: ... @overload - def visit(self, node: ast.UnaryOp, parent: NodeNG) -> nodes.UnaryOp: ... + def visit(self, node: ast.UnaryOp, parent: nodes.NodeNG) -> nodes.UnaryOp: ... @overload - def visit(self, node: ast.While, parent: NodeNG) -> nodes.While: ... + def visit(self, node: ast.While, parent: nodes.NodeNG) -> nodes.While: ... @overload - def visit(self, node: ast.With, parent: NodeNG) -> nodes.With: ... + def visit(self, node: ast.With, parent: nodes.NodeNG) -> nodes.With: ... @overload - def visit(self, node: ast.Yield, parent: NodeNG) -> nodes.Yield: ... + def visit(self, node: ast.Yield, parent: nodes.NodeNG) -> nodes.Yield: ... @overload - def visit(self, node: ast.YieldFrom, parent: NodeNG) -> nodes.YieldFrom: ... + def visit( + self, node: ast.YieldFrom, parent: nodes.NodeNG + ) -> nodes.YieldFrom: ... if sys.version_info >= (3, 10): @overload - def visit(self, node: ast.Match, parent: NodeNG) -> nodes.Match: ... + def visit(self, node: ast.Match, parent: nodes.NodeNG) -> nodes.Match: ... @overload def visit( - self, node: ast.match_case, parent: NodeNG + self, node: ast.match_case, parent: nodes.NodeNG ) -> nodes.MatchCase: ... @overload def visit( - self, node: ast.MatchValue, parent: NodeNG + self, node: ast.MatchValue, parent: nodes.NodeNG ) -> nodes.MatchValue: ... @overload def visit( - self, node: ast.MatchSingleton, parent: NodeNG + self, node: ast.MatchSingleton, parent: nodes.NodeNG ) -> nodes.MatchSingleton: ... @overload def visit( - self, node: ast.MatchSequence, parent: NodeNG + self, node: ast.MatchSequence, parent: nodes.NodeNG ) -> nodes.MatchSequence: ... @overload def visit( - self, node: ast.MatchMapping, parent: NodeNG + self, node: ast.MatchMapping, parent: nodes.NodeNG ) -> nodes.MatchMapping: ... @overload def visit( - self, node: ast.MatchClass, parent: NodeNG + self, node: ast.MatchClass, parent: nodes.NodeNG ) -> nodes.MatchClass: ... @overload - def visit(self, node: ast.MatchStar, parent: NodeNG) -> nodes.MatchStar: ... + def visit( + self, node: ast.MatchStar, parent: nodes.NodeNG + ) -> nodes.MatchStar: ... @overload - def visit(self, node: ast.MatchAs, parent: NodeNG) -> nodes.MatchAs: ... + def visit( + self, node: ast.MatchAs, parent: nodes.NodeNG + ) -> nodes.MatchAs: ... @overload - def visit(self, node: ast.MatchOr, parent: NodeNG) -> nodes.MatchOr: ... + def visit( + self, node: ast.MatchOr, parent: nodes.NodeNG + ) -> nodes.MatchOr: ... @overload - def visit(self, node: ast.pattern, parent: NodeNG) -> nodes.Pattern: ... + def visit( + self, node: ast.pattern, parent: nodes.NodeNG + ) -> nodes.Pattern: ... @overload - def visit(self, node: ast.AST, parent: NodeNG) -> NodeNG: ... + def visit(self, node: ast.AST, parent: nodes.NodeNG) -> nodes.NodeNG: ... @overload - def visit(self, node: None, parent: NodeNG) -> None: ... + def visit(self, node: None, parent: nodes.NodeNG) -> None: ... - def visit(self, node: ast.AST | None, parent: NodeNG) -> NodeNG | None: + def visit(self, node: ast.AST | None, parent: nodes.NodeNG) -> nodes.NodeNG | None: if node is None: return None cls = node.__class__ @@ -456,11 +496,13 @@ def _save_assignment(self, node: nodes.AssignName | nodes.DelName) -> None: assert node.name node.parent.set_local(node.name, node) - def visit_arg(self, node: ast.arg, parent: NodeNG) -> nodes.AssignName: + def visit_arg(self, node: ast.arg, parent: nodes.NodeNG) -> nodes.AssignName: """Visit an arg node by returning a fresh AssignName instance.""" return self.visit_assignname(node, parent, node.arg) - def visit_arguments(self, node: ast.arguments, parent: NodeNG) -> nodes.Arguments: + def visit_arguments( + self, node: ast.arguments, parent: nodes.NodeNG + ) -> nodes.Arguments: """Visit an Arguments node by returning a fresh instance of it.""" vararg: str | None = None kwarg: str | None = None @@ -472,7 +514,7 @@ def visit_arguments(self, node: ast.arguments, parent: NodeNG) -> nodes.Argument node.kwarg.arg if node.kwarg else None, parent, ( - AssignName( + nodes.AssignName( vararg_node.arg, vararg_node.lineno, vararg_node.col_offset, @@ -484,7 +526,7 @@ def visit_arguments(self, node: ast.arguments, parent: NodeNG) -> nodes.Argument else None ), ( - AssignName( + nodes.AssignName( kwarg_node.arg, kwarg_node.lineno, kwarg_node.col_offset, @@ -498,8 +540,8 @@ def visit_arguments(self, node: ast.arguments, parent: NodeNG) -> nodes.Argument ) args = [self.visit(child, newnode) for child in node.args] defaults = [self.visit(child, newnode) for child in node.defaults] - varargannotation: NodeNG | None = None - kwargannotation: NodeNG | None = None + varargannotation: nodes.NodeNG | None = None + kwargannotation: nodes.NodeNG | None = None if node.vararg: vararg = node.vararg.arg varargannotation = self.visit(node.vararg.annotation, newnode) @@ -551,7 +593,7 @@ def visit_arguments(self, node: ast.arguments, parent: NodeNG) -> nodes.Argument newnode.parent.set_local(kwarg, newnode) return newnode - def visit_assert(self, node: ast.Assert, parent: NodeNG) -> nodes.Assert: + def visit_assert(self, node: ast.Assert, parent: nodes.NodeNG) -> nodes.Assert: """Visit a Assert node by returning a fresh instance of it.""" newnode = nodes.Assert( lineno=node.lineno, @@ -560,7 +602,7 @@ def visit_assert(self, node: ast.Assert, parent: NodeNG) -> nodes.Assert: end_col_offset=node.end_col_offset, parent=parent, ) - msg: NodeNG | None = None + msg: nodes.NodeNG | None = None if node.msg: msg = self.visit(node.msg, newnode) newnode.postinit(self.visit(node.test, newnode), msg) @@ -577,7 +619,7 @@ def check_type_comment( | nodes.With | nodes.AsyncWith ), - ) -> NodeNG | None: + ) -> nodes.NodeNG | None: if not node.type_comment: return None @@ -599,8 +641,8 @@ def check_type_comment( return type_object.value def check_function_type_comment( - self, node: ast.FunctionDef | ast.AsyncFunctionDef, parent: NodeNG - ) -> tuple[NodeNG | None, list[NodeNG]] | None: + self, node: ast.FunctionDef | ast.AsyncFunctionDef, parent: nodes.NodeNG + ) -> tuple[nodes.NodeNG | None, list[nodes.NodeNG]] | None: if not node.type_comment: return None @@ -613,8 +655,8 @@ def check_function_type_comment( if not type_comment_ast: return None - returns: NodeNG | None = None - argtypes: list[NodeNG] = [ + returns: nodes.NodeNG | None = None + argtypes: list[nodes.NodeNG] = [ self.visit(elem, parent) for elem in (type_comment_ast.argtypes or []) ] if type_comment_ast.returns: @@ -623,14 +665,16 @@ def check_function_type_comment( return returns, argtypes def visit_asyncfunctiondef( - self, node: ast.AsyncFunctionDef, parent: NodeNG + self, node: ast.AsyncFunctionDef, parent: nodes.NodeNG ) -> nodes.AsyncFunctionDef: return self._visit_functiondef(nodes.AsyncFunctionDef, node, parent) - def visit_asyncfor(self, node: ast.AsyncFor, parent: NodeNG) -> nodes.AsyncFor: + def visit_asyncfor( + self, node: ast.AsyncFor, parent: nodes.NodeNG + ) -> nodes.AsyncFor: return self._visit_for(nodes.AsyncFor, node, parent) - def visit_await(self, node: ast.Await, parent: NodeNG) -> nodes.Await: + def visit_await(self, node: ast.Await, parent: nodes.NodeNG) -> nodes.Await: newnode = nodes.Await( lineno=node.lineno, col_offset=node.col_offset, @@ -641,10 +685,12 @@ def visit_await(self, node: ast.Await, parent: NodeNG) -> nodes.Await: newnode.postinit(value=self.visit(node.value, newnode)) return newnode - def visit_asyncwith(self, node: ast.AsyncWith, parent: NodeNG) -> nodes.AsyncWith: + def visit_asyncwith( + self, node: ast.AsyncWith, parent: nodes.NodeNG + ) -> nodes.AsyncWith: return self._visit_with(nodes.AsyncWith, node, parent) - def visit_assign(self, node: ast.Assign, parent: NodeNG) -> nodes.Assign: + def visit_assign(self, node: ast.Assign, parent: nodes.NodeNG) -> nodes.Assign: """Visit a Assign node by returning a fresh instance of it.""" newnode = nodes.Assign( lineno=node.lineno, @@ -661,7 +707,9 @@ def visit_assign(self, node: ast.Assign, parent: NodeNG) -> nodes.Assign: ) return newnode - def visit_annassign(self, node: ast.AnnAssign, parent: NodeNG) -> nodes.AnnAssign: + def visit_annassign( + self, node: ast.AnnAssign, parent: nodes.NodeNG + ) -> nodes.AnnAssign: """Visit an AnnAssign node by returning a fresh instance of it.""" newnode = nodes.AnnAssign( lineno=node.lineno, @@ -680,16 +728,16 @@ def visit_annassign(self, node: ast.AnnAssign, parent: NodeNG) -> nodes.AnnAssig @overload def visit_assignname( - self, node: ast.AST, parent: NodeNG, node_name: str + self, node: ast.AST, parent: nodes.NodeNG, node_name: str ) -> nodes.AssignName: ... @overload def visit_assignname( - self, node: ast.AST, parent: NodeNG, node_name: None + self, node: ast.AST, parent: nodes.NodeNG, node_name: None ) -> None: ... def visit_assignname( - self, node: ast.AST, parent: NodeNG, node_name: str | None + self, node: ast.AST, parent: nodes.NodeNG, node_name: str | None ) -> nodes.AssignName | None: """Visit a node and return a AssignName node. @@ -708,7 +756,9 @@ def visit_assignname( self._save_assignment(newnode) return newnode - def visit_augassign(self, node: ast.AugAssign, parent: NodeNG) -> nodes.AugAssign: + def visit_augassign( + self, node: ast.AugAssign, parent: nodes.NodeNG + ) -> nodes.AugAssign: """Visit a AugAssign node by returning a fresh instance of it.""" newnode = nodes.AugAssign( op=self._parser_module.bin_op_classes[type(node.op)] + "=", @@ -723,7 +773,7 @@ def visit_augassign(self, node: ast.AugAssign, parent: NodeNG) -> nodes.AugAssig ) return newnode - def visit_binop(self, node: ast.BinOp, parent: NodeNG) -> nodes.BinOp: + def visit_binop(self, node: ast.BinOp, parent: nodes.NodeNG) -> nodes.BinOp: """Visit a BinOp node by returning a fresh instance of it.""" newnode = nodes.BinOp( op=self._parser_module.bin_op_classes[type(node.op)], @@ -738,7 +788,7 @@ def visit_binop(self, node: ast.BinOp, parent: NodeNG) -> nodes.BinOp: ) return newnode - def visit_boolop(self, node: ast.BoolOp, parent: NodeNG) -> nodes.BoolOp: + def visit_boolop(self, node: ast.BoolOp, parent: nodes.NodeNG) -> nodes.BoolOp: """Visit a BoolOp node by returning a fresh instance of it.""" newnode = nodes.BoolOp( op=self._parser_module.bool_op_classes[type(node.op)], @@ -751,7 +801,7 @@ def visit_boolop(self, node: ast.BoolOp, parent: NodeNG) -> nodes.BoolOp: newnode.postinit([self.visit(child, newnode) for child in node.values]) return newnode - def visit_break(self, node: ast.Break, parent: NodeNG) -> nodes.Break: + def visit_break(self, node: ast.Break, parent: nodes.NodeNG) -> nodes.Break: """Visit a Break node by returning a fresh instance of it.""" return nodes.Break( lineno=node.lineno, @@ -761,7 +811,7 @@ def visit_break(self, node: ast.Break, parent: NodeNG) -> nodes.Break: parent=parent, ) - def visit_call(self, node: ast.Call, parent: NodeNG) -> nodes.Call: + def visit_call(self, node: ast.Call, parent: nodes.NodeNG) -> nodes.Call: """Visit a CallFunc node by returning a fresh instance of it.""" newnode = nodes.Call( lineno=node.lineno, @@ -778,7 +828,7 @@ def visit_call(self, node: ast.Call, parent: NodeNG) -> nodes.Call: return newnode def visit_classdef( - self, node: ast.ClassDef, parent: NodeNG, newstyle: bool = True + self, node: ast.ClassDef, parent: nodes.NodeNG, newstyle: bool = True ) -> nodes.ClassDef: """Visit a ClassDef node to become astroid.""" node, doc_ast_node = self._get_doc(node) @@ -818,7 +868,9 @@ def visit_classdef( parent.set_local(newnode.name, newnode) return newnode - def visit_continue(self, node: ast.Continue, parent: NodeNG) -> nodes.Continue: + def visit_continue( + self, node: ast.Continue, parent: nodes.NodeNG + ) -> nodes.Continue: """Visit a Continue node by returning a fresh instance of it.""" return nodes.Continue( lineno=node.lineno, @@ -828,7 +880,7 @@ def visit_continue(self, node: ast.Continue, parent: NodeNG) -> nodes.Continue: parent=parent, ) - def visit_compare(self, node: ast.Compare, parent: NodeNG) -> nodes.Compare: + def visit_compare(self, node: ast.Compare, parent: nodes.NodeNG) -> nodes.Compare: """Visit a Compare node by returning a fresh instance of it.""" newnode = nodes.Compare( lineno=node.lineno, @@ -850,7 +902,7 @@ def visit_compare(self, node: ast.Compare, parent: NodeNG) -> nodes.Compare: return newnode def visit_comprehension( - self, node: ast.comprehension, parent: NodeNG + self, node: ast.comprehension, parent: nodes.NodeNG ) -> nodes.Comprehension: """Visit a Comprehension node by returning a fresh instance of it.""" newnode = nodes.Comprehension( @@ -873,7 +925,7 @@ def visit_comprehension( def visit_decorators( self, node: ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef, - parent: NodeNG, + parent: nodes.NodeNG, ) -> nodes.Decorators | None: """Visit a Decorators node by returning a fresh instance of it. @@ -899,7 +951,7 @@ def visit_decorators( newnode.postinit([self.visit(child, newnode) for child in node.decorator_list]) return newnode - def visit_delete(self, node: ast.Delete, parent: NodeNG) -> nodes.Delete: + def visit_delete(self, node: ast.Delete, parent: nodes.NodeNG) -> nodes.Delete: """Visit a Delete node by returning a fresh instance of it.""" newnode = nodes.Delete( lineno=node.lineno, @@ -912,10 +964,10 @@ def visit_delete(self, node: ast.Delete, parent: NodeNG) -> nodes.Delete: return newnode def _visit_dict_items( - self, node: ast.Dict, parent: NodeNG, newnode: nodes.Dict - ) -> Generator[tuple[NodeNG, NodeNG]]: + self, node: ast.Dict, parent: nodes.NodeNG, newnode: nodes.Dict + ) -> Generator[tuple[nodes.NodeNG, nodes.NodeNG]]: for key, value in zip(node.keys, node.values): - rebuilt_key: NodeNG + rebuilt_key: nodes.NodeNG rebuilt_value = self.visit(value, newnode) if not key: # Extended unpacking @@ -930,7 +982,7 @@ def _visit_dict_items( rebuilt_key = self.visit(key, newnode) yield rebuilt_key, rebuilt_value - def visit_dict(self, node: ast.Dict, parent: NodeNG) -> nodes.Dict: + def visit_dict(self, node: ast.Dict, parent: nodes.NodeNG) -> nodes.Dict: """Visit a Dict node by returning a fresh instance of it.""" newnode = nodes.Dict( lineno=node.lineno, @@ -945,7 +997,9 @@ def visit_dict(self, node: ast.Dict, parent: NodeNG) -> nodes.Dict: newnode.postinit(items) return newnode - def visit_dictcomp(self, node: ast.DictComp, parent: NodeNG) -> nodes.DictComp: + def visit_dictcomp( + self, node: ast.DictComp, parent: nodes.NodeNG + ) -> nodes.DictComp: """Visit a DictComp node by returning a fresh instance of it.""" newnode = nodes.DictComp( lineno=node.lineno, @@ -961,7 +1015,7 @@ def visit_dictcomp(self, node: ast.DictComp, parent: NodeNG) -> nodes.DictComp: ) return newnode - def visit_expr(self, node: ast.Expr, parent: NodeNG) -> nodes.Expr: + def visit_expr(self, node: ast.Expr, parent: nodes.NodeNG) -> nodes.Expr: """Visit a Expr node by returning a fresh instance of it.""" newnode = nodes.Expr( lineno=node.lineno, @@ -974,7 +1028,7 @@ def visit_expr(self, node: ast.Expr, parent: NodeNG) -> nodes.Expr: return newnode def visit_excepthandler( - self, node: ast.ExceptHandler, parent: NodeNG + self, node: ast.ExceptHandler, parent: nodes.NodeNG ) -> nodes.ExceptHandler: """Visit an ExceptHandler node by returning a fresh instance of it.""" newnode = nodes.ExceptHandler( @@ -993,16 +1047,16 @@ def visit_excepthandler( @overload def _visit_for( - self, cls: type[nodes.For], node: ast.For, parent: NodeNG + self, cls: type[nodes.For], node: ast.For, parent: nodes.NodeNG ) -> nodes.For: ... @overload def _visit_for( - self, cls: type[nodes.AsyncFor], node: ast.AsyncFor, parent: NodeNG + self, cls: type[nodes.AsyncFor], node: ast.AsyncFor, parent: nodes.NodeNG ) -> nodes.AsyncFor: ... def _visit_for( - self, cls: type[_ForT], node: ast.For | ast.AsyncFor, parent: NodeNG + self, cls: type[_ForT], node: ast.For | ast.AsyncFor, parent: nodes.NodeNG ) -> _ForT: """Visit a For node by returning a fresh instance of it.""" newnode = cls( @@ -1022,11 +1076,11 @@ def _visit_for( ) return newnode - def visit_for(self, node: ast.For, parent: NodeNG) -> nodes.For: + def visit_for(self, node: ast.For, parent: nodes.NodeNG) -> nodes.For: return self._visit_for(nodes.For, node, parent) def visit_importfrom( - self, node: ast.ImportFrom, parent: NodeNG + self, node: ast.ImportFrom, parent: nodes.NodeNG ) -> nodes.ImportFrom: """Visit an ImportFrom node by returning a fresh instance of it.""" names = [(alias.name, alias.asname) for alias in node.names] @@ -1046,7 +1100,7 @@ def visit_importfrom( @overload def _visit_functiondef( - self, cls: type[nodes.FunctionDef], node: ast.FunctionDef, parent: NodeNG + self, cls: type[nodes.FunctionDef], node: ast.FunctionDef, parent: nodes.NodeNG ) -> nodes.FunctionDef: ... @overload @@ -1054,14 +1108,14 @@ def _visit_functiondef( self, cls: type[nodes.AsyncFunctionDef], node: ast.AsyncFunctionDef, - parent: NodeNG, + parent: nodes.NodeNG, ) -> nodes.AsyncFunctionDef: ... def _visit_functiondef( self, cls: type[_FunctionT], node: ast.FunctionDef | ast.AsyncFunctionDef, - parent: NodeNG, + parent: nodes.NodeNG, ) -> _FunctionT: """Visit an FunctionDef node to become astroid.""" self._global_names.append({}) @@ -1087,7 +1141,7 @@ def _visit_functiondef( parent=parent, ) decorators = self.visit_decorators(node, newnode) - returns: NodeNG | None + returns: nodes.NodeNG | None if node.returns: returns = self.visit(node.returns, newnode) else: @@ -1117,12 +1171,12 @@ def _visit_functiondef( return newnode def visit_functiondef( - self, node: ast.FunctionDef, parent: NodeNG + self, node: ast.FunctionDef, parent: nodes.NodeNG ) -> nodes.FunctionDef: return self._visit_functiondef(nodes.FunctionDef, node, parent) def visit_generatorexp( - self, node: ast.GeneratorExp, parent: NodeNG + self, node: ast.GeneratorExp, parent: nodes.NodeNG ) -> nodes.GeneratorExp: """Visit a GeneratorExp node by returning a fresh instance of it.""" newnode = nodes.GeneratorExp( @@ -1139,7 +1193,7 @@ def visit_generatorexp( return newnode def visit_attribute( - self, node: ast.Attribute, parent: NodeNG + self, node: ast.Attribute, parent: nodes.NodeNG ) -> nodes.Attribute | nodes.AssignAttr | nodes.DelAttr: """Visit an Attribute node by returning a fresh instance of it.""" context = self._get_context(node) @@ -1182,7 +1236,7 @@ def visit_attribute( newnode.postinit(self.visit(node.value, newnode)) return newnode - def visit_global(self, node: ast.Global, parent: NodeNG) -> nodes.Global: + def visit_global(self, node: ast.Global, parent: nodes.NodeNG) -> nodes.Global: """Visit a Global node to become astroid.""" newnode = nodes.Global( names=node.names, @@ -1197,7 +1251,7 @@ def visit_global(self, node: ast.Global, parent: NodeNG) -> nodes.Global: self._global_names[-1].setdefault(name, []).append(newnode) return newnode - def visit_if(self, node: ast.If, parent: NodeNG) -> nodes.If: + def visit_if(self, node: ast.If, parent: nodes.NodeNG) -> nodes.If: """Visit an If node by returning a fresh instance of it.""" newnode = nodes.If( lineno=node.lineno, @@ -1213,7 +1267,7 @@ def visit_if(self, node: ast.If, parent: NodeNG) -> nodes.If: ) return newnode - def visit_ifexp(self, node: ast.IfExp, parent: NodeNG) -> nodes.IfExp: + def visit_ifexp(self, node: ast.IfExp, parent: nodes.NodeNG) -> nodes.IfExp: """Visit a IfExp node by returning a fresh instance of it.""" newnode = nodes.IfExp( lineno=node.lineno, @@ -1229,7 +1283,7 @@ def visit_ifexp(self, node: ast.IfExp, parent: NodeNG) -> nodes.IfExp: ) return newnode - def visit_import(self, node: ast.Import, parent: NodeNG) -> nodes.Import: + def visit_import(self, node: ast.Import, parent: nodes.NodeNG) -> nodes.Import: """Visit a Import node by returning a fresh instance of it.""" names = [(alias.name, alias.asname) for alias in node.names] newnode = nodes.Import( @@ -1246,7 +1300,9 @@ def visit_import(self, node: ast.Import, parent: NodeNG) -> nodes.Import: parent.set_local(name.split(".")[0], newnode) return newnode - def visit_joinedstr(self, node: ast.JoinedStr, parent: NodeNG) -> nodes.JoinedStr: + def visit_joinedstr( + self, node: ast.JoinedStr, parent: nodes.NodeNG + ) -> nodes.JoinedStr: newnode = nodes.JoinedStr( lineno=node.lineno, col_offset=node.col_offset, @@ -1258,7 +1314,7 @@ def visit_joinedstr(self, node: ast.JoinedStr, parent: NodeNG) -> nodes.JoinedSt return newnode def visit_formattedvalue( - self, node: ast.FormattedValue, parent: NodeNG + self, node: ast.FormattedValue, parent: nodes.NodeNG ) -> nodes.FormattedValue: newnode = nodes.FormattedValue( lineno=node.lineno, @@ -1274,7 +1330,9 @@ def visit_formattedvalue( ) return newnode - def visit_namedexpr(self, node: ast.NamedExpr, parent: NodeNG) -> nodes.NamedExpr: + def visit_namedexpr( + self, node: ast.NamedExpr, parent: nodes.NodeNG + ) -> nodes.NamedExpr: newnode = nodes.NamedExpr( lineno=node.lineno, col_offset=node.col_offset, @@ -1287,7 +1345,7 @@ def visit_namedexpr(self, node: ast.NamedExpr, parent: NodeNG) -> nodes.NamedExp ) return newnode - def visit_keyword(self, node: ast.keyword, parent: NodeNG) -> nodes.Keyword: + def visit_keyword(self, node: ast.keyword, parent: nodes.NodeNG) -> nodes.Keyword: """Visit a Keyword node by returning a fresh instance of it.""" newnode = nodes.Keyword( arg=node.arg, @@ -1301,7 +1359,7 @@ def visit_keyword(self, node: ast.keyword, parent: NodeNG) -> nodes.Keyword: newnode.postinit(self.visit(node.value, newnode)) return newnode - def visit_lambda(self, node: ast.Lambda, parent: NodeNG) -> nodes.Lambda: + def visit_lambda(self, node: ast.Lambda, parent: nodes.NodeNG) -> nodes.Lambda: """Visit a Lambda node by returning a fresh instance of it.""" newnode = nodes.Lambda( lineno=node.lineno, @@ -1313,7 +1371,7 @@ def visit_lambda(self, node: ast.Lambda, parent: NodeNG) -> nodes.Lambda: newnode.postinit(self.visit(node.args, newnode), self.visit(node.body, newnode)) return newnode - def visit_list(self, node: ast.List, parent: NodeNG) -> nodes.List: + def visit_list(self, node: ast.List, parent: nodes.NodeNG) -> nodes.List: """Visit a List node by returning a fresh instance of it.""" context = self._get_context(node) newnode = nodes.List( @@ -1327,7 +1385,9 @@ def visit_list(self, node: ast.List, parent: NodeNG) -> nodes.List: newnode.postinit([self.visit(child, newnode) for child in node.elts]) return newnode - def visit_listcomp(self, node: ast.ListComp, parent: NodeNG) -> nodes.ListComp: + def visit_listcomp( + self, node: ast.ListComp, parent: nodes.NodeNG + ) -> nodes.ListComp: """Visit a ListComp node by returning a fresh instance of it.""" newnode = nodes.ListComp( lineno=node.lineno, @@ -1343,7 +1403,7 @@ def visit_listcomp(self, node: ast.ListComp, parent: NodeNG) -> nodes.ListComp: return newnode def visit_name( - self, node: ast.Name, parent: NodeNG + self, node: ast.Name, parent: nodes.NodeNG ) -> nodes.Name | nodes.AssignName | nodes.DelName: """Visit a Name node by returning a fresh instance of it.""" context = self._get_context(node) @@ -1381,7 +1441,9 @@ def visit_name( self._save_assignment(newnode) return newnode - def visit_nonlocal(self, node: ast.Nonlocal, parent: NodeNG) -> nodes.Nonlocal: + def visit_nonlocal( + self, node: ast.Nonlocal, parent: nodes.NodeNG + ) -> nodes.Nonlocal: """Visit a Nonlocal node and return a new instance of it.""" return nodes.Nonlocal( names=node.names, @@ -1392,7 +1454,7 @@ def visit_nonlocal(self, node: ast.Nonlocal, parent: NodeNG) -> nodes.Nonlocal: parent=parent, ) - def visit_constant(self, node: ast.Constant, parent: NodeNG) -> nodes.Const: + def visit_constant(self, node: ast.Constant, parent: nodes.NodeNG) -> nodes.Const: """Visit a Constant node by returning a fresh instance of Const.""" return nodes.Const( value=node.value, @@ -1404,7 +1466,9 @@ def visit_constant(self, node: ast.Constant, parent: NodeNG) -> nodes.Const: parent=parent, ) - def visit_paramspec(self, node: ast.ParamSpec, parent: NodeNG) -> nodes.ParamSpec: + def visit_paramspec( + self, node: ast.ParamSpec, parent: nodes.NodeNG + ) -> nodes.ParamSpec: """Visit a ParamSpec node by returning a fresh instance of it.""" newnode = nodes.ParamSpec( lineno=node.lineno, @@ -1418,7 +1482,7 @@ def visit_paramspec(self, node: ast.ParamSpec, parent: NodeNG) -> nodes.ParamSpe newnode.postinit(name=self.visit_assignname(node, newnode, node.name)) return newnode - def visit_pass(self, node: ast.Pass, parent: NodeNG) -> nodes.Pass: + def visit_pass(self, node: ast.Pass, parent: nodes.NodeNG) -> nodes.Pass: """Visit a Pass node by returning a fresh instance of it.""" return nodes.Pass( lineno=node.lineno, @@ -1428,7 +1492,7 @@ def visit_pass(self, node: ast.Pass, parent: NodeNG) -> nodes.Pass: parent=parent, ) - def visit_raise(self, node: ast.Raise, parent: NodeNG) -> nodes.Raise: + def visit_raise(self, node: ast.Raise, parent: nodes.NodeNG) -> nodes.Raise: """Visit a Raise node by returning a fresh instance of it.""" newnode = nodes.Raise( lineno=node.lineno, @@ -1444,7 +1508,7 @@ def visit_raise(self, node: ast.Raise, parent: NodeNG) -> nodes.Raise: ) return newnode - def visit_return(self, node: ast.Return, parent: NodeNG) -> nodes.Return: + def visit_return(self, node: ast.Return, parent: nodes.NodeNG) -> nodes.Return: """Visit a Return node by returning a fresh instance of it.""" newnode = nodes.Return( lineno=node.lineno, @@ -1456,7 +1520,7 @@ def visit_return(self, node: ast.Return, parent: NodeNG) -> nodes.Return: newnode.postinit(self.visit(node.value, newnode)) return newnode - def visit_set(self, node: ast.Set, parent: NodeNG) -> nodes.Set: + def visit_set(self, node: ast.Set, parent: nodes.NodeNG) -> nodes.Set: """Visit a Set node by returning a fresh instance of it.""" newnode = nodes.Set( lineno=node.lineno, @@ -1468,7 +1532,7 @@ def visit_set(self, node: ast.Set, parent: NodeNG) -> nodes.Set: newnode.postinit([self.visit(child, newnode) for child in node.elts]) return newnode - def visit_setcomp(self, node: ast.SetComp, parent: NodeNG) -> nodes.SetComp: + def visit_setcomp(self, node: ast.SetComp, parent: nodes.NodeNG) -> nodes.SetComp: """Visit a SetComp node by returning a fresh instance of it.""" newnode = nodes.SetComp( lineno=node.lineno, @@ -1500,7 +1564,9 @@ def visit_slice(self, node: ast.Slice, parent: nodes.Subscript) -> nodes.Slice: ) return newnode - def visit_subscript(self, node: ast.Subscript, parent: NodeNG) -> nodes.Subscript: + def visit_subscript( + self, node: ast.Subscript, parent: nodes.NodeNG + ) -> nodes.Subscript: """Visit a Subscript node by returning a fresh instance of it.""" context = self._get_context(node) newnode = nodes.Subscript( @@ -1516,7 +1582,7 @@ def visit_subscript(self, node: ast.Subscript, parent: NodeNG) -> nodes.Subscrip ) return newnode - def visit_starred(self, node: ast.Starred, parent: NodeNG) -> nodes.Starred: + def visit_starred(self, node: ast.Starred, parent: nodes.NodeNG) -> nodes.Starred: """Visit a Starred node and return a new instance of it.""" context = self._get_context(node) newnode = nodes.Starred( @@ -1530,7 +1596,7 @@ def visit_starred(self, node: ast.Starred, parent: NodeNG) -> nodes.Starred: newnode.postinit(self.visit(node.value, newnode)) return newnode - def visit_try(self, node: ast.Try, parent: NodeNG) -> nodes.Try: + def visit_try(self, node: ast.Try, parent: nodes.NodeNG) -> nodes.Try: """Visit a Try node by returning a fresh instance of it""" newnode = nodes.Try( lineno=node.lineno, @@ -1547,7 +1613,7 @@ def visit_try(self, node: ast.Try, parent: NodeNG) -> nodes.Try: ) return newnode - def visit_trystar(self, node: ast.TryStar, parent: NodeNG) -> nodes.TryStar: + def visit_trystar(self, node: ast.TryStar, parent: nodes.NodeNG) -> nodes.TryStar: newnode = nodes.TryStar( lineno=node.lineno, col_offset=node.col_offset, @@ -1563,7 +1629,7 @@ def visit_trystar(self, node: ast.TryStar, parent: NodeNG) -> nodes.TryStar: ) return newnode - def visit_tuple(self, node: ast.Tuple, parent: NodeNG) -> nodes.Tuple: + def visit_tuple(self, node: ast.Tuple, parent: nodes.NodeNG) -> nodes.Tuple: """Visit a Tuple node by returning a fresh instance of it.""" context = self._get_context(node) newnode = nodes.Tuple( @@ -1577,7 +1643,9 @@ def visit_tuple(self, node: ast.Tuple, parent: NodeNG) -> nodes.Tuple: newnode.postinit([self.visit(child, newnode) for child in node.elts]) return newnode - def visit_typealias(self, node: ast.TypeAlias, parent: NodeNG) -> nodes.TypeAlias: + def visit_typealias( + self, node: ast.TypeAlias, parent: nodes.NodeNG + ) -> nodes.TypeAlias: """Visit a TypeAlias node by returning a fresh instance of it.""" newnode = nodes.TypeAlias( lineno=node.lineno, @@ -1593,7 +1661,7 @@ def visit_typealias(self, node: ast.TypeAlias, parent: NodeNG) -> nodes.TypeAlia ) return newnode - def visit_typevar(self, node: ast.TypeVar, parent: NodeNG) -> nodes.TypeVar: + def visit_typevar(self, node: ast.TypeVar, parent: nodes.NodeNG) -> nodes.TypeVar: """Visit a TypeVar node by returning a fresh instance of it.""" newnode = nodes.TypeVar( lineno=node.lineno, @@ -1611,7 +1679,7 @@ def visit_typevar(self, node: ast.TypeVar, parent: NodeNG) -> nodes.TypeVar: return newnode def visit_typevartuple( - self, node: ast.TypeVarTuple, parent: NodeNG + self, node: ast.TypeVarTuple, parent: nodes.NodeNG ) -> nodes.TypeVarTuple: """Visit a TypeVarTuple node by returning a fresh instance of it.""" newnode = nodes.TypeVarTuple( @@ -1626,7 +1694,7 @@ def visit_typevartuple( newnode.postinit(name=self.visit_assignname(node, newnode, node.name)) return newnode - def visit_unaryop(self, node: ast.UnaryOp, parent: NodeNG) -> nodes.UnaryOp: + def visit_unaryop(self, node: ast.UnaryOp, parent: nodes.NodeNG) -> nodes.UnaryOp: """Visit a UnaryOp node by returning a fresh instance of it.""" newnode = nodes.UnaryOp( op=self._parser_module.unary_op_classes[node.op.__class__], @@ -1639,7 +1707,7 @@ def visit_unaryop(self, node: ast.UnaryOp, parent: NodeNG) -> nodes.UnaryOp: newnode.postinit(self.visit(node.operand, newnode)) return newnode - def visit_while(self, node: ast.While, parent: NodeNG) -> nodes.While: + def visit_while(self, node: ast.While, parent: nodes.NodeNG) -> nodes.While: """Visit a While node by returning a fresh instance of it.""" newnode = nodes.While( lineno=node.lineno, @@ -1657,19 +1725,19 @@ def visit_while(self, node: ast.While, parent: NodeNG) -> nodes.While: @overload def _visit_with( - self, cls: type[nodes.With], node: ast.With, parent: NodeNG + self, cls: type[nodes.With], node: ast.With, parent: nodes.NodeNG ) -> nodes.With: ... @overload def _visit_with( - self, cls: type[nodes.AsyncWith], node: ast.AsyncWith, parent: NodeNG + self, cls: type[nodes.AsyncWith], node: ast.AsyncWith, parent: nodes.NodeNG ) -> nodes.AsyncWith: ... def _visit_with( self, cls: type[_WithT], node: ast.With | ast.AsyncWith, - parent: NodeNG, + parent: nodes.NodeNG, ) -> _WithT: newnode = cls( lineno=node.lineno, @@ -1679,7 +1747,9 @@ def _visit_with( parent=parent, ) - def visit_child(child: ast.withitem) -> tuple[NodeNG, NodeNG | None]: + def visit_child( + child: ast.withitem, + ) -> tuple[nodes.NodeNG, nodes.NodeNG | None]: expr = self.visit(child.context_expr, newnode) var = self.visit(child.optional_vars, newnode) return expr, var @@ -1692,10 +1762,10 @@ def visit_child(child: ast.withitem) -> tuple[NodeNG, NodeNG | None]: ) return newnode - def visit_with(self, node: ast.With, parent: NodeNG) -> NodeNG: + def visit_with(self, node: ast.With, parent: nodes.NodeNG) -> nodes.NodeNG: return self._visit_with(nodes.With, node, parent) - def visit_yield(self, node: ast.Yield, parent: NodeNG) -> NodeNG: + def visit_yield(self, node: ast.Yield, parent: nodes.NodeNG) -> nodes.NodeNG: """Visit a Yield node by returning a fresh instance of it.""" newnode = nodes.Yield( lineno=node.lineno, @@ -1707,7 +1777,9 @@ def visit_yield(self, node: ast.Yield, parent: NodeNG) -> NodeNG: newnode.postinit(self.visit(node.value, newnode)) return newnode - def visit_yieldfrom(self, node: ast.YieldFrom, parent: NodeNG) -> NodeNG: + def visit_yieldfrom( + self, node: ast.YieldFrom, parent: nodes.NodeNG + ) -> nodes.NodeNG: newnode = nodes.YieldFrom( lineno=node.lineno, col_offset=node.col_offset, @@ -1720,7 +1792,7 @@ def visit_yieldfrom(self, node: ast.YieldFrom, parent: NodeNG) -> NodeNG: if sys.version_info >= (3, 10): - def visit_match(self, node: ast.Match, parent: NodeNG) -> nodes.Match: + def visit_match(self, node: ast.Match, parent: nodes.NodeNG) -> nodes.Match: newnode = nodes.Match( lineno=node.lineno, col_offset=node.col_offset, @@ -1735,7 +1807,7 @@ def visit_match(self, node: ast.Match, parent: NodeNG) -> nodes.Match: return newnode def visit_matchcase( - self, node: ast.match_case, parent: NodeNG + self, node: ast.match_case, parent: nodes.NodeNG ) -> nodes.MatchCase: newnode = nodes.MatchCase(parent=parent) newnode.postinit( @@ -1746,7 +1818,7 @@ def visit_matchcase( return newnode def visit_matchvalue( - self, node: ast.MatchValue, parent: NodeNG + self, node: ast.MatchValue, parent: nodes.NodeNG ) -> nodes.MatchValue: newnode = nodes.MatchValue( lineno=node.lineno, @@ -1759,7 +1831,7 @@ def visit_matchvalue( return newnode def visit_matchsingleton( - self, node: ast.MatchSingleton, parent: NodeNG + self, node: ast.MatchSingleton, parent: nodes.NodeNG ) -> nodes.MatchSingleton: return nodes.MatchSingleton( value=node.value, @@ -1771,7 +1843,7 @@ def visit_matchsingleton( ) def visit_matchsequence( - self, node: ast.MatchSequence, parent: NodeNG + self, node: ast.MatchSequence, parent: nodes.NodeNG ) -> nodes.MatchSequence: newnode = nodes.MatchSequence( lineno=node.lineno, @@ -1786,7 +1858,7 @@ def visit_matchsequence( return newnode def visit_matchmapping( - self, node: ast.MatchMapping, parent: NodeNG + self, node: ast.MatchMapping, parent: nodes.NodeNG ) -> nodes.MatchMapping: newnode = nodes.MatchMapping( lineno=node.lineno, @@ -1805,7 +1877,7 @@ def visit_matchmapping( return newnode def visit_matchclass( - self, node: ast.MatchClass, parent: NodeNG + self, node: ast.MatchClass, parent: nodes.NodeNG ) -> nodes.MatchClass: newnode = nodes.MatchClass( lineno=node.lineno, @@ -1825,7 +1897,7 @@ def visit_matchclass( return newnode def visit_matchstar( - self, node: ast.MatchStar, parent: NodeNG + self, node: ast.MatchStar, parent: nodes.NodeNG ) -> nodes.MatchStar: newnode = nodes.MatchStar( lineno=node.lineno, @@ -1839,7 +1911,9 @@ def visit_matchstar( newnode.postinit(name=self.visit_assignname(node, newnode, node.name)) return newnode - def visit_matchas(self, node: ast.MatchAs, parent: NodeNG) -> nodes.MatchAs: + def visit_matchas( + self, node: ast.MatchAs, parent: nodes.NodeNG + ) -> nodes.MatchAs: newnode = nodes.MatchAs( lineno=node.lineno, col_offset=node.col_offset, @@ -1855,7 +1929,9 @@ def visit_matchas(self, node: ast.MatchAs, parent: NodeNG) -> nodes.MatchAs: ) return newnode - def visit_matchor(self, node: ast.MatchOr, parent: NodeNG) -> nodes.MatchOr: + def visit_matchor( + self, node: ast.MatchOr, parent: nodes.NodeNG + ) -> nodes.MatchOr: newnode = nodes.MatchOr( lineno=node.lineno, col_offset=node.col_offset, diff --git a/tests/resources.py b/tests/resources.py index ce0bfb3df9..fb3ef1be9c 100644 --- a/tests/resources.py +++ b/tests/resources.py @@ -11,6 +11,7 @@ from pathlib import Path from astroid import builder +from astroid.manager import AstroidManager from astroid.nodes.scoped_nodes import Module DATA_DIR = Path("testdata") / "python3" @@ -22,7 +23,7 @@ def find(name: str) -> str: def build_file(path: str, modname: str | None = None) -> Module: - return builder.AstroidBuilder().file_build(find(path), modname) + return builder.AstroidBuilder(AstroidManager()).file_build(find(path), modname) class SysPathSetup: diff --git a/tests/test_builder.py b/tests/test_builder.py index 9de7f16ba7..9079d0c497 100644 --- a/tests/test_builder.py +++ b/tests/test_builder.py @@ -27,6 +27,7 @@ InferenceError, StatementMissing, ) +from astroid.manager import AstroidManager from astroid.nodes.scoped_nodes import Module from . import resources @@ -879,7 +880,7 @@ def test_module_build_dunder_file() -> None: """Test that module_build() can work with modules that have the *__file__* attribute. """ - module = builder.AstroidBuilder().module_build(collections) + module = builder.AstroidBuilder(AstroidManager()).module_build(collections) assert module.path[0] == collections.__file__ @@ -964,7 +965,7 @@ def test_build_from_live_module_without_source_file(self) -> None: with self.assertRaises(AttributeError): _ = self.imported_module.__file__ - my_builder = builder.AstroidBuilder() + my_builder = builder.AstroidBuilder(AstroidManager()) with unittest.mock.patch.object( self.imported_module.__loader__, "get_source", diff --git a/tests/test_inference.py b/tests/test_inference.py index 3a58a8b074..6b53d4f5dc 100644 --- a/tests/test_inference.py +++ b/tests/test_inference.py @@ -43,6 +43,7 @@ NoDefault, NotFoundError, ) +from astroid.manager import AstroidManager from astroid.objects import ExceptionInstance from . import resources @@ -59,7 +60,7 @@ def get_node_of_class(start_from: nodes.FunctionDef, klass: type) -> nodes.Attri return next(start_from.nodes_of_class(klass)) -builder = AstroidBuilder() +builder = AstroidBuilder(AstroidManager()) DATA_DIR = Path(__file__).parent / "testdata" / "python3" / "data" diff --git a/tests/test_nodes.py b/tests/test_nodes.py index 7f2133ed96..0c68ce7ae9 100644 --- a/tests/test_nodes.py +++ b/tests/test_nodes.py @@ -55,7 +55,7 @@ from . import resources -abuilder = builder.AstroidBuilder() +abuilder = builder.AstroidBuilder(astroid.MANAGER) class AsStringTest(resources.SysPathSetup, unittest.TestCase): diff --git a/tests/test_python3.py b/tests/test_python3.py index b46ce86e4d..d982e6f069 100644 --- a/tests/test_python3.py +++ b/tests/test_python3.py @@ -9,12 +9,13 @@ from astroid import exceptions, nodes from astroid.builder import AstroidBuilder, extract_node +from astroid.manager import AstroidManager class Python3TC(unittest.TestCase): @classmethod def setUpClass(cls): - cls.builder = AstroidBuilder() + cls.builder = AstroidBuilder(AstroidManager()) def test_starred_notation(self) -> None: astroid = self.builder.string_build("*a, b = [1, 2, 3]", "test", "test") diff --git a/tests/test_raw_building.py b/tests/test_raw_building.py index b5f3a62623..2d18e8a199 100644 --- a/tests/test_raw_building.py +++ b/tests/test_raw_building.py @@ -25,6 +25,7 @@ import tests.testdata.python3.data.fake_module_with_warnings as fm from astroid.builder import AstroidBuilder from astroid.const import IS_PYPY, PY312_PLUS +from astroid.manager import AstroidManager from astroid.raw_building import ( attach_dummy_node, build_class, @@ -93,7 +94,7 @@ def test_io_is__io(self): # what io.BufferedReader is. The code that handles this # is in astroid.raw_building.imported_member, which verifies # the true name of the module. - builder = AstroidBuilder() + builder = AstroidBuilder(AstroidManager()) module = builder.inspect_build(_io) buffered_reader = module.getattr("BufferedReader")[0] expected = "_io" if PY312_PLUS else "io" @@ -110,7 +111,7 @@ def test_build_function_deepinspect_deprecation(self) -> None: m.pd = fm # This should not raise an exception - AstroidBuilder().module_build(m, "test") + AstroidBuilder(AstroidManager()).module_build(m, "test") def test_module_object_with_broken_getattr(self) -> None: # Tests https://github.com/pylint-dev/astroid/issues/1958 @@ -118,7 +119,7 @@ def test_module_object_with_broken_getattr(self) -> None: # errors when using hasattr(). # This should not raise an exception - AstroidBuilder().inspect_build(fm_getattr, "test") + AstroidBuilder(AstroidManager()).inspect_build(fm_getattr, "test") @pytest.mark.skipif( @@ -151,7 +152,7 @@ def mocked_sys_modules_getitem(name: str) -> types.ModuleType | CustomGetattr: with mock.patch("astroid.raw_building.sys.modules") as sys_mock: sys_mock.__getitem__.side_effect = mocked_sys_modules_getitem - builder = AstroidBuilder() + builder = AstroidBuilder(AstroidManager()) builder.inspect_build(os) out, err = capsys.readouterr() diff --git a/tests/test_regrtest.py b/tests/test_regrtest.py index 2f6684124b..76a7ceae1e 100644 --- a/tests/test_regrtest.py +++ b/tests/test_regrtest.py @@ -14,6 +14,7 @@ from astroid.const import PY312_PLUS from astroid.context import InferenceContext from astroid.exceptions import InferenceError +from astroid.manager import AstroidManager from astroid.raw_building import build_module from astroid.util import Uninferable @@ -80,7 +81,7 @@ def test_package_sidepackage(self) -> None: self.assertEqual(subpackage.name, "absimp.sidepackage") def test_living_property(self) -> None: - builder = AstroidBuilder() + builder = AstroidBuilder(AstroidManager()) builder._done = {} builder._module = sys.modules[__name__] builder.object_build(build_module("module_name", ""), Whatever) @@ -90,7 +91,7 @@ def test_numpy_crash(self): """Test don't crash on numpy.""" # a crash occurred somewhere in the past, and an # InferenceError instead of a crash was better, but now we even infer! - builder = AstroidBuilder() + builder = AstroidBuilder(AstroidManager()) data = """ from numpy import multiply @@ -120,14 +121,14 @@ def test_numpy_distutils(self): def test_nameconstant(self) -> None: # used to fail for Python 3.4 - builder = AstroidBuilder() + builder = AstroidBuilder(AstroidManager()) astroid = builder.string_build("def test(x=True): pass") default = astroid.body[0].args.args[0] self.assertEqual(default.name, "x") self.assertEqual(next(default.infer()).value, True) def test_recursion_regression_issue25(self) -> None: - builder = AstroidBuilder() + builder = AstroidBuilder(AstroidManager()) data = """ import recursion as base @@ -148,7 +149,7 @@ def run(): klass.type # pylint: disable=pointless-statement # noqa: B018 def test_decorator_callchain_issue42(self) -> None: - builder = AstroidBuilder() + builder = AstroidBuilder(AstroidManager()) data = """ def test(): @@ -166,7 +167,7 @@ def crash(): self.assertEqual(astroid["crash"].type, "function") def test_filter_stmts_scoping(self) -> None: - builder = AstroidBuilder() + builder = AstroidBuilder(AstroidManager()) data = """ def test(): compiler = int() @@ -183,7 +184,7 @@ class B(compiler.__class__): self.assertEqual(base.name, "int") def test_filter_stmts_nested_if(self) -> None: - builder = AstroidBuilder() + builder = AstroidBuilder(AstroidManager()) data = """ def test(val): variable = None @@ -214,7 +215,7 @@ def test(val): assert result[2].lineno == 12 def test_ancestors_patching_class_recursion(self) -> None: - node = AstroidBuilder().string_build( + node = AstroidBuilder(AstroidManager()).string_build( textwrap.dedent( """ import string diff --git a/tests/test_scoped_nodes.py b/tests/test_scoped_nodes.py index 5e5bb581d4..f3244c6d5f 100644 --- a/tests/test_scoped_nodes.py +++ b/tests/test_scoped_nodes.py @@ -42,6 +42,7 @@ ResolveError, TooManyLevelsError, ) +from astroid.manager import AstroidManager from astroid.nodes.scoped_nodes.scoped_nodes import _is_metaclass from . import resources @@ -268,21 +269,21 @@ def test_file_stream_in_memory(self) -> None: def test_file_stream_physical(self) -> None: path = resources.find("data/all.py") - astroid = builder.AstroidBuilder().file_build(path, "all") + astroid = builder.AstroidBuilder(AstroidManager()).file_build(path, "all") with open(path, "rb") as file_io: with astroid.stream() as stream: self.assertEqual(stream.read(), file_io.read()) def test_file_stream_api(self) -> None: path = resources.find("data/all.py") - file_build = builder.AstroidBuilder().file_build(path, "all") + file_build = builder.AstroidBuilder(AstroidManager()).file_build(path, "all") with self.assertRaises(AttributeError): # pylint: disable=pointless-statement, no-member file_build.file_stream # noqa: B018 def test_stream_api(self) -> None: path = resources.find("data/all.py") - astroid = builder.AstroidBuilder().file_build(path, "all") + astroid = builder.AstroidBuilder(AstroidManager()).file_build(path, "all") stream = astroid.stream() self.assertTrue(hasattr(stream, "close")) with stream: @@ -2153,7 +2154,7 @@ class ParentGetattr(Getattr): # Test that objects analyzed through the live introspection # aren't considered to have dynamic getattr implemented. - astroid_builder = builder.AstroidBuilder() + astroid_builder = builder.AstroidBuilder(AstroidManager()) module = astroid_builder.module_build(difflib) self.assertFalse(module["SequenceMatcher"].has_dynamic_getattr()) diff --git a/tests/test_transforms.py b/tests/test_transforms.py index f4875ca5f2..87b26a5861 100644 --- a/tests/test_transforms.py +++ b/tests/test_transforms.py @@ -219,7 +219,7 @@ def predicate(node: FunctionDef) -> bool: return node.root().name == "time" with add_transform(manager, nodes.FunctionDef, transform_function, predicate): - builder_instance = builder.AstroidBuilder() + builder_instance = builder.AstroidBuilder(AstroidManager()) module = builder_instance.module_build(time) asctime = module["asctime"] @@ -233,7 +233,9 @@ def transform_function(node): manager = MANAGER with add_transform(manager, nodes.FunctionDef, transform_function): - astroid_builder = builder.AstroidBuilder(apply_transforms=False) + astroid_builder = builder.AstroidBuilder( + AstroidManager(), apply_transforms=False + ) module = astroid_builder.string_build("""def test(): pass""") # The transform wasn't applied. From ff11fa742bc44431dbbf2b4f9443b72acbd14bf3 Mon Sep 17 00:00:00 2001 From: Jacob Walls Date: Sun, 2 Feb 2025 15:59:58 -0500 Subject: [PATCH 2/3] Add annotation Co-authored-by: Pierre Sassoulas --- astroid/raw_building.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/astroid/raw_building.py b/astroid/raw_building.py index 2d872b943b..79c859a419 100644 --- a/astroid/raw_building.py +++ b/astroid/raw_building.py @@ -421,7 +421,7 @@ class InspectBuilder: bootstrapped: bool = False - def __init__(self, manager_instance) -> None: + def __init__(self, manager_instance: AstroidManager) -> None: self._manager = manager_instance self._done: dict[types.ModuleType | type, nodes.Module | nodes.ClassDef] = {} self._module: types.ModuleType From c452b0ff8a9609820b8afacd1a27a63718c485da Mon Sep 17 00:00:00 2001 From: Jacob Walls Date: Sun, 2 Feb 2025 21:30:20 -0500 Subject: [PATCH 3/3] fixup! Add annotation --- astroid/raw_building.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/astroid/raw_building.py b/astroid/raw_building.py index 79c859a419..3882ebbd2b 100644 --- a/astroid/raw_building.py +++ b/astroid/raw_building.py @@ -18,12 +18,15 @@ import warnings from collections.abc import Iterable from contextlib import redirect_stderr, redirect_stdout -from typing import Any, Union +from typing import TYPE_CHECKING, Any, Union from astroid import bases, nodes from astroid.const import _EMPTY_OBJECT_MARKER, IS_PYPY from astroid.nodes import node_classes +if TYPE_CHECKING: + from astroid.manager import AstroidManager + logger = logging.getLogger(__name__)