diff --git a/astroid/brain/brain_attrs.py b/astroid/brain/brain_attrs.py index 727fb90c0..b619bb3f4 100644 --- a/astroid/brain/brain_attrs.py +++ b/astroid/brain/brain_attrs.py @@ -8,10 +8,9 @@ Without this hook pylint reports unsupported-assignment-operation for attrs classes """ +from astroid import nodes from astroid.brain.helpers import is_class_var from astroid.manager import AstroidManager -from astroid.nodes.node_classes import AnnAssign, Assign, AssignName, Call, Unknown -from astroid.nodes.scoped_nodes import ClassDef from astroid.util import safe_infer ATTRIB_NAMES = frozenset( @@ -51,7 +50,7 @@ def is_decorated_with_attrs(node, decorator_names=ATTRS_NAMES) -> bool: if not node.decorators: return False for decorator_attribute in node.decorators.nodes: - if isinstance(decorator_attribute, Call): # decorator with arguments + if isinstance(decorator_attribute, nodes.Call): # decorator with arguments decorator_attribute = decorator_attribute.func if decorator_attribute.as_string() in decorator_names: return True @@ -62,26 +61,26 @@ def is_decorated_with_attrs(node, decorator_names=ATTRS_NAMES) -> bool: return False -def attr_attributes_transform(node: ClassDef) -> None: +def attr_attributes_transform(node: nodes.ClassDef) -> None: """Given that the ClassNode has an attr decorator, rewrite class attributes as instance attributes """ # Astroid can't infer this attribute properly # Prevents https://github.com/pylint-dev/pylint/issues/1884 - node.locals["__attrs_attrs__"] = [Unknown(parent=node)] + node.locals["__attrs_attrs__"] = [nodes.Unknown(parent=node)] use_bare_annotations = is_decorated_with_attrs(node, NEW_ATTRS_NAMES) for cdef_body_node in node.body: - if not isinstance(cdef_body_node, (Assign, AnnAssign)): + if not isinstance(cdef_body_node, (nodes.Assign, nodes.AnnAssign)): continue - if isinstance(cdef_body_node.value, Call): + if isinstance(cdef_body_node.value, nodes.Call): if cdef_body_node.value.func.as_string() not in ATTRIB_NAMES: continue elif not use_bare_annotations: continue # Skip attributes that are explicitly annotated as class variables - if isinstance(cdef_body_node, AnnAssign) and is_class_var( + if isinstance(cdef_body_node, nodes.AnnAssign) and is_class_var( cdef_body_node.annotation ): continue @@ -92,12 +91,12 @@ def attr_attributes_transform(node: ClassDef) -> None: else [cdef_body_node.target] ) for target in targets: - rhs_node = Unknown( + rhs_node = nodes.Unknown( lineno=cdef_body_node.lineno, col_offset=cdef_body_node.col_offset, parent=cdef_body_node, ) - if isinstance(target, AssignName): + if isinstance(target, nodes.AssignName): # Could be a subscript if the code analysed is # i = Optional[str] = "" # See https://github.com/pylint-dev/pylint/issues/4439 @@ -107,5 +106,5 @@ def attr_attributes_transform(node: ClassDef) -> None: def register(manager: AstroidManager) -> None: manager.register_transform( - ClassDef, attr_attributes_transform, is_decorated_with_attrs + nodes.ClassDef, attr_attributes_transform, is_decorated_with_attrs ) diff --git a/astroid/brain/brain_functools.py b/astroid/brain/brain_functools.py index c11b856ec..1cb844216 100644 --- a/astroid/brain/brain_functools.py +++ b/astroid/brain/brain_functools.py @@ -17,8 +17,6 @@ from astroid.inference_tip import inference_tip from astroid.interpreter import objectmodel from astroid.manager import AstroidManager -from astroid.nodes.node_classes import AssignName, Attribute, Call, Name -from astroid.nodes.scoped_nodes import FunctionDef from astroid.typing import InferenceResult, SuccessfulInferenceResult from astroid.util import UninferableBase, safe_infer @@ -92,7 +90,7 @@ def _functools_partial_inference( raise UseInferenceDefault from exc if isinstance(inferred_wrapped_function, UninferableBase): raise UseInferenceDefault("Cannot infer the wrapped function") - if not isinstance(inferred_wrapped_function, FunctionDef): + if not isinstance(inferred_wrapped_function, nodes.FunctionDef): raise UseInferenceDefault("The wrapped function is not a function") # Determine if the passed keywords into the callsite are supported @@ -106,7 +104,9 @@ def _functools_partial_inference( inferred_wrapped_function.args.kwonlyargs or (), ) parameter_names = { - param.name for param in function_parameters if isinstance(param, AssignName) + param.name + for param in function_parameters + if isinstance(param, nodes.AssignName) } if set(call.keyword_arguments) - parameter_names: raise UseInferenceDefault("wrapped function received unknown parameters") @@ -135,23 +135,25 @@ def _looks_like_lru_cache(node) -> bool: if not node.decorators: return False for decorator in node.decorators.nodes: - if not isinstance(decorator, (Attribute, Call)): + if not isinstance(decorator, (nodes.Attribute, nodes.Call)): continue if _looks_like_functools_member(decorator, "lru_cache"): return True return False -def _looks_like_functools_member(node: Attribute | Call, member: str) -> bool: +def _looks_like_functools_member( + node: nodes.Attribute | nodes.Call, member: str +) -> bool: """Check if the given Call node is the wanted member of functools.""" - if isinstance(node, Attribute): + if isinstance(node, nodes.Attribute): return node.attrname == member - if isinstance(node.func, Name): + if isinstance(node.func, nodes.Name): return node.func.name == member - if isinstance(node.func, Attribute): + if isinstance(node.func, nodes.Attribute): return ( node.func.attrname == member - and isinstance(node.func.expr, Name) + and isinstance(node.func.expr, nodes.Name) and node.func.expr.name == "functools" ) return False @@ -161,10 +163,12 @@ def _looks_like_functools_member(node: Attribute | Call, member: str) -> bool: def register(manager: AstroidManager) -> None: - manager.register_transform(FunctionDef, _transform_lru_cache, _looks_like_lru_cache) + manager.register_transform( + nodes.FunctionDef, _transform_lru_cache, _looks_like_lru_cache + ) manager.register_transform( - Call, + nodes.Call, inference_tip(_functools_partial_inference), _looks_like_partial, ) diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py index 7163e8607..ff5b7154d 100644 --- a/astroid/brain/brain_namedtuple_enum.py +++ b/astroid/brain/brain_namedtuple_enum.py @@ -12,7 +12,6 @@ from textwrap import dedent from typing import Final -import astroid from astroid import arguments, bases, nodes, util from astroid.builder import AstroidBuilder, _extract_single_node, extract_node from astroid.context import InferenceContext @@ -651,7 +650,7 @@ def _get_namedtuple_fields(node: nodes.Call) -> str: return field_names -def _is_enum_subclass(cls: astroid.ClassDef) -> bool: +def _is_enum_subclass(cls: nodes.ClassDef) -> bool: """Return whether cls is a subclass of an Enum.""" return cls.is_subtype_of("enum.Enum") diff --git a/astroid/brain/brain_numpy_core_function_base.py b/astroid/brain/brain_numpy_core_function_base.py index 2bfe97080..b66ba5f56 100644 --- a/astroid/brain/brain_numpy_core_function_base.py +++ b/astroid/brain/brain_numpy_core_function_base.py @@ -6,13 +6,13 @@ import functools +from astroid import nodes from astroid.brain.brain_numpy_utils import ( attribute_name_looks_like_numpy_member, infer_numpy_attribute, ) from astroid.inference_tip import inference_tip from astroid.manager import AstroidManager -from astroid.nodes.node_classes import Attribute METHODS_TO_BE_INFERRED = { "linspace": """def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0): @@ -26,7 +26,7 @@ def register(manager: AstroidManager) -> None: manager.register_transform( - Attribute, + nodes.Attribute, inference_tip(functools.partial(infer_numpy_attribute, METHODS_TO_BE_INFERRED)), functools.partial( attribute_name_looks_like_numpy_member, diff --git a/astroid/brain/brain_numpy_core_multiarray.py b/astroid/brain/brain_numpy_core_multiarray.py index 95ef0a340..19850d3cd 100644 --- a/astroid/brain/brain_numpy_core_multiarray.py +++ b/astroid/brain/brain_numpy_core_multiarray.py @@ -17,7 +17,6 @@ from astroid.builder import parse from astroid.inference_tip import inference_tip from astroid.manager import AstroidManager -from astroid.nodes.node_classes import Attribute, Name def numpy_core_multiarray_transform() -> nodes.Module: @@ -96,12 +95,12 @@ def register(manager: AstroidManager) -> None: method_names = frozenset(METHODS_TO_BE_INFERRED.keys()) manager.register_transform( - Attribute, + nodes.Attribute, inference_tip(functools.partial(infer_numpy_attribute, METHODS_TO_BE_INFERRED)), functools.partial(attribute_name_looks_like_numpy_member, method_names), ) manager.register_transform( - Name, + nodes.Name, inference_tip(functools.partial(infer_numpy_name, METHODS_TO_BE_INFERRED)), functools.partial(member_name_looks_like_numpy_member, method_names), ) diff --git a/astroid/brain/brain_numpy_core_numeric.py b/astroid/brain/brain_numpy_core_numeric.py index 72d4cc9c1..ee08e0213 100644 --- a/astroid/brain/brain_numpy_core_numeric.py +++ b/astroid/brain/brain_numpy_core_numeric.py @@ -15,7 +15,6 @@ from astroid.builder import parse from astroid.inference_tip import inference_tip from astroid.manager import AstroidManager -from astroid.nodes.node_classes import Attribute def numpy_core_numeric_transform() -> nodes.Module: @@ -42,7 +41,7 @@ def register(manager: AstroidManager) -> None: ) manager.register_transform( - Attribute, + nodes.Attribute, inference_tip(functools.partial(infer_numpy_attribute, METHODS_TO_BE_INFERRED)), functools.partial( attribute_name_looks_like_numpy_member, diff --git a/astroid/brain/brain_numpy_ndarray.py b/astroid/brain/brain_numpy_ndarray.py index 38db4e62f..c98adb156 100644 --- a/astroid/brain/brain_numpy_ndarray.py +++ b/astroid/brain/brain_numpy_ndarray.py @@ -5,12 +5,12 @@ """Astroid hooks for numpy ndarray class.""" from __future__ import annotations +from astroid import nodes from astroid.brain.brain_numpy_utils import numpy_supports_type_hints from astroid.builder import extract_node from astroid.context import InferenceContext from astroid.inference_tip import inference_tip from astroid.manager import AstroidManager -from astroid.nodes.node_classes import Attribute def infer_numpy_ndarray(node, context: InferenceContext | None = None): @@ -151,13 +151,13 @@ def __class_getitem__(cls, value): return node.infer(context=context) -def _looks_like_numpy_ndarray(node: Attribute) -> bool: +def _looks_like_numpy_ndarray(node: nodes.Attribute) -> bool: return node.attrname == "ndarray" def register(manager: AstroidManager) -> None: manager.register_transform( - Attribute, + nodes.Attribute, inference_tip(infer_numpy_ndarray), _looks_like_numpy_ndarray, ) diff --git a/astroid/brain/brain_numpy_utils.py b/astroid/brain/brain_numpy_utils.py index a3d4ed532..1a8f66573 100644 --- a/astroid/brain/brain_numpy_utils.py +++ b/astroid/brain/brain_numpy_utils.py @@ -6,9 +6,9 @@ from __future__ import annotations +from astroid import nodes from astroid.builder import extract_node from astroid.context import InferenceContext -from astroid.nodes.node_classes import Attribute, Import, Name # Class subscript is available in numpy starting with version 1.20.0 NUMPY_VERSION_TYPE_HINTS_SUPPORT = ("1", "20", "0") @@ -35,20 +35,22 @@ def _get_numpy_version() -> tuple[str, str, str]: def infer_numpy_name( - sources: dict[str, str], node: Name, context: InferenceContext | None = None + sources: dict[str, str], node: nodes.Name, context: InferenceContext | None = None ): extracted_node = extract_node(sources[node.name]) return extracted_node.infer(context=context) def infer_numpy_attribute( - sources: dict[str, str], node: Attribute, context: InferenceContext | None = None + sources: dict[str, str], + node: nodes.Attribute, + context: InferenceContext | None = None, ): extracted_node = extract_node(sources[node.attrname]) return extracted_node.infer(context=context) -def _is_a_numpy_module(node: Name) -> bool: +def _is_a_numpy_module(node: nodes.Name) -> bool: """ Returns True if the node is a representation of a numpy module. @@ -62,7 +64,7 @@ def _is_a_numpy_module(node: Name) -> bool: """ module_nickname = node.name potential_import_target = [ - x for x in node.lookup(module_nickname)[1] if isinstance(x, Import) + x for x in node.lookup(module_nickname)[1] if isinstance(x, nodes.Import) ] return any( ("numpy", module_nickname) in target.names or ("numpy", None) in target.names @@ -71,7 +73,7 @@ def _is_a_numpy_module(node: Name) -> bool: def member_name_looks_like_numpy_member( - member_names: frozenset[str], node: Name + member_names: frozenset[str], node: nodes.Name ) -> bool: """ Returns True if the Name node's name matches a member name from numpy @@ -80,13 +82,13 @@ def member_name_looks_like_numpy_member( def attribute_name_looks_like_numpy_member( - member_names: frozenset[str], node: Attribute + member_names: frozenset[str], node: nodes.Attribute ) -> bool: """ Returns True if the Attribute node's name matches a member name from numpy """ return ( node.attrname in member_names - and isinstance(node.expr, Name) + and isinstance(node.expr, nodes.Name) and _is_a_numpy_module(node.expr) ) diff --git a/astroid/brain/brain_random.py b/astroid/brain/brain_random.py index 48cc12146..84b4f4eb0 100644 --- a/astroid/brain/brain_random.py +++ b/astroid/brain/brain_random.py @@ -6,27 +6,18 @@ import random +from astroid import nodes from astroid.context import InferenceContext from astroid.exceptions import UseInferenceDefault from astroid.inference_tip import inference_tip from astroid.manager import AstroidManager -from astroid.nodes.node_classes import ( - Attribute, - Call, - Const, - EvaluatedObject, - List, - Name, - Set, - Tuple, -) from astroid.util import safe_infer -ACCEPTED_ITERABLES_FOR_SAMPLE = (List, Set, Tuple) +ACCEPTED_ITERABLES_FOR_SAMPLE = (nodes.List, nodes.Set, nodes.Tuple) def _clone_node_with_lineno(node, parent, lineno): - if isinstance(node, EvaluatedObject): + if isinstance(node, nodes.EvaluatedObject): node = node.original cls = node.__class__ other_fields = node._other_fields @@ -52,7 +43,7 @@ def infer_random_sample(node, context: InferenceContext | None = None): raise UseInferenceDefault inferred_length = safe_infer(node.args[1], context=context) - if not isinstance(inferred_length, Const): + if not isinstance(inferred_length, nodes.Const): raise UseInferenceDefault if not isinstance(inferred_length.value, int): raise UseInferenceDefault @@ -73,7 +64,7 @@ def infer_random_sample(node, context: InferenceContext | None = None): except ValueError as exc: raise UseInferenceDefault from exc - new_node = List( + new_node = nodes.List( lineno=node.lineno, col_offset=node.col_offset, parent=node.scope(), @@ -90,14 +81,14 @@ def infer_random_sample(node, context: InferenceContext | None = None): def _looks_like_random_sample(node) -> bool: func = node.func - if isinstance(func, Attribute): + if isinstance(func, nodes.Attribute): return func.attrname == "sample" - if isinstance(func, Name): + if isinstance(func, nodes.Name): return func.name == "sample" return False def register(manager: AstroidManager) -> None: manager.register_transform( - Call, inference_tip(infer_random_sample), _looks_like_random_sample + nodes.Call, inference_tip(infer_random_sample), _looks_like_random_sample ) diff --git a/astroid/brain/brain_type.py b/astroid/brain/brain_type.py index 2fb06be53..c0cad6e65 100644 --- a/astroid/brain/brain_type.py +++ b/astroid/brain/brain_type.py @@ -35,7 +35,7 @@ def _looks_like_type_subscript(node: nodes.Name) -> bool: Try to figure out if a Name node is used inside a type related subscript. :param node: node to check - :type node: astroid.nodes.node_classes.NodeNG + :type node: astroid.nodes.NodeNG :return: whether the node is a Name node inside a type related subscript """ if isinstance(node.parent, nodes.Subscript): @@ -48,7 +48,7 @@ def infer_type_sub(node, context: InferenceContext | None = None): Infer a type[...] subscript. :param node: node to infer - :type node: astroid.nodes.node_classes.NodeNG + :type node: astroid.nodes.NodeNG :return: the inferred node :rtype: nodes.NodeNG """ diff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py index 2cea7dcaa..e1679ae72 100644 --- a/astroid/brain/brain_typing.py +++ b/astroid/brain/brain_typing.py @@ -12,7 +12,7 @@ from functools import partial from typing import Final -from astroid import context +from astroid import context, nodes from astroid.brain.helpers import register_module_extender from astroid.builder import AstroidBuilder, _extract_single_node, extract_node from astroid.const import PY312_PLUS, PY313_PLUS, PY314_PLUS @@ -24,18 +24,6 @@ ) from astroid.inference_tip import inference_tip from astroid.manager import AstroidManager -from astroid.nodes.node_classes import ( - Assign, - AssignName, - Attribute, - Call, - Const, - JoinedStr, - Name, - NodeNG, - Subscript, -) -from astroid.nodes.scoped_nodes import ClassDef, FunctionDef TYPING_TYPEVARS = {"TypeVar", "NewType"} TYPING_TYPEVARS_QUALIFIED: Final = { @@ -112,16 +100,16 @@ def __class_getitem__(cls, item): def looks_like_typing_typevar_or_newtype(node) -> bool: func = node.func - if isinstance(func, Attribute): + if isinstance(func, nodes.Attribute): return func.attrname in TYPING_TYPEVARS - if isinstance(func, Name): + if isinstance(func, nodes.Name): return func.name in TYPING_TYPEVARS return False def infer_typing_typevar_or_newtype( - node: Call, context_itton: context.InferenceContext | None = None -) -> Iterator[ClassDef]: + node: nodes.Call, context_itton: context.InferenceContext | None = None +) -> Iterator[nodes.ClassDef]: """Infer a typing.TypeVar(...) or typing.NewType(...) call.""" try: func = next(node.func.infer(context=context_itton)) @@ -133,7 +121,7 @@ def infer_typing_typevar_or_newtype( if not node.args: raise UseInferenceDefault # Cannot infer from a dynamic class name (f-string) - if isinstance(node.args[0], JoinedStr): + if isinstance(node.args[0], nodes.JoinedStr): raise UseInferenceDefault typename = node.args[0].as_string().strip("'") @@ -146,18 +134,18 @@ def infer_typing_typevar_or_newtype( def _looks_like_typing_subscript(node) -> bool: """Try to figure out if a Subscript node *might* be a typing-related subscript.""" - if isinstance(node, Name): + if isinstance(node, nodes.Name): return node.name in TYPING_MEMBERS - if isinstance(node, Attribute): + if isinstance(node, nodes.Attribute): return node.attrname in TYPING_MEMBERS - if isinstance(node, Subscript): + if isinstance(node, nodes.Subscript): return _looks_like_typing_subscript(node.value) return False def infer_typing_attr( - node: Subscript, ctx: context.InferenceContext | None = None -) -> Iterator[ClassDef]: + node: nodes.Subscript, ctx: context.InferenceContext | None = None +) -> Iterator[nodes.ClassDef]: """Infer a typing.X[...] subscript.""" try: value = next(node.value.infer()) # type: ignore[union-attr] # value shouldn't be None for Subscript. @@ -170,14 +158,14 @@ def infer_typing_attr( if ( PY313_PLUS - and isinstance(value, FunctionDef) + and isinstance(value, nodes.FunctionDef) and value.qname() == "typing.Annotated" ): # typing.Annotated is a FunctionDef on 3.13+ node._explicit_inference = lambda node, context: iter([value]) return iter([value]) - if isinstance(value, ClassDef) and value.qname() in { + if isinstance(value, nodes.ClassDef) and value.qname() in { "typing.Generic", "typing.Annotated", "typing_extensions.Annotated", @@ -188,7 +176,7 @@ def infer_typing_attr( func_to_add = _extract_single_node(CLASS_GETITEM_TEMPLATE) value.locals["__class_getitem__"] = [func_to_add] if ( - isinstance(node.parent, ClassDef) + isinstance(node.parent, nodes.ClassDef) and node in node.parent.bases and getattr(node.parent, "__cache", None) ): @@ -205,14 +193,14 @@ def infer_typing_attr( return node.infer(context=ctx) -def _looks_like_generic_class_pep695(node: ClassDef) -> bool: +def _looks_like_generic_class_pep695(node: nodes.ClassDef) -> bool: """Check if class is using type parameter. Python 3.12+.""" return len(node.type_params) > 0 def infer_typing_generic_class_pep695( - node: ClassDef, ctx: context.InferenceContext | None = None -) -> Iterator[ClassDef]: + node: nodes.ClassDef, ctx: context.InferenceContext | None = None +) -> Iterator[nodes.ClassDef]: """Add __class_getitem__ for generic classes. Python 3.12+.""" func_to_add = _extract_single_node(CLASS_GETITEM_TEMPLATE) node.locals["__class_getitem__"] = [func_to_add] @@ -220,17 +208,17 @@ def infer_typing_generic_class_pep695( def _looks_like_typedDict( # pylint: disable=invalid-name - node: FunctionDef | ClassDef, + node: nodes.FunctionDef | nodes.ClassDef, ) -> bool: """Check if node is TypedDict FunctionDef.""" return node.qname() in TYPING_TYPEDDICT_QUALIFIED def infer_typedDict( # pylint: disable=invalid-name - node: FunctionDef, ctx: context.InferenceContext | None = None -) -> Iterator[ClassDef]: + node: nodes.FunctionDef, ctx: context.InferenceContext | None = None +) -> Iterator[nodes.ClassDef]: """Replace TypedDict FunctionDef with ClassDef.""" - class_def = ClassDef( + class_def = nodes.ClassDef( name="TypedDict", lineno=node.lineno, col_offset=node.col_offset, @@ -244,7 +232,7 @@ def infer_typedDict( # pylint: disable=invalid-name return iter([class_def]) -def _looks_like_typing_alias(node: Call) -> bool: +def _looks_like_typing_alias(node: nodes.Call) -> bool: """ Returns True if the node corresponds to a call to _alias function. @@ -255,18 +243,18 @@ def _looks_like_typing_alias(node: Call) -> bool: :param node: call node """ return ( - isinstance(node.func, Name) + isinstance(node.func, nodes.Name) # TODO: remove _DeprecatedGenericAlias when Py3.14 min and node.func.name in {"_alias", "_DeprecatedGenericAlias"} and len(node.args) == 2 and ( # _alias function works also for builtins object such as list and dict - isinstance(node.args[0], (Attribute, Name)) + isinstance(node.args[0], (nodes.Attribute, nodes.Name)) ) ) -def _forbid_class_getitem_access(node: ClassDef) -> None: +def _forbid_class_getitem_access(node: nodes.ClassDef) -> None: """Disable the access to __class_getitem__ method for the node in parameters.""" def full_raiser(origin_func, attr, *args, **kwargs): @@ -291,8 +279,8 @@ def full_raiser(origin_func, attr, *args, **kwargs): def infer_typing_alias( - node: Call, ctx: context.InferenceContext | None = None -) -> Iterator[ClassDef]: + node: nodes.Call, ctx: context.InferenceContext | None = None +) -> Iterator[nodes.ClassDef]: """ Infers the call to _alias function Insert ClassDef, with same name as aliased class, @@ -304,9 +292,9 @@ def infer_typing_alias( # TODO: evaluate if still necessary when Py3.12 is minimum """ if ( - not isinstance(node.parent, Assign) + not isinstance(node.parent, nodes.Assign) or not len(node.parent.targets) == 1 - or not isinstance(node.parent.targets[0], AssignName) + or not isinstance(node.parent.targets[0], nodes.AssignName) ): raise UseInferenceDefault try: @@ -316,7 +304,7 @@ def infer_typing_alias( assign_name = node.parent.targets[0] - class_def = ClassDef( + class_def = nodes.ClassDef( name=assign_name.name, lineno=assign_name.lineno, col_offset=assign_name.col_offset, @@ -324,13 +312,13 @@ def infer_typing_alias( end_lineno=assign_name.end_lineno, end_col_offset=assign_name.end_col_offset, ) - if isinstance(res, ClassDef): + if isinstance(res, nodes.ClassDef): # Only add `res` as base if it's a `ClassDef` # This isn't the case for `typing.Pattern` and `typing.Match` class_def.postinit(bases=[res], body=[], decorators=None) maybe_type_var = node.args[1] - if isinstance(maybe_type_var, Const) and maybe_type_var.value > 0: + if isinstance(maybe_type_var, nodes.Const) and maybe_type_var.value > 0: # If typing alias is subscriptable, add `__class_getitem__` to ClassDef func_to_add = _extract_single_node(CLASS_GETITEM_TEMPLATE) class_def.locals["__class_getitem__"] = [func_to_add] @@ -345,7 +333,7 @@ def infer_typing_alias( return iter([class_def]) -def _looks_like_special_alias(node: Call) -> bool: +def _looks_like_special_alias(node: nodes.Call) -> bool: """Return True if call is for Tuple or Callable alias. In PY37 and PY38 the call is to '_VariadicGenericAlias' with 'tuple' as @@ -357,28 +345,28 @@ def _looks_like_special_alias(node: Call) -> bool: PY37: Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True) PY39: Callable = _CallableType(collections.abc.Callable, 2) """ - return isinstance(node.func, Name) and ( + return isinstance(node.func, nodes.Name) and ( ( node.func.name == "_TupleType" - and isinstance(node.args[0], Name) + and isinstance(node.args[0], nodes.Name) and node.args[0].name == "tuple" ) or ( node.func.name == "_CallableType" - and isinstance(node.args[0], Attribute) + and isinstance(node.args[0], nodes.Attribute) and node.args[0].as_string() == "collections.abc.Callable" ) ) def infer_special_alias( - node: Call, ctx: context.InferenceContext | None = None -) -> Iterator[ClassDef]: + node: nodes.Call, ctx: context.InferenceContext | None = None +) -> Iterator[nodes.ClassDef]: """Infer call to tuple alias as new subscriptable class typing.Tuple.""" if not ( - isinstance(node.parent, Assign) + isinstance(node.parent, nodes.Assign) and len(node.parent.targets) == 1 - and isinstance(node.parent.targets[0], AssignName) + and isinstance(node.parent.targets[0], nodes.AssignName) ): raise UseInferenceDefault try: @@ -387,7 +375,7 @@ def infer_special_alias( raise InferenceError(node=node.args[0], context=ctx) from e assign_name = node.parent.targets[0] - class_def = ClassDef( + class_def = nodes.ClassDef( name=assign_name.name, parent=node.parent, lineno=assign_name.lineno, @@ -403,17 +391,17 @@ def infer_special_alias( return iter([class_def]) -def _looks_like_typing_cast(node: Call) -> bool: - return (isinstance(node.func, Name) and node.func.name == "cast") or ( - isinstance(node.func, Attribute) and node.func.attrname == "cast" +def _looks_like_typing_cast(node: nodes.Call) -> bool: + return (isinstance(node.func, nodes.Name) and node.func.name == "cast") or ( + isinstance(node.func, nodes.Attribute) and node.func.attrname == "cast" ) def infer_typing_cast( - node: Call, ctx: context.InferenceContext | None = None -) -> Iterator[NodeNG]: + node: nodes.Call, ctx: context.InferenceContext | None = None +) -> Iterator[nodes.NodeNG]: """Infer call to cast() returning same type as casted-from var.""" - if not isinstance(node.func, (Name, Attribute)): + if not isinstance(node.func, (nodes.Name, nodes.Attribute)): raise UseInferenceDefault try: @@ -421,7 +409,7 @@ def infer_typing_cast( except (InferenceError, StopIteration) as exc: raise UseInferenceDefault from exc if ( - not isinstance(func, FunctionDef) + not isinstance(func, nodes.FunctionDef) or func.qname() != "typing.cast" or len(node.args) != 2 ): @@ -481,32 +469,32 @@ def __class_getitem__(cls, item): return cls def register(manager: AstroidManager) -> None: manager.register_transform( - Call, + nodes.Call, inference_tip(infer_typing_typevar_or_newtype), looks_like_typing_typevar_or_newtype, ) manager.register_transform( - Subscript, inference_tip(infer_typing_attr), _looks_like_typing_subscript + nodes.Subscript, inference_tip(infer_typing_attr), _looks_like_typing_subscript ) manager.register_transform( - Call, inference_tip(infer_typing_cast), _looks_like_typing_cast + nodes.Call, inference_tip(infer_typing_cast), _looks_like_typing_cast ) manager.register_transform( - FunctionDef, inference_tip(infer_typedDict), _looks_like_typedDict + nodes.FunctionDef, inference_tip(infer_typedDict), _looks_like_typedDict ) manager.register_transform( - Call, inference_tip(infer_typing_alias), _looks_like_typing_alias + nodes.Call, inference_tip(infer_typing_alias), _looks_like_typing_alias ) manager.register_transform( - Call, inference_tip(infer_special_alias), _looks_like_special_alias + nodes.Call, inference_tip(infer_special_alias), _looks_like_special_alias ) if PY312_PLUS: register_module_extender(manager, "typing", _typing_transform) manager.register_transform( - ClassDef, + nodes.ClassDef, inference_tip(infer_typing_generic_class_pep695), _looks_like_generic_class_pep695, ) diff --git a/astroid/brain/brain_uuid.py b/astroid/brain/brain_uuid.py index 37800b8e0..4405a62b3 100644 --- a/astroid/brain/brain_uuid.py +++ b/astroid/brain/brain_uuid.py @@ -3,17 +3,16 @@ # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt """Astroid hooks for the UUID module.""" +from astroid import nodes from astroid.manager import AstroidManager -from astroid.nodes.node_classes import Const -from astroid.nodes.scoped_nodes import ClassDef -def _patch_uuid_class(node: ClassDef) -> None: +def _patch_uuid_class(node: nodes.ClassDef) -> None: # The .int member is patched using __dict__ - node.locals["int"] = [Const(0, parent=node)] + node.locals["int"] = [nodes.Const(0, parent=node)] def register(manager: AstroidManager) -> None: manager.register_transform( - ClassDef, _patch_uuid_class, lambda node: node.qname() == "uuid.UUID" + nodes.ClassDef, _patch_uuid_class, lambda node: node.qname() == "uuid.UUID" ) diff --git a/astroid/context.py b/astroid/context.py index d1aeef3bb..fa9ed2265 100644 --- a/astroid/context.py +++ b/astroid/context.py @@ -15,11 +15,9 @@ if TYPE_CHECKING: from astroid import constraint, nodes - from astroid.nodes.node_classes import Keyword - from astroid.nodes.node_ng import NodeNG _InferenceCache = dict[ - tuple["NodeNG", str | None, str | None, str | None], Sequence["NodeNG"] + tuple["nodes.NodeNG", str | None, str | None, str | None], Sequence["nodes.NodeNG"] ] _INFERENCE_CACHE: _InferenceCache = {} @@ -170,8 +168,8 @@ class CallContext: def __init__( self, - args: list[NodeNG], - keywords: list[Keyword] | None = None, + args: list[nodes.NodeNG], + keywords: list[nodes.Keyword] | None = None, callee: InferenceResult | None = None, ): self.args = args # Call positional arguments diff --git a/astroid/interpreter/dunder_lookup.py b/astroid/interpreter/dunder_lookup.py index 727c1ad46..8eab35c4f 100644 --- a/astroid/interpreter/dunder_lookup.py +++ b/astroid/interpreter/dunder_lookup.py @@ -18,20 +18,20 @@ from typing import TYPE_CHECKING import astroid +from astroid import nodes from astroid.exceptions import AttributeInferenceError if TYPE_CHECKING: - from astroid import nodes from astroid.context import InferenceContext def _lookup_in_mro(node, name) -> list: attrs = node.locals.get(name, []) - nodes = itertools.chain.from_iterable( + nodes_ = itertools.chain.from_iterable( ancestor.locals.get(name, []) for ancestor in node.ancestors(recurs=True) ) - values = list(itertools.chain(attrs, nodes)) + values = list(itertools.chain(attrs, nodes_)) if not values: raise AttributeInferenceError(attribute=name, target=node) @@ -47,13 +47,11 @@ def lookup( will be returned. Otherwise, `astroid.AttributeInferenceError` is going to be raised. """ - if isinstance( - node, (astroid.List, astroid.Tuple, astroid.Const, astroid.Dict, astroid.Set) - ): + if isinstance(node, (nodes.List, nodes.Tuple, nodes.Const, nodes.Dict, nodes.Set)): return _builtin_lookup(node, name) if isinstance(node, astroid.Instance): return _lookup_in_mro(node, name) - if isinstance(node, astroid.ClassDef): + if isinstance(node, nodes.ClassDef): return _class_lookup(node, name, context=context) raise AttributeInferenceError(attribute=name, target=node) diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py index 31ef12e41..eac9e4308 100644 --- a/astroid/interpreter/objectmodel.py +++ b/astroid/interpreter/objectmodel.py @@ -427,13 +427,13 @@ def test(self): we get a new object which has two parameters, *self* and *type*. """ nonlocal func - arguments = astroid.Arguments( + arguments = nodes.Arguments( parent=func.args.parent, vararg=None, kwarg=None ) positional_or_keyword_params = func.args.args.copy() positional_or_keyword_params.append( - astroid.AssignName( + nodes.AssignName( name="type", lineno=0, col_offset=0, @@ -953,7 +953,7 @@ def infer_call_result( def attr_fset(self): func = self._instance - def find_setter(func: Property) -> astroid.FunctionDef | None: + def find_setter(func: Property) -> nodes.FunctionDef | None: """ Given a property, find the corresponding setter function and returns it. diff --git a/astroid/manager.py b/astroid/manager.py index 163321b80..e2328862a 100644 --- a/astroid/manager.py +++ b/astroid/manager.py @@ -412,7 +412,7 @@ def register_failed_import_hook(self, hook: Callable[[str], nodes.Module]) -> No `hook` must be a function that accepts a single argument `modname` which contains the name of the module or package that could not be imported. - If `hook` can resolve the import, must return a node of type `astroid.Module`, + If `hook` can resolve the import, must return a node of type `nodes.Module`, otherwise, it must raise `AstroidBuildingError`. """ self._failed_import_hooks.append(hook) diff --git a/astroid/nodes/as_string.py b/astroid/nodes/as_string.py index 7d04b5eb6..01007b96e 100644 --- a/astroid/nodes/as_string.py +++ b/astroid/nodes/as_string.py @@ -14,23 +14,6 @@ if TYPE_CHECKING: from astroid import objects - from astroid.nodes import Const - from astroid.nodes.node_classes import ( - Interpolation, - Match, - MatchAs, - MatchCase, - MatchClass, - MatchMapping, - MatchOr, - MatchSequence, - MatchSingleton, - MatchStar, - MatchValue, - TemplateStr, - Unknown, - ) - from astroid.nodes.node_ng import NodeNG # pylint: disable=unused-argument @@ -45,11 +28,11 @@ class AsStringVisitor: def __init__(self, indent: str = " "): self.indent: str = indent - def __call__(self, node: NodeNG) -> str: + def __call__(self, node: nodes.NodeNG) -> str: """Makes this visitor behave as a simple function""" return node.accept(self).replace(DOC_NEWLINE, "\n") - def _docs_dedent(self, doc_node: Const | None) -> str: + def _docs_dedent(self, doc_node: nodes.Const | None) -> str: """Stop newlines in docs being indented by self._stmt_list""" if not doc_node: return "" @@ -69,7 +52,7 @@ def _stmt_list(self, stmts: list, indent: bool = True) -> str: return self.indent + stmts_str.replace("\n", "\n" + self.indent) def _precedence_parens( - self, node: NodeNG, child: NodeNG, is_left: bool = True + self, node: nodes.NodeNG, child: nodes.NodeNG, is_left: bool = True ) -> str: """Wrap child in parens only if required to keep same semantics""" if self._should_wrap(node, child, is_left): @@ -77,7 +60,9 @@ def _precedence_parens( return child.accept(self) - def _should_wrap(self, node: NodeNG, child: NodeNG, is_left: bool) -> bool: + def _should_wrap( + self, node: nodes.NodeNG, child: nodes.NodeNG, is_left: bool + ) -> bool: """Wrap child if: - it has lower precedence - same precedence with position opposite to associativity direction @@ -111,34 +96,34 @@ def visit_asyncfor(self, node: nodes.AsyncFor) -> str: return f"async {self.visit_for(node)}" def visit_arguments(self, node: nodes.Arguments) -> str: - """return an astroid.Arguments node as string""" + """return an nodes.Arguments node as string""" return node.format_args() def visit_assignattr(self, node: nodes.AssignAttr) -> str: - """return an astroid.AssignAttr node as string""" + """return an nodes.AssignAttr node as string""" return self.visit_attribute(node) def visit_assert(self, node: nodes.Assert) -> str: - """return an astroid.Assert node as string""" + """return an nodes.Assert node as string""" if node.fail: return f"assert {node.test.accept(self)}, {node.fail.accept(self)}" return f"assert {node.test.accept(self)}" def visit_assignname(self, node: nodes.AssignName) -> str: - """return an astroid.AssignName node as string""" + """return an nodes.AssignName node as string""" return node.name def visit_assign(self, node: nodes.Assign) -> str: - """return an astroid.Assign node as string""" + """return an nodes.Assign node as string""" lhs = " = ".join(n.accept(self) for n in node.targets) return f"{lhs} = {node.value.accept(self)}" def visit_augassign(self, node: nodes.AugAssign) -> str: - """return an astroid.AugAssign node as string""" + """return an nodes.AugAssign node as string""" return f"{node.target.accept(self)} {node.op} {node.value.accept(self)}" def visit_annassign(self, node: nodes.AnnAssign) -> str: - """Return an astroid.AnnAssign node as string""" + """Return an nodes.AnnAssign node as string""" target = node.target.accept(self) annotation = node.annotation.accept(self) @@ -147,7 +132,7 @@ def visit_annassign(self, node: nodes.AnnAssign) -> str: return f"{target}: {annotation} = {node.value.accept(self)}" def visit_binop(self, node: nodes.BinOp) -> str: - """return an astroid.BinOp node as string""" + """return an nodes.BinOp node as string""" left = self._precedence_parens(node, node.left) right = self._precedence_parens(node, node.right, is_left=False) if node.op == "**": @@ -156,16 +141,16 @@ def visit_binop(self, node: nodes.BinOp) -> str: return f"{left} {node.op} {right}" def visit_boolop(self, node: nodes.BoolOp) -> str: - """return an astroid.BoolOp node as string""" + """return an nodes.BoolOp node as string""" values = [f"{self._precedence_parens(node, n)}" for n in node.values] return (f" {node.op} ").join(values) def visit_break(self, node: nodes.Break) -> str: - """return an astroid.Break node as string""" + """return an nodes.Break node as string""" return "break" def visit_call(self, node: nodes.Call) -> str: - """return an astroid.Call node as string""" + """return an nodes.Call node as string""" expr_str = self._precedence_parens(node, node.func) args = [arg.accept(self) for arg in node.args] if node.keywords: @@ -186,7 +171,7 @@ def _handle_type_params( ) def visit_classdef(self, node: nodes.ClassDef) -> str: - """return an astroid.ClassDef node as string""" + """return an nodes.ClassDef node as string""" decorate = node.decorators.accept(self) if node.decorators else "" type_params = self._handle_type_params(node.type_params) args = [n.accept(self) for n in node.bases] @@ -200,7 +185,7 @@ def visit_classdef(self, node: nodes.ClassDef) -> str: ) def visit_compare(self, node: nodes.Compare) -> str: - """return an astroid.Compare node as string""" + """return an nodes.Compare node as string""" rhs_str = " ".join( f"{op} {self._precedence_parens(node, expr, is_left=False)}" for op, expr in node.ops @@ -208,39 +193,39 @@ def visit_compare(self, node: nodes.Compare) -> str: return f"{self._precedence_parens(node, node.left)} {rhs_str}" def visit_comprehension(self, node: nodes.Comprehension) -> str: - """return an astroid.Comprehension node as string""" + """return an nodes.Comprehension node as string""" ifs = "".join(f" if {n.accept(self)}" for n in node.ifs) generated = f"for {node.target.accept(self)} in {node.iter.accept(self)}{ifs}" return f"{'async ' if node.is_async else ''}{generated}" def visit_const(self, node: nodes.Const) -> str: - """return an astroid.Const node as string""" + """return an nodes.Const node as string""" if node.value is Ellipsis: return "..." return repr(node.value) def visit_continue(self, node: nodes.Continue) -> str: - """return an astroid.Continue node as string""" + """return an nodes.Continue node as string""" return "continue" def visit_delete(self, node: nodes.Delete) -> str: - """return an astroid.Delete node as string""" + """return an nodes.Delete node as string""" return f"del {', '.join(child.accept(self) for child in node.targets)}" def visit_delattr(self, node: nodes.DelAttr) -> str: - """return an astroid.DelAttr node as string""" + """return an nodes.DelAttr node as string""" return self.visit_attribute(node) def visit_delname(self, node: nodes.DelName) -> str: - """return an astroid.DelName node as string""" + """return an nodes.DelName node as string""" return node.name def visit_decorators(self, node: nodes.Decorators) -> str: - """return an astroid.Decorators node as string""" + """return an nodes.Decorators node as string""" return "@%s\n" % "\n@".join(item.accept(self) for item in node.nodes) def visit_dict(self, node: nodes.Dict) -> str: - """return an astroid.Dict node as string""" + """return an nodes.Dict node as string""" return "{%s}" % ", ".join(self._visit_dict(node)) def _visit_dict(self, node: nodes.Dict) -> Iterator[str]: @@ -257,7 +242,7 @@ def visit_dictunpack(self, node: nodes.DictUnpack) -> str: return "**" def visit_dictcomp(self, node: nodes.DictComp) -> str: - """return an astroid.DictComp node as string""" + """return an nodes.DictComp node as string""" return "{{{}: {} {}}}".format( node.key.accept(self), node.value.accept(self), @@ -265,7 +250,7 @@ def visit_dictcomp(self, node: nodes.DictComp) -> str: ) def visit_expr(self, node: nodes.Expr) -> str: - """return an astroid.Expr node as string""" + """return an nodes.Expr node as string""" return node.value.accept(self) def visit_emptynode(self, node: nodes.EmptyNode) -> str: @@ -290,7 +275,7 @@ def visit_empty(self, node: nodes.EmptyNode) -> str: return "" def visit_for(self, node: nodes.For) -> str: - """return an astroid.For node as string""" + """return an nodes.For node as string""" fors = "for {} in {}:\n{}".format( node.target.accept(self), node.iter.accept(self), self._stmt_list(node.body) ) @@ -299,7 +284,7 @@ def visit_for(self, node: nodes.For) -> str: return fors def visit_importfrom(self, node: nodes.ImportFrom) -> str: - """return an astroid.ImportFrom node as string""" + """return an nodes.ImportFrom node as string""" return "from {} import {}".format( "." * (node.level or 0) + node.modname, _import_string(node.names) ) @@ -364,15 +349,15 @@ def handle_functiondef(self, node: nodes.FunctionDef, keyword: str) -> str: ) def visit_functiondef(self, node: nodes.FunctionDef) -> str: - """return an astroid.FunctionDef node as string""" + """return an nodes.FunctionDef node as string""" return self.handle_functiondef(node, "def") def visit_asyncfunctiondef(self, node: nodes.AsyncFunctionDef) -> str: - """return an astroid.AsyncFunction node as string""" + """return an nodes.AsyncFunction node as string""" return self.handle_functiondef(node, "async def") def visit_generatorexp(self, node: nodes.GeneratorExp) -> str: - """return an astroid.GeneratorExp node as string""" + """return an nodes.GeneratorExp node as string""" return "({} {})".format( node.elt.accept(self), " ".join(n.accept(self) for n in node.generators) ) @@ -380,7 +365,7 @@ def visit_generatorexp(self, node: nodes.GeneratorExp) -> str: def visit_attribute( self, node: nodes.Attribute | nodes.AssignAttr | nodes.DelAttr ) -> str: - """return an astroid.Attribute node as string""" + """return an nodes.Attribute node as string""" try: left = self._precedence_parens(node, node.expr) except RecursionError: @@ -395,11 +380,11 @@ def visit_attribute( return f"{left}.{node.attrname}" def visit_global(self, node: nodes.Global) -> str: - """return an astroid.Global node as string""" + """return an nodes.Global node as string""" return f"global {', '.join(node.names)}" def visit_if(self, node: nodes.If) -> str: - """return an astroid.If node as string""" + """return an nodes.If node as string""" ifs = [f"if {node.test.accept(self)}:\n{self._stmt_list(node.body)}"] if node.has_elif_block(): ifs.append(f"el{self._stmt_list(node.orelse, indent=False)}") @@ -408,7 +393,7 @@ def visit_if(self, node: nodes.If) -> str: return "\n".join(ifs) def visit_ifexp(self, node: nodes.IfExp) -> str: - """return an astroid.IfExp node as string""" + """return an nodes.IfExp node as string""" return "{} if {} else {}".format( self._precedence_parens(node, node.body, is_left=True), self._precedence_parens(node, node.test, is_left=True), @@ -416,17 +401,17 @@ def visit_ifexp(self, node: nodes.IfExp) -> str: ) def visit_import(self, node: nodes.Import) -> str: - """return an astroid.Import node as string""" + """return an nodes.Import node as string""" return f"import {_import_string(node.names)}" def visit_keyword(self, node: nodes.Keyword) -> str: - """return an astroid.Keyword node as string""" + """return an nodes.Keyword node as string""" if node.arg is None: return f"**{node.value.accept(self)}" return f"{node.arg}={node.value.accept(self)}" def visit_lambda(self, node: nodes.Lambda) -> str: - """return an astroid.Lambda node as string""" + """return an nodes.Lambda node as string""" args = node.args.accept(self) body = node.body.accept(self) if args: @@ -435,22 +420,22 @@ def visit_lambda(self, node: nodes.Lambda) -> str: return f"lambda: {body}" def visit_list(self, node: nodes.List) -> str: - """return an astroid.List node as string""" + """return an nodes.List node as string""" return f"[{', '.join(child.accept(self) for child in node.elts)}]" def visit_listcomp(self, node: nodes.ListComp) -> str: - """return an astroid.ListComp node as string""" + """return an nodes.ListComp node as string""" return "[{} {}]".format( node.elt.accept(self), " ".join(n.accept(self) for n in node.generators) ) def visit_module(self, node: nodes.Module) -> str: - """return an astroid.Module node as string""" + """return an nodes.Module node as string""" docs = f'"""{node.doc_node.value}"""\n\n' if node.doc_node else "" return docs + "\n".join(n.accept(self) for n in node.body) + "\n\n" def visit_name(self, node: nodes.Name) -> str: - """return an astroid.Name node as string""" + """return an nodes.Name node as string""" return node.name def visit_namedexpr(self, node: nodes.NamedExpr) -> str: @@ -460,18 +445,18 @@ def visit_namedexpr(self, node: nodes.NamedExpr) -> str: return f"{target} := {value}" def visit_nonlocal(self, node: nodes.Nonlocal) -> str: - """return an astroid.Nonlocal node as string""" + """return an nodes.Nonlocal node as string""" return f"nonlocal {', '.join(node.names)}" def visit_paramspec(self, node: nodes.ParamSpec) -> str: - """return an astroid.ParamSpec node as string""" + """return an nodes.ParamSpec node as string""" default_value_str = ( f" = {node.default_value.accept(self)}" if node.default_value else "" ) return f"**{node.name.accept(self)}{default_value_str}" def visit_pass(self, node: nodes.Pass) -> str: - """return an astroid.Pass node as string""" + """return an nodes.Pass node as string""" return "pass" def visit_partialfunction(self, node: objects.PartialFunction) -> str: @@ -479,7 +464,7 @@ def visit_partialfunction(self, node: objects.PartialFunction) -> str: return self.visit_functiondef(node) def visit_raise(self, node: nodes.Raise) -> str: - """return an astroid.Raise node as string""" + """return an nodes.Raise node as string""" if node.exc: if node.cause: return f"raise {node.exc.accept(self)} from {node.cause.accept(self)}" @@ -487,7 +472,7 @@ def visit_raise(self, node: nodes.Raise) -> str: return "raise" def visit_return(self, node: nodes.Return) -> str: - """return an astroid.Return node as string""" + """return an nodes.Return node as string""" if node.is_tuple_return() and len(node.value.elts) > 1: elts = [child.accept(self) for child in node.value.elts] return f"return {', '.join(elts)}" @@ -498,17 +483,17 @@ def visit_return(self, node: nodes.Return) -> str: return "return" def visit_set(self, node: nodes.Set) -> str: - """return an astroid.Set node as string""" + """return an nodes.Set node as string""" return "{%s}" % ", ".join(child.accept(self) for child in node.elts) def visit_setcomp(self, node: nodes.SetComp) -> str: - """return an astroid.SetComp node as string""" + """return an nodes.SetComp node as string""" return "{{{} {}}}".format( node.elt.accept(self), " ".join(n.accept(self) for n in node.generators) ) def visit_slice(self, node: nodes.Slice) -> str: - """return an astroid.Slice node as string""" + """return an nodes.Slice node as string""" lower = node.lower.accept(self) if node.lower else "" upper = node.upper.accept(self) if node.upper else "" step = node.step.accept(self) if node.step else "" @@ -517,7 +502,7 @@ def visit_slice(self, node: nodes.Slice) -> str: return f"{lower}:{upper}" def visit_subscript(self, node: nodes.Subscript) -> str: - """return an astroid.Subscript node as string""" + """return an nodes.Subscript node as string""" idx = node.slice if idx.__class__.__name__.lower() == "index": idx = idx.value @@ -529,7 +514,7 @@ def visit_subscript(self, node: nodes.Subscript) -> str: return f"{self._precedence_parens(node, node.value)}[{idxstr}]" def visit_try(self, node: nodes.Try) -> str: - """return an astroid.Try node as string""" + """return an nodes.Try node as string""" trys = [f"try:\n{self._stmt_list(node.body)}"] for handler in node.handlers: trys.append(handler.accept(self)) @@ -540,7 +525,7 @@ def visit_try(self, node: nodes.Try) -> str: return "\n".join(trys) def visit_trystar(self, node: nodes.TryStar) -> str: - """return an astroid.TryStar node as string""" + """return an nodes.TryStar node as string""" trys = [f"try:\n{self._stmt_list(node.body)}"] for handler in node.handlers: trys.append(handler.accept(self)) @@ -551,18 +536,18 @@ def visit_trystar(self, node: nodes.TryStar) -> str: return "\n".join(trys) def visit_tuple(self, node: nodes.Tuple) -> str: - """return an astroid.Tuple node as string""" + """return an nodes.Tuple node as string""" if len(node.elts) == 1: return f"({node.elts[0].accept(self)}, )" return f"({', '.join(child.accept(self) for child in node.elts)})" def visit_typealias(self, node: nodes.TypeAlias) -> str: - """return an astroid.TypeAlias node as string""" + """return an nodes.TypeAlias node as string""" type_params = self._handle_type_params(node.type_params) return f"type {node.name.accept(self)}{type_params} = {node.value.accept(self)}" def visit_typevar(self, node: nodes.TypeVar) -> str: - """return an astroid.TypeVar node as string""" + """return an nodes.TypeVar node as string""" bound_str = f": {node.bound.accept(self)}" if node.bound else "" default_value_str = ( f" = {node.default_value.accept(self)}" if node.default_value else "" @@ -570,14 +555,14 @@ def visit_typevar(self, node: nodes.TypeVar) -> str: return f"{node.name.accept(self)}{bound_str}{default_value_str}" def visit_typevartuple(self, node: nodes.TypeVarTuple) -> str: - """return an astroid.TypeVarTuple node as string""" + """return an nodes.TypeVarTuple node as string""" default_value_str = ( f" = {node.default_value.accept(self)}" if node.default_value else "" ) return f"*{node.name.accept(self)}{default_value_str}" def visit_unaryop(self, node: nodes.UnaryOp) -> str: - """return an astroid.UnaryOp node as string""" + """return an nodes.UnaryOp node as string""" if node.op == "not": operator = "not " else: @@ -585,14 +570,14 @@ def visit_unaryop(self, node: nodes.UnaryOp) -> str: return f"{operator}{self._precedence_parens(node, node.operand)}" def visit_while(self, node: nodes.While) -> str: - """return an astroid.While node as string""" + """return an nodes.While node as string""" whiles = f"while {node.test.accept(self)}:\n{self._stmt_list(node.body)}" if node.orelse: whiles = f"{whiles}\nelse:\n{self._stmt_list(node.orelse)}" return whiles def visit_with(self, node: nodes.With) -> str: # 'with' without 'as' is possible - """return an astroid.With node as string""" + """return an nodes.With node as string""" items = ", ".join( f"{expr.accept(self)}" + ((v and f" as {v.accept(self)}") or "") for expr, v in node.items @@ -609,7 +594,7 @@ def visit_yield(self, node: nodes.Yield) -> str: return f"({expr})" def visit_yieldfrom(self, node: nodes.YieldFrom) -> str: - """Return an astroid.YieldFrom node as string.""" + """Return an nodes.YieldFrom node as string.""" yi_val = (" " + node.value.accept(self)) if node.value else "" expr = "yield from" + yi_val if node.parent.is_statement: @@ -621,35 +606,35 @@ def visit_starred(self, node: nodes.Starred) -> str: """return Starred node as string""" return "*" + node.value.accept(self) - def visit_match(self, node: Match) -> str: - """Return an astroid.Match node as string.""" + def visit_match(self, node: nodes.Match) -> str: + """Return an nodes.Match node as string.""" return f"match {node.subject.accept(self)}:\n{self._stmt_list(node.cases)}" - def visit_matchcase(self, node: MatchCase) -> str: - """Return an astroid.MatchCase node as string.""" + def visit_matchcase(self, node: nodes.MatchCase) -> str: + """Return an nodes.MatchCase node as string.""" guard_str = f" if {node.guard.accept(self)}" if node.guard else "" return ( f"case {node.pattern.accept(self)}{guard_str}:\n" f"{self._stmt_list(node.body)}" ) - def visit_matchvalue(self, node: MatchValue) -> str: - """Return an astroid.MatchValue node as string.""" + def visit_matchvalue(self, node: nodes.MatchValue) -> str: + """Return an nodes.MatchValue node as string.""" return node.value.accept(self) @staticmethod - def visit_matchsingleton(node: MatchSingleton) -> str: - """Return an astroid.MatchSingleton node as string.""" + def visit_matchsingleton(node: nodes.MatchSingleton) -> str: + """Return an nodes.MatchSingleton node as string.""" return str(node.value) - def visit_matchsequence(self, node: MatchSequence) -> str: - """Return an astroid.MatchSequence node as string.""" + def visit_matchsequence(self, node: nodes.MatchSequence) -> str: + """Return an nodes.MatchSequence node as string.""" if node.patterns is None: return "[]" return f"[{', '.join(p.accept(self) for p in node.patterns)}]" - def visit_matchmapping(self, node: MatchMapping) -> str: - """Return an astroid.MatchMapping node as string.""" + def visit_matchmapping(self, node: nodes.MatchMapping) -> str: + """Return an nodes..MatchMapping node as string.""" mapping_strings: list[str] = [] if node.keys and node.patterns: mapping_strings.extend( @@ -660,8 +645,8 @@ def visit_matchmapping(self, node: MatchMapping) -> str: mapping_strings.append(f"**{node.rest.accept(self)}") return f"{'{'}{', '.join(mapping_strings)}{'}'}" - def visit_matchclass(self, node: MatchClass) -> str: - """Return an astroid.MatchClass node as string.""" + def visit_matchclass(self, node: nodes.MatchClass) -> str: + """Return an nodes..MatchClass node as string.""" if node.cls is None: raise AssertionError(f"{node} does not have a 'cls' node") class_strings: list[str] = [] @@ -672,31 +657,29 @@ def visit_matchclass(self, node: MatchClass) -> str: class_strings.append(f"{attr}={pattern.accept(self)}") return f"{node.cls.accept(self)}({', '.join(class_strings)})" - def visit_matchstar(self, node: MatchStar) -> str: - """Return an astroid.MatchStar node as string.""" + def visit_matchstar(self, node: nodes.MatchStar) -> str: + """Return an nodes..MatchStar node as string.""" return f"*{node.name.accept(self) if node.name else '_'}" - def visit_matchas(self, node: MatchAs) -> str: - """Return an astroid.MatchAs node as string.""" - # pylint: disable=import-outside-toplevel - # Prevent circular dependency - from astroid.nodes.node_classes import MatchClass, MatchMapping, MatchSequence - - if isinstance(node.parent, (MatchSequence, MatchMapping, MatchClass)): + def visit_matchas(self, node: nodes.MatchAs) -> str: + """Return an nodes..MatchAs node as string.""" + if isinstance( + node.parent, (nodes.MatchSequence, nodes.MatchMapping, nodes.MatchClass) + ): return node.name.accept(self) if node.name else "_" return ( f"{node.pattern.accept(self) if node.pattern else '_'}" f"{f' as {node.name.accept(self)}' if node.name else ''}" ) - def visit_matchor(self, node: MatchOr) -> str: - """Return an astroid.MatchOr node as string.""" + def visit_matchor(self, node: nodes.MatchOr) -> str: + """Return an nodes.MatchOr node as string.""" if node.patterns is None: raise AssertionError(f"{node} does not have pattern nodes") return " | ".join(p.accept(self) for p in node.patterns) - def visit_templatestr(self, node: TemplateStr) -> str: - """Return an astroid.TemplateStr node as string.""" + def visit_templatestr(self, node: nodes.TemplateStr) -> str: + """Return an nodes.TemplateStr node as string.""" string = "" for value in node.values: match value: @@ -709,8 +692,8 @@ def visit_templatestr(self, node: TemplateStr) -> str: break return "t" + quote + string + quote - def visit_interpolation(self, node: Interpolation) -> str: - """Return an astroid.Interpolation node as string.""" + def visit_interpolation(self, node: nodes.Interpolation) -> str: + """Return an nodes.Interpolation node as string.""" result = f"{node.str}" if node.conversion and node.conversion >= 0: # e.g. if node.conversion == 114: result += "!r" @@ -738,7 +721,7 @@ def visit_property(self, node: objects.Property) -> str: def visit_evaluatedobject(self, node: nodes.EvaluatedObject) -> str: return node.original.accept(self) - def visit_unknown(self, node: Unknown) -> str: + def visit_unknown(self, node: nodes.Unknown) -> str: return str(node) diff --git a/tests/brain/test_attr.py b/tests/brain/test_attr.py index 667561bd0..23dae4708 100644 --- a/tests/brain/test_attr.py +++ b/tests/brain/test_attr.py @@ -85,7 +85,7 @@ class Eggs: for name in ("f", "g", "h", "i", "j", "k", "l", "m"): should_be_unknown = next(module.getattr(name)[0].infer()).getattr("d")[0] - self.assertIsInstance(should_be_unknown, astroid.Unknown) + self.assertIsInstance(should_be_unknown, nodes.Unknown) def test_attrs_transform(self) -> None: """Test brain for decorators of the 'attrs' package. @@ -158,7 +158,7 @@ class Legs: for name in ("f", "g", "h", "i", "j", "k", "l"): should_be_unknown = next(module.getattr(name)[0].infer()).getattr("d")[0] - self.assertIsInstance(should_be_unknown, astroid.Unknown, name) + self.assertIsInstance(should_be_unknown, nodes.Unknown, name) def test_special_attributes(self) -> None: """Make sure special attrs attributes exist""" @@ -200,7 +200,7 @@ class Foo: Foo() """ should_be_unknown = next(astroid.extract_node(code).infer()).getattr("bar")[0] - self.assertIsInstance(should_be_unknown, astroid.Unknown) + self.assertIsInstance(should_be_unknown, nodes.Unknown) def test_attr_with_only_annotation_fails(self) -> None: code = """ @@ -228,7 +228,7 @@ class Foo: should_be_unknown = next(astroid.extract_node(code).infer()).getattr( attr_name )[0] - self.assertIsInstance(should_be_unknown, astroid.Unknown) + self.assertIsInstance(should_be_unknown, nodes.Unknown) def test_attrs_with_class_var_annotation(self) -> None: cases = { diff --git a/tests/brain/test_brain.py b/tests/brain/test_brain.py index 0e1ec7dbb..64dbdc876 100644 --- a/tests/brain/test_brain.py +++ b/tests/brain/test_brain.py @@ -21,11 +21,9 @@ InferenceError, UseInferenceDefault, ) -from astroid.nodes.node_classes import Const -from astroid.nodes.scoped_nodes import ClassDef -def assertEqualMro(klass: ClassDef, expected_mro: list[str]) -> None: +def assertEqualMro(klass: nodes.ClassDef, expected_mro: list[str]) -> None: """Check mro names.""" assert [member.qname() for member in klass.mro()] == expected_mro @@ -140,10 +138,10 @@ def test_type_subscript(self): """ ) val_inf = src.annotation.value.inferred()[0] - self.assertIsInstance(val_inf, astroid.ClassDef) + self.assertIsInstance(val_inf, nodes.ClassDef) self.assertEqual(val_inf.name, "type") meth_inf = val_inf.getattr("__class_getitem__")[0] - self.assertIsInstance(meth_inf, astroid.FunctionDef) + self.assertIsInstance(meth_inf, nodes.FunctionDef) def test_invalid_type_subscript(self): """ @@ -157,7 +155,7 @@ def test_invalid_type_subscript(self): """ ) val_inf = src.annotation.value.inferred()[0] - self.assertIsInstance(val_inf, astroid.ClassDef) + self.assertIsInstance(val_inf, nodes.ClassDef) self.assertEqual(val_inf.name, "str") with self.assertRaises(AttributeInferenceError): # pylint: disable=expression-not-assigned @@ -365,7 +363,7 @@ def as_integer(self): ) self.assertEqual(len(klass.getattr("as_string")), 1) inferred = next(called.infer()) - self.assertIsInstance(inferred, astroid.Const) + self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, 5) def test_namedtuple_inference(self) -> None: @@ -455,7 +453,7 @@ class Example(NamedTuple): self.assertIsInstance(inferred, astroid.Instance) class_attr = inferred.getattr("CLASS_ATTR")[0] - self.assertIsInstance(class_attr, astroid.AssignName) + self.assertIsInstance(class_attr, nodes.AssignName) const = next(class_attr.infer()) self.assertEqual(const.value, "class_attr") @@ -546,10 +544,10 @@ class Foo: """ ) inferred = next(result.infer()) - self.assertIsInstance(inferred, astroid.ClassDef) + self.assertIsInstance(inferred, nodes.ClassDef) class_def_attr = inferred.getattr("Foo")[0] - self.assertIsInstance(class_def_attr, astroid.ClassDef) + self.assertIsInstance(class_def_attr, nodes.ClassDef) attr_def = class_def_attr.getattr("bar")[0] attr = next(attr_def.infer()) self.assertEqual(attr.value, "bar") @@ -1040,7 +1038,7 @@ def test_inferred_successfully(self) -> None: """ ) inferred = next(node.infer()) - self.assertIsInstance(inferred, astroid.List) + self.assertIsInstance(inferred, nodes.List) elems = sorted(elem.value for elem in inferred.elts) self.assertEqual(elems, [1, 2]) @@ -1058,12 +1056,12 @@ def sequence(): ) # Check that arguments are of type `nodes.Call`. sequence, length = node.args - self.assertIsInstance(sequence, astroid.Call) - self.assertIsInstance(length, astroid.Call) + self.assertIsInstance(sequence, nodes.Call) + self.assertIsInstance(length, nodes.Call) # Check the inference of `random.sample` call. inferred = next(node.infer()) - self.assertIsInstance(inferred, astroid.List) + self.assertIsInstance(inferred, nodes.List) elems = sorted(elem.value for elem in inferred.elts) self.assertEqual(elems, [1, 2]) @@ -1075,7 +1073,7 @@ class A: pass sample(list({1: A()}.values()), 1)""" ) inferred = next(node.infer()) - assert isinstance(inferred, astroid.List) + assert isinstance(inferred, nodes.List) assert len(inferred.elts) == 1 assert isinstance(inferred.elts[0], nodes.Call) @@ -1106,7 +1104,7 @@ def test_subprcess_check_output(self) -> None: node = astroid.extract_node(code) inferred = next(node.infer()) # Can be either str or bytes - assert isinstance(inferred, astroid.Const) + assert isinstance(inferred, nodes.Const) assert isinstance(inferred.value, (str, bytes)) def test_popen_does_not_have_class_getitem(self): @@ -1361,7 +1359,7 @@ def test_too_many_args(self) -> None: _get_result_node("issubclass(int, int, str)") -def _get_result_node(code: str) -> Const: +def _get_result_node(code: str) -> nodes.Const: node = next(astroid.extract_node(code).infer()) return node @@ -1582,7 +1580,7 @@ def test_infer_str() -> None: ) for node in ast_nodes: inferred = next(node.infer()) - assert isinstance(inferred, astroid.Const) + assert isinstance(inferred, nodes.Const) node = astroid.extract_node( """ @@ -1603,7 +1601,7 @@ def test_infer_int() -> None: ) for node in ast_nodes: inferred = next(node.infer()) - assert isinstance(inferred, astroid.Const) + assert isinstance(inferred, nodes.Const) ast_nodes = astroid.extract_node( """ @@ -1645,7 +1643,7 @@ def test_infer_dict_from_keys() -> None: ) for node in good_nodes: inferred = next(node.infer()) - assert isinstance(inferred, astroid.Dict) + assert isinstance(inferred, nodes.Dict) assert inferred.items == [] # Test inferable values @@ -1657,9 +1655,9 @@ def test_infer_dict_from_keys() -> None: """ ) inferred = next(from_dict.infer()) - assert isinstance(inferred, astroid.Dict) + assert isinstance(inferred, nodes.Dict) itered = inferred.itered() - assert all(isinstance(elem, astroid.Const) for elem in itered) + assert all(isinstance(elem, nodes.Const) for elem in itered) actual_values = [elem.value for elem in itered] assert sorted(actual_values) == ["a", "b", "c"] @@ -1670,9 +1668,9 @@ def test_infer_dict_from_keys() -> None: """ ) inferred = next(from_string.infer()) - assert isinstance(inferred, astroid.Dict) + assert isinstance(inferred, nodes.Dict) itered = inferred.itered() - assert all(isinstance(elem, astroid.Const) for elem in itered) + assert all(isinstance(elem, nodes.Const) for elem in itered) actual_values = [elem.value for elem in itered] assert sorted(actual_values) == ["a", "b", "c"] @@ -1683,9 +1681,9 @@ def test_infer_dict_from_keys() -> None: """ ) inferred = next(from_bytes.infer()) - assert isinstance(inferred, astroid.Dict) + assert isinstance(inferred, nodes.Dict) itered = inferred.itered() - assert all(isinstance(elem, astroid.Const) for elem in itered) + assert all(isinstance(elem, nodes.Const) for elem in itered) actual_values = [elem.value for elem in itered] assert sorted(actual_values) == [97, 98, 99] @@ -1699,9 +1697,9 @@ def test_infer_dict_from_keys() -> None: ) for node in from_others: inferred = next(node.infer()) - assert isinstance(inferred, astroid.Dict) + assert isinstance(inferred, nodes.Dict) itered = inferred.itered() - assert all(isinstance(elem, astroid.Const) for elem in itered) + assert all(isinstance(elem, nodes.Const) for elem in itered) actual_values = [elem.value for elem in itered] assert sorted(actual_values) == ["a", "b", "c"] @@ -1749,7 +1747,7 @@ def test(a, b, c): ) for node in ast_nodes: inferred = next(node.infer()) - assert isinstance(inferred, (astroid.FunctionDef, astroid.Instance)) + assert isinstance(inferred, (nodes.FunctionDef, astroid.Instance)) assert inferred.qname() in { "functools.partial", "functools.partial.newfunc", @@ -1780,7 +1778,7 @@ def other_test(a, b, *, c=1): expected_values = [4, 7, 7, 3, 12, 16, 32, 36, 3, 9, 7] for node, expected_value in zip(ast_nodes, expected_values): inferred = next(node.infer()) - assert isinstance(inferred, astroid.Const) + assert isinstance(inferred, nodes.Const) assert inferred.value == expected_value def test_partial_assignment(self) -> None: @@ -1881,7 +1879,7 @@ def test_http_status_brain() -> None: """ ) inferred = next(node.infer()) - assert isinstance(inferred, astroid.Const) + assert isinstance(inferred, nodes.Const) def test_http_status_brain_iterable() -> None: @@ -1908,7 +1906,7 @@ def test_oserror_model() -> None: ) inferred = next(node.infer()) strerror = next(inferred.igetattr("strerror")) - assert isinstance(strerror, astroid.Const) + assert isinstance(strerror, nodes.Const) assert strerror.value == "" @@ -1929,9 +1927,9 @@ def test_crypt_brain() -> None: @pytest.mark.parametrize( "code,expected_class,expected_value", [ - ("'hey'.encode()", astroid.Const, b""), - ("b'hey'.decode()", astroid.Const, ""), - ("'hey'.encode().decode()", astroid.Const, ""), + ("'hey'.encode()", nodes.Const, b""), + ("b'hey'.decode()", nodes.Const, ""), + ("'hey'.encode().decode()", nodes.Const, ""), ], ) def test_str_and_bytes(code, expected_class, expected_value): diff --git a/tests/brain/test_enum.py b/tests/brain/test_enum.py index 127b3ed70..4e3e732af 100644 --- a/tests/brain/test_enum.py +++ b/tests/brain/test_enum.py @@ -38,7 +38,7 @@ def mymethod(self, x): self.assertIn("builtins.property", prop.decoratornames()) meth = one.getattr("mymethod")[0] - self.assertIsInstance(meth, astroid.FunctionDef) + self.assertIsInstance(meth, nodes.FunctionDef) def test_looks_like_enum_false_positive(self) -> None: # Test that a class named Enumeration is not considered a builtin enum. @@ -70,7 +70,7 @@ class Color(Enum): assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) - self.assertIsInstance(inferred[0], astroid.Const) + self.assertIsInstance(inferred[0], nodes.Const) self.assertEqual(inferred[0].value, 1) def test_ignores_with_nodes_from_body_of_enum(self) -> None: @@ -169,7 +169,7 @@ def test_enum_func_form_subscriptable(self) -> None: self.assertIsInstance(instance, astroid.Instance) inferred = next(name.infer()) - self.assertIsInstance(inferred, astroid.Const) + self.assertIsInstance(inferred, nodes.Const) def test_enum_func_form_has_dunder_members(self) -> None: instance = builder.extract_node( @@ -181,7 +181,7 @@ def test_enum_func_form_has_dunder_members(self) -> None: """ ) instance = next(instance.infer()) - self.assertIsInstance(instance, astroid.Const) + self.assertIsInstance(instance, nodes.Const) self.assertIsInstance(instance.value, str) def test_infer_enum_value_as_the_right_type(self) -> None: @@ -197,13 +197,13 @@ class A(Enum): ) inferred_string = string_value.inferred() assert any( - isinstance(elem, astroid.Const) and elem.value == "a" + isinstance(elem, nodes.Const) and elem.value == "a" for elem in inferred_string ) inferred_int = int_value.inferred() assert any( - isinstance(elem, astroid.Const) and elem.value == 1 for elem in inferred_int + isinstance(elem, nodes.Const) and elem.value == 1 for elem in inferred_int ) def test_mingled_single_and_double_quotes_does_not_crash(self) -> None: @@ -247,7 +247,7 @@ class Commands(IntEnum): """ ) inferred = next(node.infer()) - assert isinstance(inferred, astroid.ClassDef) + assert isinstance(inferred, nodes.ClassDef) def test_enum_tuple_list_values(self) -> None: tuple_node, list_node = builder.extract_node( @@ -263,8 +263,8 @@ class MyEnum(enum.Enum): ) inferred_tuple_node = next(tuple_node.infer()) inferred_list_node = next(list_node.infer()) - assert isinstance(inferred_tuple_node, astroid.Tuple) - assert isinstance(inferred_list_node, astroid.List) + assert isinstance(inferred_tuple_node, nodes.Tuple) + assert isinstance(inferred_list_node, nodes.List) assert inferred_tuple_node.as_string() == "(1, 2)" assert inferred_list_node.as_string() == "[2, 4]" @@ -361,7 +361,7 @@ class Color(EnumSubclass): assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) - self.assertIsInstance(inferred[0], astroid.Const) + self.assertIsInstance(inferred[0], nodes.Const) self.assertEqual(inferred[0].value, "red") def test_enum_subclass_member_value(self) -> None: @@ -381,7 +381,7 @@ class Color(EnumSubclass): assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) - self.assertIsInstance(inferred[0], astroid.Const) + self.assertIsInstance(inferred[0], nodes.Const) self.assertEqual(inferred[0].value, 1) def test_enum_subclass_member_method(self) -> None: @@ -403,7 +403,7 @@ class Color(EnumSubclass): assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) - self.assertIsInstance(inferred[0], astroid.Const) + self.assertIsInstance(inferred[0], nodes.Const) self.assertEqual(inferred[0].value, "red") def test_enum_subclass_different_modules(self) -> None: @@ -430,7 +430,7 @@ class Color(EnumSubclass): assert isinstance(ast_node, nodes.NodeNG) inferred = ast_node.inferred() self.assertEqual(len(inferred), 1) - self.assertIsInstance(inferred[0], astroid.Const) + self.assertIsInstance(inferred[0], nodes.Const) self.assertEqual(inferred[0].value, 1) def test_members_member_ignored(self) -> None: @@ -445,7 +445,7 @@ class Animal(Enum): ) inferred = next(ast_node.infer()) - self.assertIsInstance(inferred, astroid.Dict) + self.assertIsInstance(inferred, nodes.Dict) self.assertTrue(inferred.locals) def test_enum_as_renamed_import(self) -> None: diff --git a/tests/brain/test_named_tuple.py b/tests/brain/test_named_tuple.py index 40a96c7ce..c26585fb6 100644 --- a/tests/brain/test_named_tuple.py +++ b/tests/brain/test_named_tuple.py @@ -6,7 +6,6 @@ import unittest -import astroid from astroid import builder, nodes, util from astroid.exceptions import AttributeInferenceError @@ -184,8 +183,8 @@ def test_namedtuple_bases_are_actually_names_not_nodes(self) -> None: """ ) inferred = next(node.infer()) - self.assertIsInstance(inferred, astroid.ClassDef) - self.assertIsInstance(inferred.bases[0], astroid.Name) + self.assertIsInstance(inferred, nodes.ClassDef) + self.assertIsInstance(inferred.bases[0], nodes.Name) self.assertEqual(inferred.bases[0].name, "tuple") def test_invalid_label_does_not_crash_inference(self) -> None: @@ -196,7 +195,7 @@ def test_invalid_label_does_not_crash_inference(self) -> None: """ node = builder.extract_node(code) inferred = next(node.infer()) - assert isinstance(inferred, astroid.ClassDef) + assert isinstance(inferred, nodes.ClassDef) assert "b" not in inferred.locals assert "c" not in inferred.locals diff --git a/tests/test_group_exceptions.py b/tests/test_group_exceptions.py index 31b013e59..661a824e8 100644 --- a/tests/test_group_exceptions.py +++ b/tests/test_group_exceptions.py @@ -6,20 +6,13 @@ import pytest from astroid import ( - AssignName, - ExceptHandler, - For, - List, - Name, - Try, - Tuple, Uninferable, bases, extract_node, + nodes, ) from astroid.const import PY311_PLUS from astroid.context import InferenceContext -from astroid.nodes import Expr, Raise, TryStar @pytest.mark.skipif(not PY311_PLUS, reason="Exception group introduced in Python 3.11") @@ -35,7 +28,7 @@ def test_group_exceptions_exceptions() -> None: ) inferred = node.inferred()[0] - assert isinstance(inferred, Tuple) + assert isinstance(inferred, nodes.Tuple) @pytest.mark.skipif(not PY311_PLUS, reason="Requires Python 3.11 or higher") @@ -53,20 +46,20 @@ def test_group_exceptions() -> None: print("Handling TypeError")""" ) ) - assert isinstance(node, Try) + assert isinstance(node, nodes.Try) handler = node.handlers[0] assert node.block_range(lineno=1) == (1, 9) assert node.block_range(lineno=2) == (2, 2) assert node.block_range(lineno=5) == (5, 9) - assert isinstance(handler, ExceptHandler) + assert isinstance(handler, nodes.ExceptHandler) assert handler.type.name == "ExceptionGroup" children = list(handler.get_children()) assert len(children) == 3 exception_group, short_name, for_loop = children - assert isinstance(exception_group, Name) + assert isinstance(exception_group, nodes.Name) assert exception_group.block_range(1) == (1, 4) - assert isinstance(short_name, AssignName) - assert isinstance(for_loop, For) + assert isinstance(short_name, nodes.AssignName) + assert isinstance(for_loop, nodes.For) @pytest.mark.skipif(not PY311_PLUS, reason="Requires Python 3.11 or higher") @@ -85,9 +78,9 @@ def test_star_exceptions() -> None: sys.exit(0)""" ) node = extract_node(code) - assert isinstance(node, TryStar) + assert isinstance(node, nodes.TryStar) assert node.as_string() == code.replace('"', "'").strip() - assert isinstance(node.body[0], Raise) + assert isinstance(node.body[0], nodes.Raise) assert node.block_range(1) == (1, 11) assert node.block_range(2) == (2, 2) assert node.block_range(3) == (3, 3) @@ -101,13 +94,13 @@ def test_star_exceptions() -> None: assert node.block_range(11) == (11, 11) assert node.handlers handler = node.handlers[0] - assert isinstance(handler, ExceptHandler) + assert isinstance(handler, nodes.ExceptHandler) assert handler.type.name == "ValueError" orelse = node.orelse[0] - assert isinstance(orelse, Expr) + assert isinstance(orelse, nodes.Expr) assert orelse.value.args[0].value == 127 final = node.finalbody[0] - assert isinstance(final, Expr) + assert isinstance(final, nodes.Expr) assert final.value.args[0].value == 0 @@ -144,15 +137,15 @@ def test_star_exceptions_infer_exceptions() -> None: sys.exit(0)""" ) node = extract_node(code) - assert isinstance(node, TryStar) + assert isinstance(node, nodes.TryStar) inferred_ve = next(node.handlers[0].statement().name.infer()) assert inferred_ve.name == "ExceptionGroup" - assert isinstance(inferred_ve.getattr("exceptions")[0], List) + assert isinstance(inferred_ve.getattr("exceptions")[0], nodes.List) assert ( inferred_ve.getattr("exceptions")[0].elts[0].pytype() == "builtins.ValueError" ) inferred_te = next(node.handlers[1].statement().name.infer()) assert inferred_te.name == "ExceptionGroup" - assert isinstance(inferred_te.getattr("exceptions")[0], List) + assert isinstance(inferred_te.getattr("exceptions")[0], nodes.List) assert inferred_te.getattr("exceptions")[0].elts[0].pytype() == "builtins.TypeError" diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 12168cf64..4df145bab 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -12,7 +12,6 @@ from astroid.const import IS_PYPY from astroid.exceptions import _NonDeducibleTypeHierarchy from astroid.nodes.node_classes import UNATTACHED_UNKNOWN -from astroid.nodes.scoped_nodes import ClassDef class TestHelpers(unittest.TestCase): @@ -23,14 +22,14 @@ def setUp(self) -> None: self.builtins = astroid_manager.astroid_cache[builtins_name] self.manager = manager.AstroidManager() - def _extract(self, obj_name: str) -> ClassDef: + def _extract(self, obj_name: str) -> nodes.ClassDef: return self.builtins.getattr(obj_name)[0] - def _build_custom_builtin(self, obj_name: str) -> ClassDef: + def _build_custom_builtin(self, obj_name: str) -> nodes.ClassDef: proxy = raw_building.build_class(obj_name, self.builtins) return proxy - def assert_classes_equal(self, cls: ClassDef, other: ClassDef) -> None: + def assert_classes_equal(self, cls: nodes.ClassDef, other: nodes.ClassDef) -> None: self.assertEqual(cls.name, other.name) self.assertEqual(cls.parent, other.parent) self.assertEqual(cls.qname(), other.qname()) diff --git a/tests/test_inference.py b/tests/test_inference.py index e4cd0a7b0..bf41e8cf5 100644 --- a/tests/test_inference.py +++ b/tests/test_inference.py @@ -19,9 +19,6 @@ import pytest from astroid import ( - Assign, - Const, - Slice, Uninferable, arguments, manager, @@ -71,7 +68,7 @@ def infer_default(self: Any, *args: InferenceContext) -> None: raise InferenceError infer_default = decoratorsmod.path_wrapper(infer_default) - infer_end = decoratorsmod.path_wrapper(Slice._infer) + infer_end = decoratorsmod.path_wrapper(nodes.Slice._infer) with self.assertRaises(InferenceError): next(infer_default(1)) self.assertEqual(next(infer_end(1)), 1) @@ -665,7 +662,7 @@ def test_fstring_inference(self) -> None: inferred = node.inferred() self.assertEqual(len(inferred), 1) value_node = inferred[0] - self.assertIsInstance(value_node, Const) + self.assertIsInstance(value_node, nodes.Const) self.assertEqual(value_node.value, "Hello John!") def test_float_complex_ambiguity(self) -> None: @@ -5571,7 +5568,7 @@ def test_formatted_fstring_inference(code, result) -> None: if result is None: assert value_node is util.Uninferable else: - assert isinstance(value_node, Const) + assert isinstance(value_node, nodes.Const) assert value_node.value == result @@ -6185,7 +6182,7 @@ def test(self): """ ) inferred = next(node.infer()) - assert isinstance(inferred, Slice) + assert isinstance(inferred, nodes.Slice) def test_exception_lookup_last_except_handler_wins() -> None: @@ -7422,13 +7419,13 @@ class Cls: def test_joined_str_returns_string(source, expected) -> None: """Regression test for https://github.com/pylint-dev/pylint/issues/9947.""" node = extract_node(source) - assert isinstance(node, Assign) + assert isinstance(node, nodes.Assign) target = node.targets[0] assert target inferred = list(target.inferred()) assert len(inferred) == 1 if expected: - assert isinstance(inferred[0], Const) + assert isinstance(inferred[0], nodes.Const) inferred[0].value.startswith(expected) else: assert inferred[0] is Uninferable diff --git a/tests/test_manager.py b/tests/test_manager.py index 641fafdf5..e420e6b15 100644 --- a/tests/test_manager.py +++ b/tests/test_manager.py @@ -15,7 +15,7 @@ import pytest import astroid -from astroid import manager, test_utils +from astroid import manager, nodes, test_utils from astroid.const import IS_JYTHON, IS_PYPY, PY312_PLUS from astroid.exceptions import ( AstroidBuildingError, @@ -107,7 +107,7 @@ def _test_ast_from_old_namespace_package_protocol(self, root: str) -> None: try: for name in ("foo", "bar", "baz"): module = self.manager.ast_from_module_name("package." + name) - self.assertIsInstance(module, astroid.Module) + self.assertIsInstance(module, nodes.Module) finally: sys.path = origpath @@ -181,10 +181,10 @@ def test_implicit_namespace_package(self) -> None: try: module = self.manager.ast_from_module_name("namespace_pep_420.module") - self.assertIsInstance(module, astroid.Module) + self.assertIsInstance(module, nodes.Module) self.assertEqual(module.name, "namespace_pep_420.module") var = next(module.igetattr("var")) - self.assertIsInstance(var, astroid.Const) + self.assertIsInstance(var, nodes.Const) self.assertEqual(var.value, 42) finally: for _ in range(2): @@ -202,7 +202,7 @@ def test_namespace_package_pth_support(self) -> None: module = self.manager.ast_from_module_name("foogle.fax") submodule = next(module.igetattr("a")) value = next(submodule.igetattr("x")) - self.assertIsInstance(value, astroid.Const) + self.assertIsInstance(value, nodes.Const) with self.assertRaises(AstroidImportError): self.manager.ast_from_module_name("foogle.moogle") finally: diff --git a/tests/test_nodes.py b/tests/test_nodes.py index 9ed2022fb..6ff4e81ad 100644 --- a/tests/test_nodes.py +++ b/tests/test_nodes.py @@ -43,22 +43,8 @@ AttributeInferenceError, StatementMissing, ) -from astroid.nodes.node_classes import ( - UNATTACHED_UNKNOWN, - AssignAttr, - AssignName, - Attribute, - Call, - ImportFrom, - Tuple, -) -from astroid.nodes.scoped_nodes import ( - SYNTHETIC_ROOT, - ClassDef, - FunctionDef, - GeneratorExp, - Module, -) +from astroid.nodes.node_classes import UNATTACHED_UNKNOWN +from astroid.nodes.scoped_nodes import SYNTHETIC_ROOT from tests.testdata.python3.recursion_error import LONG_CHAINED_METHOD_CALL from . import resources @@ -68,7 +54,7 @@ class AsStringTest(resources.SysPathSetup, unittest.TestCase): def test_tuple_as_string(self) -> None: - def build(string: str) -> Tuple: + def build(string: str) -> nodes.Tuple: return abuilder.string_build(string).body[0].value self.assertEqual(build("1,").as_string(), "(1, )") @@ -411,7 +397,7 @@ class _NodeTest(unittest.TestCase): CODE = "" @property - def astroid(self) -> Module: + def astroid(self) -> nodes.Module: try: return self.__class__.__dict__["CODE_Astroid"] except KeyError: @@ -606,9 +592,7 @@ def test_as_string(self) -> None: ast = self.module["modutils"] self.assertEqual(ast.as_string(), "from astroid import modutils") ast = self.module["NameNode"] - self.assertEqual( - ast.as_string(), "from astroid.nodes.node_classes import Name as NameNode" - ) + self.assertEqual(ast.as_string(), "from astroid.nodes import Name as NameNode") ast = self.module["os"] self.assertEqual(ast.as_string(), "import os.path") code = """from . import here @@ -908,8 +892,8 @@ def test_complex(self) -> None: assign = builder.extract_node(code) self.assertIsInstance(assign, nodes.AnnAssign) self.assertEqual(assign.target.name, "test") - self.assertIsInstance(assign.annotation, astroid.Subscript) - self.assertIsInstance(assign.value, astroid.Dict) + self.assertIsInstance(assign.annotation, nodes.Subscript) + self.assertIsInstance(assign.value, nodes.Dict) def test_as_string(self) -> None: code = textwrap.dedent( @@ -1277,30 +1261,30 @@ class AliasesTest(unittest.TestCase): def setUp(self) -> None: self.transformer = transforms.TransformVisitor() - def parse_transform(self, code: str) -> Module: + def parse_transform(self, code: str) -> nodes.Module: module = parse(code, apply_transforms=False) return self.transformer.visit(module) def test_aliases(self) -> None: - def test_from(node: ImportFrom) -> ImportFrom: + def test_from(node: nodes.ImportFrom) -> nodes.ImportFrom: node.names = [*node.names, ("absolute_import", None)] return node - def test_class(node: ClassDef) -> ClassDef: + def test_class(node: nodes.ClassDef) -> nodes.ClassDef: node.name = "Bar" return node - def test_function(node: FunctionDef) -> FunctionDef: + def test_function(node: nodes.FunctionDef) -> nodes.FunctionDef: node.name = "another_test" return node - def test_callfunc(node: Call) -> Call | None: + def test_callfunc(node: nodes.Call) -> nodes.Call | None: if node.func.name == "Foo": node.func.name = "Bar" return node return None - def test_assname(node: AssignName) -> AssignName | None: + def test_assname(node: nodes.AssignName) -> nodes.AssignName | None: if node.name == "foo": return nodes.AssignName( "bar", @@ -1312,19 +1296,19 @@ def test_assname(node: AssignName) -> AssignName | None: ) return None - def test_assattr(node: AssignAttr) -> AssignAttr: + def test_assattr(node: nodes.AssignAttr) -> nodes.AssignAttr: if node.attrname == "a": node.attrname = "b" return node return None - def test_getattr(node: Attribute) -> Attribute: + def test_getattr(node: nodes.Attribute) -> nodes.Attribute: if node.attrname == "a": node.attrname = "b" return node return None - def test_genexpr(node: GeneratorExp) -> GeneratorExp: + def test_genexpr(node: nodes.GeneratorExp) -> nodes.GeneratorExp: if node.elt.value == 1: node.elt = nodes.Const(2, node.lineno, node.col_offset, node.parent) return node @@ -1533,7 +1517,7 @@ def test_type_comments_with() -> None: ) node = module.body[0] ignored_node = module.body[1] - assert isinstance(node.type_annotation, astroid.Name) + assert isinstance(node.type_annotation, nodes.Name) assert ignored_node.type_annotation is None @@ -1549,7 +1533,7 @@ def test_type_comments_for() -> None: ) node = module.body[0] ignored_node = module.body[1] - assert isinstance(node.type_annotation, astroid.Subscript) + assert isinstance(node.type_annotation, nodes.Subscript) assert node.type_annotation.as_string() == "List[int]" assert ignored_node.type_annotation is None @@ -1564,7 +1548,7 @@ def test_type_coments_assign() -> None: ) node = module.body[0] ignored_node = module.body[1] - assert isinstance(node.type_annotation, astroid.Subscript) + assert isinstance(node.type_annotation, nodes.Subscript) assert node.type_annotation.as_string() == "List[int]" assert ignored_node.type_annotation is None @@ -1620,9 +1604,9 @@ def func2(): """ ) expected_annotations = [ - (["int"], astroid.Name, "str"), - (["int", "int", "int"], astroid.Tuple, "(str, str)"), - (["int", "int", "str", "List[int]"], astroid.Subscript, "List[int]"), + (["int"], nodes.Name, "str"), + (["int", "int", "int"], nodes.Tuple, "(str, str)"), + (["int", "int", "str", "List[int]"], nodes.Subscript, "List[int]"), ] for node, (expected_args, expected_returns_type, expected_returns_string) in zip( module.body, expected_annotations @@ -1667,7 +1651,7 @@ def func2( ] for node, expected_args in zip(module.body, expected_annotations): assert len(node.type_comment_args) == 1 - assert isinstance(node.type_comment_args[0], astroid.Const) + assert isinstance(node.type_comment_args[0], nodes.Const) assert node.type_comment_args[0].value == Ellipsis assert len(node.args.type_comment_args) == len(expected_args) for expected_arg, actual_arg in zip(expected_args, node.args.type_comment_args): @@ -1696,7 +1680,7 @@ def f_arg_comment( ] for node, expected_types in zip(module.body, expected_annotations): assert len(node.type_comment_args) == 1 - assert isinstance(node.type_comment_args[0], astroid.Const) + assert isinstance(node.type_comment_args[0], nodes.Const) assert node.type_comment_args[0].value == Ellipsis type_comments = [ node.args.type_comment_posonlyargs, @@ -1917,15 +1901,15 @@ def g( assert len(type_comments) == 1 type_comment = type_comments[0] - assert isinstance(type_comment, astroid.Attribute) - assert isinstance(type_comment.parent, astroid.Expr) - assert isinstance(type_comment.parent.parent, astroid.Arguments) + assert isinstance(type_comment, nodes.Attribute) + assert isinstance(type_comment.parent, nodes.Expr) + assert isinstance(type_comment.parent.parent, nodes.Arguments) def test_const_itered() -> None: code = 'a = "string"' node = astroid.extract_node(code).value - assert isinstance(node, astroid.Const) + assert isinstance(node, nodes.Const) itered = node.itered() assert len(itered) == 6 assert [elem.value for elem in itered] == list("string") @@ -1994,12 +1978,12 @@ def test_match_simple(): assert isinstance(case0.pattern, nodes.MatchValue) assert ( - isinstance(case0.pattern.value, astroid.Const) + isinstance(case0.pattern.value, nodes.Const) and case0.pattern.value.value == 200 ) assert list(case0.pattern.get_children()) == [case0.pattern.value] assert case0.guard is None - assert isinstance(case0.body[0], astroid.Pass) + assert isinstance(case0.body[0], nodes.Pass) assert list(case0.get_children()) == [case0.pattern, case0.body[0]] assert isinstance(case1.pattern, nodes.MatchOr) diff --git a/tests/test_object_model.py b/tests/test_object_model.py index 9ad4d39a9..f3015db9c 100644 --- a/tests/test_object_model.py +++ b/tests/test_object_model.py @@ -38,21 +38,21 @@ def __init__(self): ) assert isinstance(ast_nodes, list) cls = next(ast_nodes[0].infer()) - self.assertIsInstance(cls, astroid.ClassDef) + self.assertIsInstance(cls, nodes.ClassDef) self.assertEqual(cls.name, "A") module = next(ast_nodes[1].infer()) - self.assertIsInstance(module, astroid.Const) + self.assertIsInstance(module, nodes.Const) self.assertEqual(module.value, "fake_module") doc = next(ast_nodes[2].infer()) - self.assertIsInstance(doc, astroid.Const) + self.assertIsInstance(doc, nodes.Const) self.assertEqual(doc.value, "test") dunder_dict = next(ast_nodes[3].infer()) - self.assertIsInstance(dunder_dict, astroid.Dict) - attr = next(dunder_dict.getitem(astroid.Const("a")).infer()) - self.assertIsInstance(attr, astroid.Const) + self.assertIsInstance(dunder_dict, nodes.Dict) + attr = next(dunder_dict.getitem(nodes.Const("a")).infer()) + self.assertIsInstance(attr, nodes.Const) self.assertEqual(attr.value, 42) @pytest.mark.xfail(reason="Instance lookup cannot override object model") @@ -68,7 +68,7 @@ def __dict__(self): """ ) inferred = next(ast_node.infer()) - self.assertIsInstance(inferred, astroid.List) + self.assertIsInstance(inferred, nodes.List) self.assertEqual(inferred.elts, []) @@ -85,7 +85,7 @@ def test(self): pass ) assert isinstance(ast_nodes, list) func = next(ast_nodes[0].infer()) - self.assertIsInstance(func, astroid.FunctionDef) + self.assertIsInstance(func, nodes.FunctionDef) self.assertEqual(func.name, "test") self_ = next(ast_nodes[1].infer()) @@ -110,17 +110,17 @@ def test(self): pass ) assert isinstance(ast_nodes, list) cls = next(ast_nodes[0].infer()) - self.assertIsInstance(cls, astroid.ClassDef) + self.assertIsInstance(cls, nodes.ClassDef) unbound_name = "function" self.assertEqual(cls.name, unbound_name) func = next(ast_nodes[1].infer()) - self.assertIsInstance(func, astroid.FunctionDef) + self.assertIsInstance(func, nodes.FunctionDef) self.assertEqual(func.name, "test") self_ = next(ast_nodes[2].infer()) - self.assertIsInstance(self_, astroid.Const) + self.assertIsInstance(self_, nodes.Const) self.assertIsNone(self_.value) self.assertEqual(cls.name, next(ast_nodes[3].infer()).name) @@ -138,7 +138,7 @@ class A: """ ) inferred = next(ast_node.infer()) - self.assertIsInstance(inferred, astroid.Const) + self.assertIsInstance(inferred, nodes.Const) self.assertEqual(inferred.value, "first") def test_class_model_correct_mro_subclasses_proxied(self) -> None: @@ -153,8 +153,8 @@ class A(object): for node in ast_nodes: inferred = next(node.infer()) self.assertIsInstance(inferred, astroid.BoundMethod) - self.assertIsInstance(inferred._proxied, astroid.FunctionDef) - self.assertIsInstance(inferred.bound, astroid.ClassDef) + self.assertIsInstance(inferred._proxied, nodes.FunctionDef) + self.assertIsInstance(inferred.bound, nodes.ClassDef) self.assertEqual(inferred.bound.name, "type") def test_class_model(self) -> None: @@ -181,41 +181,41 @@ class C(A): pass ) assert isinstance(ast_nodes, list) module = next(ast_nodes[0].infer()) - self.assertIsInstance(module, astroid.Const) + self.assertIsInstance(module, nodes.Const) self.assertEqual(module.value, "fake_module") name = next(ast_nodes[1].infer()) - self.assertIsInstance(name, astroid.Const) + self.assertIsInstance(name, nodes.Const) self.assertEqual(name.value, "A") qualname = next(ast_nodes[2].infer()) - self.assertIsInstance(qualname, astroid.Const) + self.assertIsInstance(qualname, nodes.Const) self.assertEqual(qualname.value, "fake_module.A") doc = next(ast_nodes[3].infer()) - self.assertIsInstance(doc, astroid.Const) + self.assertIsInstance(doc, nodes.Const) self.assertEqual(doc.value, "test") mro = next(ast_nodes[4].infer()) - self.assertIsInstance(mro, astroid.Tuple) + self.assertIsInstance(mro, nodes.Tuple) self.assertEqual([cls.name for cls in mro.elts], ["A", "object"]) called_mro = next(ast_nodes[5].infer()) self.assertEqual(called_mro.elts, mro.elts) base_nodes = next(ast_nodes[6].infer()) - self.assertIsInstance(base_nodes, astroid.Tuple) + self.assertIsInstance(base_nodes, nodes.Tuple) self.assertEqual([cls.name for cls in base_nodes.elts], ["object"]) cls = next(ast_nodes[7].infer()) - self.assertIsInstance(cls, astroid.ClassDef) + self.assertIsInstance(cls, nodes.ClassDef) self.assertEqual(cls.name, "type") cls_dict = next(ast_nodes[8].infer()) - self.assertIsInstance(cls_dict, astroid.Dict) + self.assertIsInstance(cls_dict, nodes.Dict) subclasses = next(ast_nodes[9].infer()) - self.assertIsInstance(subclasses, astroid.List) + self.assertIsInstance(subclasses, nodes.List) self.assertEqual([cls.name for cls in subclasses.elts], ["B", "C"]) @@ -227,7 +227,7 @@ def test_priority_to_local_defined_values(self) -> None: """ ) file_value = next(ast_node.igetattr("__file__")) - self.assertIsInstance(file_value, astroid.Const) + self.assertIsInstance(file_value, nodes.Const) self.assertEqual(file_value.value, "mine") def test__path__not_a_package(self) -> None: @@ -278,20 +278,20 @@ def test_module_model(self) -> None: ) assert isinstance(ast_nodes, list) path = next(ast_nodes[0].infer()) - self.assertIsInstance(path, astroid.List) - self.assertIsInstance(path.elts[0], astroid.Const) + self.assertIsInstance(path, nodes.List) + self.assertIsInstance(path.elts[0], nodes.Const) self.assertEqual(path.elts[0].value, xml.__path__[0]) name = next(ast_nodes[1].infer()) - self.assertIsInstance(name, astroid.Const) + self.assertIsInstance(name, nodes.Const) self.assertEqual(name.value, "xml") doc = next(ast_nodes[2].infer()) - self.assertIsInstance(doc, astroid.Const) + self.assertIsInstance(doc, nodes.Const) self.assertEqual(doc.value, xml.__doc__) file_ = next(ast_nodes[3].infer()) - self.assertIsInstance(file_, astroid.Const) + self.assertIsInstance(file_, nodes.Const) self.assertEqual(file_.value, xml.__file__.replace(".pyc", ".py")) for ast_node in ast_nodes[4:7]: @@ -299,11 +299,11 @@ def test_module_model(self) -> None: self.assertIs(inferred, astroid.Uninferable) package = next(ast_nodes[7].infer()) - self.assertIsInstance(package, astroid.Const) + self.assertIsInstance(package, nodes.Const) self.assertEqual(package.value, "xml") dict_ = next(ast_nodes[8].infer()) - self.assertIsInstance(dict_, astroid.Dict) + self.assertIsInstance(dict_, nodes.Dict) init_ = next(ast_nodes[9].infer()) assert isinstance(init_, bases.BoundMethod) @@ -346,7 +346,7 @@ def test(self): return 42 self.assertIsInstance(bound, astroid.BoundMethod) self.assertEqual(bound._proxied._proxied.name, "test") result = next(result.infer()) - self.assertIsInstance(result, astroid.Const) + self.assertIsInstance(result, nodes.Const) self.assertEqual(result.value, 42) def test___get__has_extra_params_defined(self) -> None: @@ -386,7 +386,7 @@ def test(self): return self.x """ ) result = next(result.infer()) - self.assertIsInstance(result, astroid.Const) + self.assertIsInstance(result, nodes.Const) self.assertEqual(result.value, 42) def test_descriptors_binding_invalid(self) -> None: @@ -464,30 +464,30 @@ def func(a=1, b=2): ) assert isinstance(ast_nodes, list) name = next(ast_nodes[0].infer()) - self.assertIsInstance(name, astroid.Const) + self.assertIsInstance(name, nodes.Const) self.assertEqual(name.value, "func") doc = next(ast_nodes[1].infer()) - self.assertIsInstance(doc, astroid.Const) + self.assertIsInstance(doc, nodes.Const) self.assertEqual(doc.value, "test") qualname = next(ast_nodes[2].infer()) - self.assertIsInstance(qualname, astroid.Const) + self.assertIsInstance(qualname, nodes.Const) self.assertEqual(qualname.value, "fake_module.func") module = next(ast_nodes[3].infer()) - self.assertIsInstance(module, astroid.Const) + self.assertIsInstance(module, nodes.Const) self.assertEqual(module.value, "fake_module") defaults = next(ast_nodes[4].infer()) - self.assertIsInstance(defaults, astroid.Tuple) + self.assertIsInstance(defaults, nodes.Tuple) self.assertEqual([default.value for default in defaults.elts], [1, 2]) dict_ = next(ast_nodes[5].infer()) - self.assertIsInstance(dict_, astroid.Dict) + self.assertIsInstance(dict_, nodes.Dict) globals_ = next(ast_nodes[6].infer()) - self.assertIsInstance(globals_, astroid.Dict) + self.assertIsInstance(globals_, nodes.Dict) for ast_node in ast_nodes[7:9]: self.assertIs(next(ast_node.infer()), astroid.Uninferable) @@ -529,7 +529,7 @@ def test(): pass """ ) annotations = next(ast_node.infer()) - self.assertIsInstance(annotations, astroid.Dict) + self.assertIsInstance(annotations, nodes.Dict) self.assertEqual(len(annotations.items), 0) def test_builtin_dunder_init_does_not_crash_when_accessing_annotations( @@ -544,7 +544,7 @@ def class_method(cls): """ ) inferred = next(ast_node.infer()) - self.assertIsInstance(inferred, astroid.Dict) + self.assertIsInstance(inferred, nodes.Dict) self.assertEqual(len(inferred.items), 0) def test_annotations_kwdefaults(self) -> None: @@ -556,20 +556,18 @@ def test(a: 1, *args: 2, f:4='lala', **kwarg:3)->2: pass """ ) annotations = next(ast_node[0].infer()) - self.assertIsInstance(annotations, astroid.Dict) - self.assertIsInstance( - annotations.getitem(astroid.Const("return")), astroid.Const - ) - self.assertEqual(annotations.getitem(astroid.Const("return")).value, 2) - self.assertIsInstance(annotations.getitem(astroid.Const("a")), astroid.Const) - self.assertEqual(annotations.getitem(astroid.Const("a")).value, 1) - self.assertEqual(annotations.getitem(astroid.Const("args")).value, 2) - self.assertEqual(annotations.getitem(astroid.Const("kwarg")).value, 3) + self.assertIsInstance(annotations, nodes.Dict) + self.assertIsInstance(annotations.getitem(nodes.Const("return")), nodes.Const) + self.assertEqual(annotations.getitem(nodes.Const("return")).value, 2) + self.assertIsInstance(annotations.getitem(nodes.Const("a")), nodes.Const) + self.assertEqual(annotations.getitem(nodes.Const("a")).value, 1) + self.assertEqual(annotations.getitem(nodes.Const("args")).value, 2) + self.assertEqual(annotations.getitem(nodes.Const("kwarg")).value, 3) - self.assertEqual(annotations.getitem(astroid.Const("f")).value, 4) + self.assertEqual(annotations.getitem(nodes.Const("f")).value, 4) kwdefaults = next(ast_node[1].infer()) - self.assertIsInstance(kwdefaults, astroid.Dict) + self.assertIsInstance(kwdefaults, nodes.Dict) # self.assertEqual(kwdefaults.getitem('f').value, 'lala') def test_annotation_positional_only(self): @@ -580,12 +578,12 @@ def test(a: 1, b: 2, /, c: 3): pass """ ) annotations = next(ast_node.infer()) - self.assertIsInstance(annotations, astroid.Dict) + self.assertIsInstance(annotations, nodes.Dict) - self.assertIsInstance(annotations.getitem(astroid.Const("a")), astroid.Const) - self.assertEqual(annotations.getitem(astroid.Const("a")).value, 1) - self.assertEqual(annotations.getitem(astroid.Const("b")).value, 2) - self.assertEqual(annotations.getitem(astroid.Const("c")).value, 3) + self.assertIsInstance(annotations.getitem(nodes.Const("a")), nodes.Const) + self.assertEqual(annotations.getitem(nodes.Const("a")).value, 1) + self.assertEqual(annotations.getitem(nodes.Const("b")).value, 2) + self.assertEqual(annotations.getitem(nodes.Const("c")).value, 3) def test_is_not_lambda(self): ast_node = builder.extract_node("def func(): pass") @@ -657,11 +655,11 @@ def test(): self.assertEqual(doc.value, "a") gi_code = next(ast_nodes[2].infer()) - self.assertIsInstance(gi_code, astroid.ClassDef) + self.assertIsInstance(gi_code, nodes.ClassDef) self.assertEqual(gi_code.name, "gi_code") gi_frame = next(ast_nodes[3].infer()) - self.assertIsInstance(gi_frame, astroid.ClassDef) + self.assertIsInstance(gi_frame, nodes.ClassDef) self.assertEqual(gi_frame.name, "gi_frame") send = next(ast_nodes[4].infer()) @@ -690,7 +688,7 @@ def test_valueerror_py3() -> None: ) assert isinstance(ast_nodes, list) args = next(ast_nodes[0].infer()) - assert isinstance(args, astroid.Tuple) + assert isinstance(args, nodes.Tuple) tb = next(ast_nodes[1].infer()) # Python 3.11: If 'contextlib' is loaded, '__traceback__' # could be set inside '__exit__' method in @@ -717,7 +715,7 @@ def test_syntax_error(self) -> None: """ ) inferred = next(ast_node.infer()) - assert isinstance(inferred, astroid.Const) + assert isinstance(inferred, nodes.Const) @unittest.skipIf(HAS_SIX, "This test fails if the six library is installed") def test_oserror(self) -> None: @@ -734,7 +732,7 @@ def test_oserror(self) -> None: expected_values = ["", "", 0] for node, value in zip(ast_nodes, expected_values): inferred = next(node.infer()) - assert isinstance(inferred, astroid.Const) + assert isinstance(inferred, nodes.Const) assert inferred.value == value def test_unicodedecodeerror(self) -> None: @@ -746,7 +744,7 @@ def test_unicodedecodeerror(self) -> None: """ node = builder.extract_node(code) inferred = next(node.infer()) - assert isinstance(inferred, astroid.Const) + assert isinstance(inferred, nodes.Const) assert inferred.value == b"" def test_import_error(self) -> None: @@ -761,7 +759,7 @@ def test_import_error(self) -> None: ) for node in ast_nodes: inferred = next(node.infer()) - assert isinstance(inferred, astroid.Const) + assert isinstance(inferred, nodes.Const) assert inferred.value == "" def test_exception_instance_correctly_instantiated(self) -> None: @@ -776,14 +774,14 @@ def test_exception_instance_correctly_instantiated(self) -> None: inferred = next(ast_node.infer()) assert isinstance(inferred, astroid.Instance) cls = next(inferred.igetattr("__class__")) - assert isinstance(cls, astroid.ClassDef) + assert isinstance(cls, nodes.ClassDef) class DictObjectModelTest(unittest.TestCase): def test__class__(self) -> None: ast_node = builder.extract_node("{}.__class__") inferred = next(ast_node.infer()) - self.assertIsInstance(inferred, astroid.ClassDef) + self.assertIsInstance(inferred, nodes.ClassDef) self.assertEqual(inferred.name, "dict") def test_attributes_inferred_as_methods(self) -> None: @@ -851,7 +849,7 @@ def foo(): cache_clear = next(ast_nodes[0].infer()) assert isinstance(cache_clear, astroid.BoundMethod) wrapped = next(ast_nodes[1].infer()) - assert isinstance(wrapped, astroid.FunctionDef) + assert isinstance(wrapped, nodes.FunctionDef) assert wrapped.name == "foo" cache_info = next(ast_nodes[2].infer()) assert isinstance(cache_info, astroid.Instance) diff --git a/tests/test_protocols.py b/tests/test_protocols.py index 94b0656eb..bb2d939be 100644 --- a/tests/test_protocols.py +++ b/tests/test_protocols.py @@ -122,7 +122,7 @@ def test_assigned_stmts_starred_for(self) -> None: for1_starred = next(assign_stmts.nodes_of_class(nodes.Starred)) assigned = next(for1_starred.assigned_stmts()) - assert isinstance(assigned, astroid.List) + assert isinstance(assigned, nodes.List) assert assigned.as_string() == "[1, 2]" def _get_starred_stmts(self, code: str) -> list | UninferableBase: @@ -236,7 +236,7 @@ def transform(node: nodes.Assign) -> None: node.root().locals["__all__"] = [node.value] manager = astroid.MANAGER - with _add_transform(manager, astroid.Assign, transform): + with _add_transform(manager, nodes.Assign, transform): module = astroid.parse( """ __all__ = ['a'] diff --git a/tests/test_transforms.py b/tests/test_transforms.py index 87b26a586..04e02662a 100644 --- a/tests/test_transforms.py +++ b/tests/test_transforms.py @@ -16,8 +16,6 @@ from astroid.brain.brain_dataclasses import _looks_like_dataclass_field_call from astroid.const import IS_PYPY from astroid.manager import AstroidManager -from astroid.nodes.node_classes import Call, Compare, Const, Name -from astroid.nodes.scoped_nodes import FunctionDef, Module from tests.testdata.python3.recursion_error import LONG_CHAINED_METHOD_CALL @@ -39,12 +37,12 @@ class TestTransforms(unittest.TestCase): def setUp(self) -> None: self.transformer = transforms.TransformVisitor() - def parse_transform(self, code: str) -> Module: + def parse_transform(self, code: str) -> nodes.Module: module = parse(code, apply_transforms=False) return self.transformer.visit(module) def test_function_inlining_transform(self) -> None: - def transform_call(node: Call) -> Const: + def transform_call(node: nodes.Call) -> nodes.Const: # Let's do some function inlining inferred = next(node.infer()) return inferred @@ -65,14 +63,14 @@ def test(): return 42 def test_recursive_transforms_into_astroid_fields(self) -> None: # Test that the transformer walks properly the tree # by going recursively into the _astroid_fields per each node. - def transform_compare(node: Compare) -> Const: + def transform_compare(node: nodes.Compare) -> nodes.Const: # Let's check the values of the ops _, right = node.ops[0] # Assume they are Consts and they were transformed before # us. return nodes.const_factory(node.left.value < right.value) - def transform_name(node: Name) -> Const: + def transform_name(node: nodes.Name) -> nodes.Const: # Should be Consts return next(node.infer()) @@ -92,7 +90,7 @@ def transform_name(node: Name) -> Const: self.assertFalse(module.body[2].value.value) def test_transform_patches_locals(self) -> None: - def transform_function(node: FunctionDef) -> None: + def transform_function(node: nodes.FunctionDef) -> None: assign = nodes.Assign( parent=node, lineno=node.lineno, @@ -127,11 +125,11 @@ def test(): self.assertEqual(func.body[1].as_string(), "value = 42") def test_predicates(self) -> None: - def transform_call(node: Call) -> Const: + def transform_call(node: nodes.Call) -> nodes.Const: inferred = next(node.infer()) return inferred - def should_inline(node: Call) -> bool: + def should_inline(node: nodes.Call) -> bool: return node.func.name.startswith("inlineme") self.transformer.register_transform(nodes.Call, transform_call, should_inline) @@ -165,7 +163,7 @@ def test_transforms_are_separated(self) -> None: # on a partially constructed tree anymore, which was the # source of crashes in the past when certain inference rules # were used in a transform. - def transform_function(node: FunctionDef) -> Const: + def transform_function(node: nodes.FunctionDef) -> nodes.Const: if node.decorators: for decorator in node.decorators.nodes: inferred = next(decorator.infer()) @@ -201,7 +199,7 @@ def bala(self): def test_transforms_are_called_for_builtin_modules(self) -> None: # Test that transforms are called for builtin modules. - def transform_function(node: FunctionDef) -> FunctionDef: + def transform_function(node: nodes.FunctionDef) -> nodes.FunctionDef: name = nodes.AssignName( name="value", lineno=0, @@ -215,7 +213,7 @@ def transform_function(node: FunctionDef) -> FunctionDef: manager = MANAGER - def predicate(node: FunctionDef) -> bool: + def predicate(node: nodes.FunctionDef) -> bool: return node.root().name == "time" with add_transform(manager, nodes.FunctionDef, transform_function, predicate): @@ -271,7 +269,7 @@ def transform_class(cls): IS_PYPY, reason="Could not find a useful recursion limit on all versions" ) def test_transform_aborted_if_recursion_limited(self): - def transform_call(node: Call) -> Const: + def transform_call(node: nodes.Call) -> nodes.Const: return node self.transformer.register_transform( diff --git a/tests/testdata/python3/data/module.py b/tests/testdata/python3/data/module.py index fba4c9c77..98da5dd63 100644 --- a/tests/testdata/python3/data/module.py +++ b/tests/testdata/python3/data/module.py @@ -2,7 +2,7 @@ """ __revision__ = '$Id: module.py,v 1.2 2005-11-02 11:56:54 syt Exp $' -from astroid.nodes.node_classes import Name as NameNode +from astroid.nodes import Name as NameNode from astroid import modutils from astroid.utils import * import os.path diff --git a/tests/testdata/python3/data/module3.14.py b/tests/testdata/python3/data/module3.14.py index a29b14d89..e5af6b022 100644 --- a/tests/testdata/python3/data/module3.14.py +++ b/tests/testdata/python3/data/module3.14.py @@ -2,7 +2,7 @@ """ __revision__ = '$Id: module.py,v 1.2 2005-11-02 11:56:54 syt Exp $' -from astroid.nodes.node_classes import Name as NameNode +from astroid.nodes import Name as NameNode from astroid import modutils from astroid.utils import * import os.path