diff options
| author | Pierre Sassoulas <pierre.sassoulas@gmail.com> | 2021-06-26 09:56:19 +0200 |
|---|---|---|
| committer | Pierre Sassoulas <pierre.sassoulas@gmail.com> | 2021-08-05 21:48:42 +0200 |
| commit | da4471aa4c907a6ef364f0385ed69496a154efa5 (patch) | |
| tree | c7a9180922fcacdbe5f98edb452d899a64ea9e03 | |
| parent | dde5508ea6dba400c48db5bfafee7747bb59ae34 (diff) | |
| download | astroid-git-da4471aa4c907a6ef364f0385ed69496a154efa5.tar.gz | |
Create 'nodes' package, deprecate 'node_classes' and 'scoped_nodes'
Add deprecation warning and retro-compatibility for old API in
node_classes and scoped_nodes.
To be removed in 3.0.0.
| -rw-r--r-- | .pre-commit-config.yaml | 2 | ||||
| -rw-r--r-- | ChangeLog | 2 | ||||
| -rw-r--r-- | astroid/__init__.py | 103 | ||||
| -rw-r--r-- | astroid/node_classes.py | 5430 | ||||
| -rw-r--r-- | astroid/nodes/__init__.py | 214 | ||||
| -rw-r--r-- | astroid/nodes/node_classes.py | 5343 | ||||
| -rw-r--r-- | astroid/nodes/scoped_nodes.py | 3034 | ||||
| -rw-r--r-- | astroid/rebuilder.py | 2 | ||||
| -rw-r--r-- | astroid/scoped_nodes.py | 3056 | ||||
| -rw-r--r-- | tests/unittest_nodes.py | 4 |
10 files changed, 8812 insertions, 8378 deletions
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 340c40ab..934cb6d4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,7 +13,7 @@ repos: rev: v1.4 hooks: - id: autoflake - exclude: tests/testdata|astroid/__init__.py + exclude: tests/testdata|astroid/__init__.py|astroid/scoped_nodes.py|astroid/node_classes.py args: - --in-place - --remove-all-unused-imports @@ -6,6 +6,8 @@ What's New in astroid 2.7.0? ============================ Release date: TBA +* Import from ``astroid.node_classes`` and ``astroid.scoped_nodes`` has been deprecated in favor of + ``astroid.nodes``. Only the imports from ``astroid.nodes`` will work in astroid 3.0.0. What's New in astroid 2.6.7? ============================ diff --git a/astroid/__init__.py b/astroid/__init__.py index f4f8c49d..724dec07 100644 --- a/astroid/__init__.py +++ b/astroid/__init__.py @@ -50,6 +50,8 @@ from astroid.__pkginfo__ import __version__, version # isort: on +from astroid import node_classes # Deprecated, to remove later +from astroid import scoped_nodes # Deprecated, to remove later from astroid import inference, raw_building from astroid.astroid_manager import MANAGER from astroid.bases import BaseInstance, BoundMethod, Instance, UnboundMethod @@ -58,9 +60,104 @@ from astroid.builder import extract_node, parse from astroid.const import Context, Del, Load, Store from astroid.exceptions import * from astroid.inference_tip import _inference_tip_cached, inference_tip -from astroid.node_classes import are_exclusive, unpack_infer -from astroid.nodes import * # pylint: disable=redefined-builtin (Ellipsis) -from astroid.scoped_nodes import builtin_lookup + +# isort: off +# It's impossible to import from astroid.nodes with a wildcard, because +# there is a cyclic import that prevent creating an __all__ in astroid/nodes +# and we need astroid/scoped_nodes and astroid/node_classes to work. So +# importing with a wildcard would clash with astroid/nodes/scoped_nodes +# and astroid/nodes/node_classes. +from astroid.nodes import ( # pylint: disable=redefined-builtin (Ellipsis) + CONST_CLS, + AnnAssign, + Arguments, + Assert, + Assign, + AssignAttr, + AssignName, + AsyncFor, + AsyncFunctionDef, + AsyncWith, + Attribute, + AugAssign, + Await, + BinOp, + BoolOp, + Break, + Call, + ClassDef, + Compare, + Comprehension, + ComprehensionScope, + Const, + Continue, + Decorators, + DelAttr, + Delete, + DelName, + Dict, + DictComp, + DictUnpack, + Ellipsis, + EmptyNode, + EvaluatedObject, + ExceptHandler, + Expr, + ExtSlice, + For, + FormattedValue, + FunctionDef, + GeneratorExp, + Global, + If, + IfExp, + Import, + ImportFrom, + Index, + JoinedStr, + Keyword, + Lambda, + List, + ListComp, + Match, + MatchAs, + MatchCase, + MatchClass, + MatchMapping, + MatchOr, + MatchSequence, + MatchSingleton, + MatchStar, + MatchValue, + Module, + Name, + NamedExpr, + NodeNG, + Nonlocal, + Pass, + Raise, + Return, + Set, + SetComp, + Slice, + Starred, + Subscript, + TryExcept, + TryFinally, + Tuple, + UnaryOp, + Unknown, + While, + With, + Yield, + YieldFrom, + are_exclusive, + builtin_lookup, + unpack_infer, + function_to_method, +) + +# isort: on from astroid.util import Uninferable # load brain plugins diff --git a/astroid/node_classes.py b/astroid/node_classes.py index e087b91b..035adead 100644 --- a/astroid/node_classes.py +++ b/astroid/node_classes.py @@ -1,5343 +1,91 @@ -# Copyright (c) 2009-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> -# Copyright (c) 2010 Daniel Harding <dharding@gmail.com> -# Copyright (c) 2012 FELD Boris <lothiraldan@gmail.com> -# Copyright (c) 2013-2014 Google, Inc. -# Copyright (c) 2014-2021 Claudiu Popa <pcmanticore@gmail.com> -# Copyright (c) 2014 Eevee (Alex Munroe) <amunroe@yelp.com> -# Copyright (c) 2015-2016 Ceridwen <ceridwenv@gmail.com> -# Copyright (c) 2015 Florian Bruhin <me@the-compiler.org> -# Copyright (c) 2016-2017 Derek Gustafson <degustaf@gmail.com> -# Copyright (c) 2016 Jared Garst <jgarst@users.noreply.github.com> -# Copyright (c) 2016 Jakub Wilk <jwilk@jwilk.net> -# Copyright (c) 2016 Dave Baum <dbaum@google.com> -# Copyright (c) 2017-2020 Ashley Whetter <ashley@awhetter.co.uk> -# Copyright (c) 2017, 2019 Łukasz Rogalski <rogalski.91@gmail.com> -# Copyright (c) 2017 rr- <rr-@sakuya.pl> -# Copyright (c) 2018-2021 hippo91 <guillaume.peillex@gmail.com> -# Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com> -# Copyright (c) 2018 Nick Drozd <nicholasdrozd@gmail.com> -# Copyright (c) 2018 Ville Skyttä <ville.skytta@iki.fi> -# Copyright (c) 2018 brendanator <brendan.maginnis@gmail.com> -# Copyright (c) 2018 HoverHell <hoverhell@gmail.com> -# Copyright (c) 2019 kavins14 <kavin.singh@mail.utoronto.ca> -# Copyright (c) 2019 kavins14 <kavinsingh@hotmail.com> -# Copyright (c) 2020 Raphael Gaschignard <raphael@rtpg.co> -# Copyright (c) 2020 Bryce Guinta <bryce.guinta@protonmail.com> -# Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com> -# Copyright (c) 2021 David Liu <david@cs.toronto.edu> -# Copyright (c) 2021 Alphadelta14 <alpha@alphaservcomputing.solutions> -# Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com> -# Copyright (c) 2021 Andrew Haigh <hello@nelf.in> -# Copyright (c) 2021 Federico Bond <federicobond@gmail.com> - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE - -"""Module for some node classes. More nodes in scoped_nodes.py""" - -import abc -import itertools -import pprint -import sys -import typing -from functools import lru_cache -from functools import singledispatch as _singledispatch -from typing import Callable, ClassVar, Generator, Optional - -from astroid import as_string, bases -from astroid import context as contextmod -from astroid import decorators, mixins, util -from astroid.const import BUILTINS, Context -from astroid.exceptions import ( - AstroidError, - AstroidIndexError, - AstroidTypeError, - InferenceError, - NoDefault, - UseInferenceDefault, +# pylint: disable=unused-import + +import warnings + +from astroid.nodes.node_classes import ( # pylint: disable=redefined-builtin (Ellipsis) + CONST_CLS, + AnnAssign, + Arguments, + Assert, + Assign, + AssignAttr, + AssignName, + AsyncFor, + AsyncWith, + Attribute, + AugAssign, + Await, + BinOp, + BoolOp, + Break, + Call, + Compare, + Comprehension, + Const, + Continue, + Decorators, + DelAttr, + Delete, + DelName, + Dict, + DictUnpack, + Ellipsis, + EmptyNode, + EvaluatedObject, + ExceptHandler, + Expr, + ExtSlice, + For, + FormattedValue, + Global, + If, + IfExp, + Import, + ImportFrom, + Index, + JoinedStr, + Keyword, + List, + Match, + MatchAs, + MatchCase, + MatchClass, + MatchMapping, + MatchOr, + MatchSequence, + MatchSingleton, + MatchStar, + MatchValue, + Name, + NamedExpr, + NodeNG, + Nonlocal, + Pass, + Raise, + Return, + Set, + Slice, + Starred, + Subscript, + TryExcept, + TryFinally, + Tuple, + UnaryOp, + Unknown, + While, + With, + Yield, + YieldFrom, + _BaseContainer, + are_exclusive, + const_factory, + unpack_infer, ) -from astroid.manager import AstroidManager - -if sys.version_info >= (3, 8): - from typing import Literal -else: - from typing_extensions import Literal - - -def _is_const(value): - return isinstance(value, tuple(CONST_CLS)) - - -@decorators.raise_if_nothing_inferred -def unpack_infer(stmt, context=None): - """recursively generate nodes inferred by the given statement. - If the inferred value is a list or a tuple, recurse on the elements - """ - if isinstance(stmt, (List, Tuple)): - for elt in stmt.elts: - if elt is util.Uninferable: - yield elt - continue - yield from unpack_infer(elt, context) - return dict(node=stmt, context=context) - # if inferred is a final node, return it and stop - inferred = next(stmt.infer(context), util.Uninferable) - if inferred is stmt: - yield inferred - return dict(node=stmt, context=context) - # else, infer recursively, except Uninferable object that should be returned as is - for inferred in stmt.infer(context): - if inferred is util.Uninferable: - yield inferred - else: - yield from unpack_infer(inferred, context) - - return dict(node=stmt, context=context) - - -def are_exclusive(stmt1, stmt2, exceptions: Optional[typing.List[str]] = None) -> bool: - """return true if the two given statements are mutually exclusive - - `exceptions` may be a list of exception names. If specified, discard If - branches and check one of the statement is in an exception handler catching - one of the given exceptions. - - algorithm : - 1) index stmt1's parents - 2) climb among stmt2's parents until we find a common parent - 3) if the common parent is a If or TryExcept statement, look if nodes are - in exclusive branches - """ - # index stmt1's parents - stmt1_parents = {} - children = {} - node = stmt1.parent - previous = stmt1 - while node: - stmt1_parents[node] = 1 - children[node] = previous - previous = node - node = node.parent - # climb among stmt2's parents until we find a common parent - node = stmt2.parent - previous = stmt2 - while node: - if node in stmt1_parents: - # if the common parent is a If or TryExcept statement, look if - # nodes are in exclusive branches - if isinstance(node, If) and exceptions is None: - if ( - node.locate_child(previous)[1] - is not node.locate_child(children[node])[1] - ): - return True - elif isinstance(node, TryExcept): - c2attr, c2node = node.locate_child(previous) - c1attr, c1node = node.locate_child(children[node]) - if c1node is not c2node: - first_in_body_caught_by_handlers = ( - c2attr == "handlers" - and c1attr == "body" - and previous.catch(exceptions) - ) - second_in_body_caught_by_handlers = ( - c2attr == "body" - and c1attr == "handlers" - and children[node].catch(exceptions) - ) - first_in_else_other_in_handlers = ( - c2attr == "handlers" and c1attr == "orelse" - ) - second_in_else_other_in_handlers = ( - c2attr == "orelse" and c1attr == "handlers" - ) - if any( - ( - first_in_body_caught_by_handlers, - second_in_body_caught_by_handlers, - first_in_else_other_in_handlers, - second_in_else_other_in_handlers, - ) - ): - return True - elif c2attr == "handlers" and c1attr == "handlers": - return previous is not children[node] - return False - previous = node - node = node.parent - return False - - -# getitem() helpers. - -_SLICE_SENTINEL = object() - - -def _slice_value(index, context=None): - """Get the value of the given slice index.""" - - if isinstance(index, Const): - if isinstance(index.value, (int, type(None))): - return index.value - elif index is None: - return None - else: - # Try to infer what the index actually is. - # Since we can't return all the possible values, - # we'll stop at the first possible value. - try: - inferred = next(index.infer(context=context)) - except (InferenceError, StopIteration): - pass - else: - if isinstance(inferred, Const): - if isinstance(inferred.value, (int, type(None))): - return inferred.value - - # Use a sentinel, because None can be a valid - # value that this function can return, - # as it is the case for unspecified bounds. - return _SLICE_SENTINEL - - -def _infer_slice(node, context=None): - lower = _slice_value(node.lower, context) - upper = _slice_value(node.upper, context) - step = _slice_value(node.step, context) - if all(elem is not _SLICE_SENTINEL for elem in (lower, upper, step)): - return slice(lower, upper, step) - - raise AstroidTypeError( - message="Could not infer slice used in subscript", - node=node, - index=node.parent, - context=context, - ) - - -def _container_getitem(instance, elts, index, context=None): - """Get a slice or an item, using the given *index*, for the given sequence.""" - try: - if isinstance(index, Slice): - index_slice = _infer_slice(index, context=context) - new_cls = instance.__class__() - new_cls.elts = elts[index_slice] - new_cls.parent = instance.parent - return new_cls - if isinstance(index, Const): - return elts[index.value] - except IndexError as exc: - raise AstroidIndexError( - message="Index {index!s} out of range", - node=instance, - index=index, - context=context, - ) from exc - except TypeError as exc: - raise AstroidTypeError( - message="Type error {error!r}", node=instance, index=index, context=context - ) from exc - - raise AstroidTypeError("Could not use %s as subscript index" % index) - - -OP_PRECEDENCE = { - op: precedence - for precedence, ops in enumerate( - [ - ["Lambda"], # lambda x: x + 1 - ["IfExp"], # 1 if True else 2 - ["or"], - ["and"], - ["not"], - ["Compare"], # in, not in, is, is not, <, <=, >, >=, !=, == - ["|"], - ["^"], - ["&"], - ["<<", ">>"], - ["+", "-"], - ["*", "@", "/", "//", "%"], - ["UnaryOp"], # +, -, ~ - ["**"], - ["Await"], - ] - ) - for op in ops -} - - -class NodeNG: - """A node of the new Abstract Syntax Tree (AST). - - This is the base class for all Astroid node classes. - """ - - is_statement: ClassVar[bool] = False - """Whether this node indicates a statement.""" - optional_assign: ClassVar[ - bool - ] = False # True for For (and for Comprehension if py <3.0) - """Whether this node optionally assigns a variable. - - This is for loop assignments because loop won't necessarily perform an - assignment if the loop has no iterations. - This is also the case from comprehensions in Python 2. - """ - is_function: ClassVar[bool] = False # True for FunctionDef nodes - """Whether this node indicates a function.""" - is_lambda: ClassVar[bool] = False - - # Attributes below are set by the builder module or by raw factories - _astroid_fields: ClassVar[typing.Tuple[str, ...]] = () - """Node attributes that contain child nodes. - - This is redefined in most concrete classes. - """ - _other_fields: ClassVar[typing.Tuple[str, ...]] = () - """Node attributes that do not contain child nodes.""" - _other_other_fields: ClassVar[typing.Tuple[str, ...]] = () - """Attributes that contain AST-dependent fields.""" - # instance specific inference function infer(node, context) - _explicit_inference = None - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional["NodeNG"] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.lineno: Optional[int] = lineno - """The line that this node appears on in the source code.""" - - self.col_offset: Optional[int] = col_offset - """The column that this node appears on in the source code.""" - - self.parent: Optional["NodeNG"] = parent - """The parent node in the syntax tree.""" - - def infer(self, context=None, **kwargs): - """Get a generator of the inferred values. - - This is the main entry point to the inference system. - - .. seealso:: :ref:`inference` - - If the instance has some explicit inference function set, it will be - called instead of the default interface. - - :returns: The inferred values. - :rtype: iterable - """ - if context is not None: - context = context.extra_context.get(self, context) - if self._explicit_inference is not None: - # explicit_inference is not bound, give it self explicitly - try: - # pylint: disable=not-callable - results = tuple(self._explicit_inference(self, context, **kwargs)) - if context is not None: - context.nodes_inferred += len(results) - yield from results - return - except UseInferenceDefault: - pass - - if not context: - # nodes_inferred? - yield from self._infer(context, **kwargs) - return - - key = (self, context.lookupname, context.callcontext, context.boundnode) - if key in context.inferred: - yield from context.inferred[key] - return - - generator = self._infer(context, **kwargs) - results = [] - - # Limit inference amount to help with performance issues with - # exponentially exploding possible results. - limit = AstroidManager().max_inferable_values - for i, result in enumerate(generator): - if i >= limit or (context.nodes_inferred > context.max_inferred): - yield util.Uninferable - break - results.append(result) - yield result - context.nodes_inferred += 1 - - # Cache generated results for subsequent inferences of the - # same node using the same context - context.inferred[key] = tuple(results) - return - - def _repr_name(self): - """Get a name for nice representation. - - This is either :attr:`name`, :attr:`attrname`, or the empty string. - - :returns: The nice name. - :rtype: str - """ - if all(name not in self._astroid_fields for name in ("name", "attrname")): - return getattr(self, "name", "") or getattr(self, "attrname", "") - return "" - - def __str__(self): - rname = self._repr_name() - cname = type(self).__name__ - if rname: - string = "%(cname)s.%(rname)s(%(fields)s)" - alignment = len(cname) + len(rname) + 2 - else: - string = "%(cname)s(%(fields)s)" - alignment = len(cname) + 1 - result = [] - for field in self._other_fields + self._astroid_fields: - value = getattr(self, field) - width = 80 - len(field) - alignment - lines = pprint.pformat(value, indent=2, width=width).splitlines(True) - - inner = [lines[0]] - for line in lines[1:]: - inner.append(" " * alignment + line) - result.append("{}={}".format(field, "".join(inner))) - - return string % { - "cname": cname, - "rname": rname, - "fields": (",\n" + " " * alignment).join(result), - } - - def __repr__(self): - rname = self._repr_name() - if rname: - string = "<%(cname)s.%(rname)s l.%(lineno)s at 0x%(id)x>" - else: - string = "<%(cname)s l.%(lineno)s at 0x%(id)x>" - return string % { - "cname": type(self).__name__, - "rname": rname, - "lineno": self.fromlineno, - "id": id(self), - } - - def accept(self, visitor): - """Visit this node using the given visitor.""" - func = getattr(visitor, "visit_" + self.__class__.__name__.lower()) - return func(self) - - def get_children(self): - """Get the child nodes below this node. - - :returns: The children. - :rtype: iterable(NodeNG) - """ - for field in self._astroid_fields: - attr = getattr(self, field) - if attr is None: - continue - if isinstance(attr, (list, tuple)): - yield from attr - else: - yield attr - yield from () - - def last_child(self): # -> Optional["NodeNG"] - """An optimized version of list(get_children())[-1]""" - for field in self._astroid_fields[::-1]: - attr = getattr(self, field) - if not attr: # None or empty listy / tuple - continue - if isinstance(attr, (list, tuple)): - return attr[-1] - return attr - return None - - def parent_of(self, node): - """Check if this node is the parent of the given node. - - :param node: The node to check if it is the child. - :type node: NodeNG - - :returns: True if this node is the parent of the given node, - False otherwise. - :rtype: bool - """ - parent = node.parent - while parent is not None: - if self is parent: - return True - parent = parent.parent - return False - - def statement(self): - """The first parent node, including self, marked as statement node. - - :returns: The first parent statement. - :rtype: NodeNG - """ - if self.is_statement: - return self - return self.parent.statement() - - def frame(self): - """The first parent frame node. - - A frame node is a :class:`Module`, :class:`FunctionDef`, - or :class:`ClassDef`. - - :returns: The first parent frame node. - :rtype: Module or FunctionDef or ClassDef - """ - return self.parent.frame() - - def scope(self): - """The first parent node defining a new scope. - - :returns: The first parent scope node. - :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr - """ - if self.parent: - return self.parent.scope() - return None - - def root(self): - """Return the root node of the syntax tree. - - :returns: The root node. - :rtype: Module - """ - if self.parent: - return self.parent.root() - return self - - def child_sequence(self, child): - """Search for the sequence that contains this child. - - :param child: The child node to search sequences for. - :type child: NodeNG - - :returns: The sequence containing the given child node. - :rtype: iterable(NodeNG) - - :raises AstroidError: If no sequence could be found that contains - the given child. - """ - for field in self._astroid_fields: - node_or_sequence = getattr(self, field) - if node_or_sequence is child: - return [node_or_sequence] - # /!\ compiler.ast Nodes have an __iter__ walking over child nodes - if ( - isinstance(node_or_sequence, (tuple, list)) - and child in node_or_sequence - ): - return node_or_sequence - - msg = "Could not find %s in %s's children" - raise AstroidError(msg % (repr(child), repr(self))) - - def locate_child(self, child): - """Find the field of this node that contains the given child. - - :param child: The child node to search fields for. - :type child: NodeNG - - :returns: A tuple of the name of the field that contains the child, - and the sequence or node that contains the child node. - :rtype: tuple(str, iterable(NodeNG) or NodeNG) - - :raises AstroidError: If no field could be found that contains - the given child. - """ - for field in self._astroid_fields: - node_or_sequence = getattr(self, field) - # /!\ compiler.ast Nodes have an __iter__ walking over child nodes - if child is node_or_sequence: - return field, child - if ( - isinstance(node_or_sequence, (tuple, list)) - and child in node_or_sequence - ): - return field, node_or_sequence - msg = "Could not find %s in %s's children" - raise AstroidError(msg % (repr(child), repr(self))) - - # FIXME : should we merge child_sequence and locate_child ? locate_child - # is only used in are_exclusive, child_sequence one time in pylint. - - def next_sibling(self): - """The next sibling statement node. - - :returns: The next sibling statement node. - :rtype: NodeNG or None - """ - return self.parent.next_sibling() - - def previous_sibling(self): - """The previous sibling statement. - - :returns: The previous sibling statement node. - :rtype: NodeNG or None - """ - return self.parent.previous_sibling() - - # these are lazy because they're relatively expensive to compute for every - # single node, and they rarely get looked at - - @decorators.cachedproperty - def fromlineno(self) -> Optional[int]: - """The first line that this node appears on in the source code.""" - if self.lineno is None: - return self._fixed_source_line() - return self.lineno - - @decorators.cachedproperty - def tolineno(self) -> Optional[int]: - """The last line that this node appears on in the source code.""" - if not self._astroid_fields: - # can't have children - last_child = None - else: - last_child = self.last_child() - if last_child is None: - return self.fromlineno - - return last_child.tolineno - - def _fixed_source_line(self) -> Optional[int]: - """Attempt to find the line that this node appears on. - - We need this method since not all nodes have :attr:`lineno` set. - """ - line = self.lineno - _node = self - try: - while line is None: - _node = next(_node.get_children()) - line = _node.lineno - except StopIteration: - _node = self.parent - while _node and line is None: - line = _node.lineno - _node = _node.parent - return line - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int or None) - """ - return lineno, self.tolineno - - def set_local(self, name, stmt): - """Define that the given name is declared in the given statement node. - - This definition is stored on the parent scope node. - - .. seealso:: :meth:`scope` - - :param name: The name that is being defined. - :type name: str - - :param stmt: The statement that defines the given name. - :type stmt: NodeNG - """ - self.parent.set_local(name, stmt) - - def nodes_of_class(self, klass, skip_klass=None): - """Get the nodes (including this one or below) of the given types. - - :param klass: The types of node to search for. - :type klass: builtins.type or tuple(builtins.type) - - :param skip_klass: The types of node to ignore. This is useful to ignore - subclasses of :attr:`klass`. - :type skip_klass: builtins.type or tuple(builtins.type) - - :returns: The node of the given types. - :rtype: iterable(NodeNG) - """ - if isinstance(self, klass): - yield self - - if skip_klass is None: - for child_node in self.get_children(): - yield from child_node.nodes_of_class(klass, skip_klass) - - return - - for child_node in self.get_children(): - if isinstance(child_node, skip_klass): - continue - yield from child_node.nodes_of_class(klass, skip_klass) - - @decorators.cached - def _get_assign_nodes(self): - return [] - - def _get_name_nodes(self): - for child_node in self.get_children(): - yield from child_node._get_name_nodes() - - def _get_return_nodes_skip_functions(self): - yield from () - - def _get_yield_nodes_skip_lambdas(self): - yield from () - - def _infer_name(self, frame, name): - # overridden for ImportFrom, Import, Global, TryExcept and Arguments - pass - - def _infer(self, context=None): - """we don't know how to resolve a statement by default""" - # this method is overridden by most concrete classes - raise InferenceError( - "No inference function for {node!r}.", node=self, context=context - ) - - def inferred(self): - """Get a list of the inferred values. - - .. seealso:: :ref:`inference` - - :returns: The inferred values. - :rtype: list - """ - return list(self.infer()) - - def instantiate_class(self): - """Instantiate an instance of the defined class. - - .. note:: - - On anything other than a :class:`ClassDef` this will return self. - - :returns: An instance of the defined class. - :rtype: object - """ - return self - - def has_base(self, node): - """Check if this node inherits from the given type. - - :param node: The node defining the base to look for. - Usually this is a :class:`Name` node. - :type node: NodeNG - """ - return False - - def callable(self): - """Whether this node defines something that is callable. - - :returns: True if this defines something that is callable, - False otherwise. - :rtype: bool - """ - return False - - def eq(self, value): - return False - - def as_string(self): - """Get the source code that this node represents. - - :returns: The source code. - :rtype: str - """ - return as_string.to_code(self) - - def repr_tree( - self, - ids=False, - include_linenos=False, - ast_state=False, - indent=" ", - max_depth=0, - max_width=80, - ) -> str: - """Get a string representation of the AST from this node. - - :param ids: If true, includes the ids with the node type names. - :type ids: bool - - :param include_linenos: If true, includes the line numbers and - column offsets. - :type include_linenos: bool - - :param ast_state: If true, includes information derived from - the whole AST like local and global variables. - :type ast_state: bool - - :param indent: A string to use to indent the output string. - :type indent: str - - :param max_depth: If set to a positive integer, won't return - nodes deeper than max_depth in the string. - :type max_depth: int - - :param max_width: Attempt to format the output string to stay - within this number of characters, but can exceed it under some - circumstances. Only positive integer values are valid, the default is 80. - :type max_width: int - - :returns: The string representation of the AST. - :rtype: str - """ - - @_singledispatch - def _repr_tree(node, result, done, cur_indent="", depth=1): - """Outputs a representation of a non-tuple/list, non-node that's - contained within an AST, including strings. - """ - lines = pprint.pformat( - node, width=max(max_width - len(cur_indent), 1) - ).splitlines(True) - result.append(lines[0]) - result.extend([cur_indent + line for line in lines[1:]]) - return len(lines) != 1 - - # pylint: disable=unused-variable,useless-suppression; doesn't understand singledispatch - @_repr_tree.register(tuple) - @_repr_tree.register(list) - def _repr_seq(node, result, done, cur_indent="", depth=1): - """Outputs a representation of a sequence that's contained within an AST.""" - cur_indent += indent - result.append("[") - if not node: - broken = False - elif len(node) == 1: - broken = _repr_tree(node[0], result, done, cur_indent, depth) - elif len(node) == 2: - broken = _repr_tree(node[0], result, done, cur_indent, depth) - if not broken: - result.append(", ") - else: - result.append(",\n") - result.append(cur_indent) - broken = _repr_tree(node[1], result, done, cur_indent, depth) or broken - else: - result.append("\n") - result.append(cur_indent) - for child in node[:-1]: - _repr_tree(child, result, done, cur_indent, depth) - result.append(",\n") - result.append(cur_indent) - _repr_tree(node[-1], result, done, cur_indent, depth) - broken = True - result.append("]") - return broken - - # pylint: disable=unused-variable,useless-suppression; doesn't understand singledispatch - @_repr_tree.register(NodeNG) - def _repr_node(node, result, done, cur_indent="", depth=1): - """Outputs a strings representation of an astroid node.""" - if node in done: - result.append( - indent - + "<Recursion on {} with id={}".format( - type(node).__name__, id(node) - ) - ) - return False - done.add(node) - - if max_depth and depth > max_depth: - result.append("...") - return False - depth += 1 - cur_indent += indent - if ids: - result.append(f"{type(node).__name__}<0x{id(node):x}>(\n") - else: - result.append("%s(" % type(node).__name__) - fields = [] - if include_linenos: - fields.extend(("lineno", "col_offset")) - fields.extend(node._other_fields) - fields.extend(node._astroid_fields) - if ast_state: - fields.extend(node._other_other_fields) - if not fields: - broken = False - elif len(fields) == 1: - result.append("%s=" % fields[0]) - broken = _repr_tree( - getattr(node, fields[0]), result, done, cur_indent, depth - ) - else: - result.append("\n") - result.append(cur_indent) - for field in fields[:-1]: - result.append("%s=" % field) - _repr_tree(getattr(node, field), result, done, cur_indent, depth) - result.append(",\n") - result.append(cur_indent) - result.append("%s=" % fields[-1]) - _repr_tree(getattr(node, fields[-1]), result, done, cur_indent, depth) - broken = True - result.append(")") - return broken - - result = [] - _repr_tree(self, result, set()) - return "".join(result) - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - The boolean value of a node can have three - possible values: - - * False: For instance, empty data structures, - False, empty strings, instances which return - explicitly False from the __nonzero__ / __bool__ - method. - * True: Most of constructs are True by default: - classes, functions, modules etc - * Uninferable: The inference engine is uncertain of the - node's value. - - :returns: The boolean value of this node. - :rtype: bool or Uninferable - """ - return util.Uninferable - - def op_precedence(self): - # Look up by class name or default to highest precedence - return OP_PRECEDENCE.get(self.__class__.__name__, len(OP_PRECEDENCE)) - - def op_left_associative(self): - # Everything is left associative except `**` and IfExp - return True - - -class Statement(NodeNG): - """Statement node adding a few attributes""" - - is_statement = True - """Whether this node indicates a statement.""" - - def next_sibling(self): - """The next sibling statement node. - - :returns: The next sibling statement node. - :rtype: NodeNG or None - """ - stmts = self.parent.child_sequence(self) - index = stmts.index(self) - try: - return stmts[index + 1] - except IndexError: - return None - - def previous_sibling(self): - """The previous sibling statement. - - :returns: The previous sibling statement node. - :rtype: NodeNG or None - """ - stmts = self.parent.child_sequence(self) - index = stmts.index(self) - if index >= 1: - return stmts[index - 1] - return None - - -class _BaseContainer( - mixins.ParentAssignTypeMixin, NodeNG, bases.Instance, metaclass=abc.ABCMeta -): - """Base class for Set, FrozenSet, Tuple and List.""" - - _astroid_fields = ("elts",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.elts: typing.List[NodeNG] = [] - """The elements in the node.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, elts: typing.List[NodeNG]) -> None: - """Do some setup after initialisation. - - :param elts: The list of elements the that node contains. - """ - self.elts = elts - - @classmethod - def from_elements(cls, elts=None): - """Create a node of this type from the given list of elements. - - :param elts: The list of elements that the node should contain. - :type elts: list(NodeNG) - - :returns: A new node containing the given elements. - :rtype: NodeNG - """ - node = cls() - if elts is None: - node.elts = [] - else: - node.elts = [const_factory(e) if _is_const(e) else e for e in elts] - return node - - def itered(self): - """An iterator over the elements this node contains. - - :returns: The contents of this node. - :rtype: iterable(NodeNG) - """ - return self.elts - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - :rtype: bool or Uninferable - """ - return bool(self.elts) - - @abc.abstractmethod - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - - def get_children(self): - yield from self.elts - - -class LookupMixIn: - """Mixin to look up a name in the right scope.""" - - @lru_cache(maxsize=None) - def lookup(self, name): - """Lookup where the given variable is assigned. - - The lookup starts from self's scope. If self is not a frame itself - and the name is found in the inner frame locals, statements will be - filtered to remove ignorable statements according to self's location. - - :param name: The name of the variable to find assignments for. - :type name: str - - :returns: The scope node and the list of assignments associated to the - given name according to the scope where it has been found (locals, - globals or builtin). - :rtype: tuple(str, list(NodeNG)) - """ - return self.scope().scope_lookup(self, name) - - def ilookup(self, name): - """Lookup the inferred values of the given variable. - - :param name: The variable name to find values for. - :type name: str - - :returns: The inferred values of the statements returned from - :meth:`lookup`. - :rtype: iterable - """ - frame, stmts = self.lookup(name) - context = contextmod.InferenceContext() - return bases._infer_stmts(stmts, context, frame) - - def _get_filtered_node_statements(self, nodes): - statements = [(node, node.statement()) for node in nodes] - # Next we check if we have ExceptHandlers that are parent - # of the underlying variable, in which case the last one survives - if len(statements) > 1 and all( - isinstance(stmt, ExceptHandler) for _, stmt in statements - ): - statements = [ - (node, stmt) for node, stmt in statements if stmt.parent_of(self) - ] - return statements - - def _filter_stmts(self, stmts, frame, offset): - """Filter the given list of statements to remove ignorable statements. - - If self is not a frame itself and the name is found in the inner - frame locals, statements will be filtered to remove ignorable - statements according to self's location. - - :param stmts: The statements to filter. - :type stmts: list(NodeNG) - - :param frame: The frame that all of the given statements belong to. - :type frame: NodeNG - - :param offset: The line offset to filter statements up to. - :type offset: int - - :returns: The filtered statements. - :rtype: list(NodeNG) - """ - # if offset == -1, my actual frame is not the inner frame but its parent - # - # class A(B): pass - # - # we need this to resolve B correctly - if offset == -1: - myframe = self.frame().parent.frame() - else: - myframe = self.frame() - # If the frame of this node is the same as the statement - # of this node, then the node is part of a class or - # a function definition and the frame of this node should be the - # the upper frame, not the frame of the definition. - # For more information why this is important, - # see Pylint issue #295. - # For example, for 'b', the statement is the same - # as the frame / scope: - # - # def test(b=1): - # ... - - if self.statement() is myframe and myframe.parent: - myframe = myframe.parent.frame() - mystmt = self.statement() - # line filtering if we are in the same frame - # - # take care node may be missing lineno information (this is the case for - # nodes inserted for living objects) - if myframe is frame and mystmt.fromlineno is not None: - assert mystmt.fromlineno is not None, mystmt - mylineno = mystmt.fromlineno + offset - else: - # disabling lineno filtering - mylineno = 0 - - _stmts = [] - _stmt_parents = [] - statements = self._get_filtered_node_statements(stmts) - for node, stmt in statements: - # line filtering is on and we have reached our location, break - if stmt.fromlineno and stmt.fromlineno > mylineno > 0: - break - # Ignore decorators with the same name as the - # decorated function - # Fixes issue #375 - if mystmt is stmt and is_from_decorator(self): - continue - assert hasattr(node, "assign_type"), ( - node, - node.scope(), - node.scope().locals, - ) - assign_type = node.assign_type() - if node.has_base(self): - break - - _stmts, done = assign_type._get_filtered_stmts(self, node, _stmts, mystmt) - if done: - break - - optional_assign = assign_type.optional_assign - if optional_assign and assign_type.parent_of(self): - # we are inside a loop, loop var assignment is hiding previous - # assignment - _stmts = [node] - _stmt_parents = [stmt.parent] - continue - - if isinstance(assign_type, NamedExpr): - _stmts = [node] - continue - - # XXX comment various branches below!!! - try: - pindex = _stmt_parents.index(stmt.parent) - except ValueError: - pass - else: - # we got a parent index, this means the currently visited node - # is at the same block level as a previously visited node - if _stmts[pindex].assign_type().parent_of(assign_type): - # both statements are not at the same block level - continue - # if currently visited node is following previously considered - # assignment and both are not exclusive, we can drop the - # previous one. For instance in the following code :: - # - # if a: - # x = 1 - # else: - # x = 2 - # print x - # - # we can't remove neither x = 1 nor x = 2 when looking for 'x' - # of 'print x'; while in the following :: - # - # x = 1 - # x = 2 - # print x - # - # we can remove x = 1 when we see x = 2 - # - # moreover, on loop assignment types, assignment won't - # necessarily be done if the loop has no iteration, so we don't - # want to clear previous assignments if any (hence the test on - # optional_assign) - if not (optional_assign or are_exclusive(_stmts[pindex], node)): - del _stmt_parents[pindex] - del _stmts[pindex] - - # If self and node are exclusive, then we can ignore node - if are_exclusive(self, node): - continue - - # An AssignName node overrides previous assignments if: - # 1. node's statement always assigns - # 2. node and self are in the same block (i.e., has the same parent as self) - if isinstance(node, AssignName): - if isinstance(stmt, ExceptHandler): - # If node's statement is an ExceptHandler, then it is the variable - # bound to the caught exception. If self is not contained within - # the exception handler block, node should override previous assignments; - # otherwise, node should be ignored, as an exception variable - # is local to the handler block. - if stmt.parent_of(self): - _stmts = [] - _stmt_parents = [] - else: - continue - elif not optional_assign and stmt.parent is mystmt.parent: - _stmts = [] - _stmt_parents = [] - elif isinstance(node, DelName): - # Remove all previously stored assignments - _stmts = [] - _stmt_parents = [] - continue - # Add the new assignment - _stmts.append(node) - if isinstance(node, Arguments) or isinstance(node.parent, Arguments): - # Special case for _stmt_parents when node is a function parameter; - # in this case, stmt is the enclosing FunctionDef, which is what we - # want to add to _stmt_parents, not stmt.parent. This case occurs when - # node is an Arguments node (representing varargs or kwargs parameter), - # and when node.parent is an Arguments node (other parameters). - # See issue #180. - _stmt_parents.append(stmt) - else: - _stmt_parents.append(stmt.parent) - return _stmts - - -# Name classes - - -class AssignName( - mixins.NoChildrenMixin, LookupMixIn, mixins.ParentAssignTypeMixin, NodeNG -): - """Variation of :class:`ast.Assign` representing assignment to a name. - - An :class:`AssignName` is the name of something that is assigned to. - This includes variables defined in a function signature or in a loop. - - >>> node = astroid.extract_node('variable = range(10)') - >>> node - <Assign l.1 at 0x7effe1db8550> - >>> list(node.get_children()) - [<AssignName.variable l.1 at 0x7effe1db8748>, <Call l.1 at 0x7effe1db8630>] - >>> list(node.get_children())[0].as_string() - 'variable' - """ - - _other_fields = ("name",) - - def __init__( - self, - name: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param name: The name that is assigned to. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.name: Optional[str] = name - """The name that is assigned to.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - -class DelName( - mixins.NoChildrenMixin, LookupMixIn, mixins.ParentAssignTypeMixin, NodeNG -): - """Variation of :class:`ast.Delete` representing deletion of a name. - - A :class:`DelName` is the name of something that is deleted. - - >>> node = astroid.extract_node("del variable #@") - >>> list(node.get_children()) - [<DelName.variable l.1 at 0x7effe1da4d30>] - >>> list(node.get_children())[0].as_string() - 'variable' - """ - - _other_fields = ("name",) - - def __init__( - self, - name: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param name: The name that is being deleted. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.name: Optional[str] = name - """The name that is being deleted.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - -class Name(mixins.NoChildrenMixin, LookupMixIn, NodeNG): - """Class representing an :class:`ast.Name` node. - - A :class:`Name` node is something that is named, but not covered by - :class:`AssignName` or :class:`DelName`. - - >>> node = astroid.extract_node('range(10)') - >>> node - <Call l.1 at 0x7effe1db8710> - >>> list(node.get_children()) - [<Name.range l.1 at 0x7effe1db86a0>, <Const.int l.1 at 0x7effe1db8518>] - >>> list(node.get_children())[0].as_string() - 'range' - """ - - _other_fields = ("name",) - - def __init__( - self, - name: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param name: The name that this node refers to. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.name: Optional[str] = name - """The name that this node refers to.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def _get_name_nodes(self): - yield self - - for child_node in self.get_children(): - yield from child_node._get_name_nodes() - - -class Arguments(mixins.AssignTypeMixin, NodeNG): - """Class representing an :class:`ast.arguments` node. - - An :class:`Arguments` node represents that arguments in a - function definition. - - >>> node = astroid.extract_node('def foo(bar): pass') - >>> node - <FunctionDef.foo l.1 at 0x7effe1db8198> - >>> node.args - <Arguments l.1 at 0x7effe1db82e8> - """ - - # Python 3.4+ uses a different approach regarding annotations, - # each argument is a new class, _ast.arg, which exposes an - # 'annotation' attribute. In astroid though, arguments are exposed - # as is in the Arguments node and the only way to expose annotations - # is by using something similar with Python 3.3: - # - we expose 'varargannotation' and 'kwargannotation' of annotations - # of varargs and kwargs. - # - we expose 'annotation', a list with annotations for - # for each normal argument. If an argument doesn't have an - # annotation, its value will be None. - _astroid_fields = ( - "args", - "defaults", - "kwonlyargs", - "posonlyargs", - "posonlyargs_annotations", - "kw_defaults", - "annotations", - "varargannotation", - "kwargannotation", - "kwonlyargs_annotations", - "type_comment_args", - "type_comment_kwonlyargs", - "type_comment_posonlyargs", - ) - - _other_fields = ("vararg", "kwarg") - - def __init__( - self, - vararg: Optional[str] = None, - kwarg: Optional[str] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param vararg: The name of the variable length arguments. - - :param kwarg: The name of the variable length keyword arguments. - - :param parent: The parent node in the syntax tree. - """ - super().__init__(parent=parent) - - self.vararg: Optional[str] = vararg # can be None - """The name of the variable length arguments.""" - - self.kwarg: Optional[str] = kwarg # can be None - """The name of the variable length keyword arguments.""" - - self.args: typing.List[AssignName] - """The names of the required arguments.""" - - self.defaults: typing.List[NodeNG] - """The default values for arguments that can be passed positionally.""" - - self.kwonlyargs: typing.List[AssignName] - """The keyword arguments that cannot be passed positionally.""" - - self.posonlyargs: typing.List[AssignName] = [] - """The arguments that can only be passed positionally.""" - - self.kw_defaults: typing.List[Optional[NodeNG]] - """The default values for keyword arguments that cannot be passed positionally.""" - - self.annotations: typing.List[Optional[NodeNG]] - """The type annotations of arguments that can be passed positionally.""" - - self.posonlyargs_annotations: typing.List[Optional[NodeNG]] = [] - """The type annotations of arguments that can only be passed positionally.""" - - self.kwonlyargs_annotations: typing.List[Optional[NodeNG]] = [] - """The type annotations of arguments that cannot be passed positionally.""" - - self.type_comment_args: typing.List[Optional[NodeNG]] = [] - """The type annotation, passed by a type comment, of each argument. - - If an argument does not have a type comment, - the value for that argument will be None. - """ - - self.type_comment_kwonlyargs: typing.List[Optional[NodeNG]] = [] - """The type annotation, passed by a type comment, of each keyword only argument. - - If an argument does not have a type comment, - the value for that argument will be None. - """ - - self.type_comment_posonlyargs: typing.List[Optional[NodeNG]] = [] - """The type annotation, passed by a type comment, of each positional argument. - - If an argument does not have a type comment, - the value for that argument will be None. - """ - - self.varargannotation: Optional[NodeNG] = None # can be None - """The type annotation for the variable length arguments.""" - - self.kwargannotation: Optional[NodeNG] = None # can be None - """The type annotation for the variable length keyword arguments.""" - - # pylint: disable=too-many-arguments - def postinit( - self, - args: typing.List[AssignName], - defaults: typing.List[NodeNG], - kwonlyargs: typing.List[AssignName], - kw_defaults: typing.List[Optional[NodeNG]], - annotations: typing.List[Optional[NodeNG]], - posonlyargs: Optional[typing.List[AssignName]] = None, - kwonlyargs_annotations: Optional[typing.List[Optional[NodeNG]]] = None, - posonlyargs_annotations: Optional[typing.List[Optional[NodeNG]]] = None, - varargannotation: Optional[NodeNG] = None, - kwargannotation: Optional[NodeNG] = None, - type_comment_args: Optional[typing.List[Optional[NodeNG]]] = None, - type_comment_kwonlyargs: Optional[typing.List[Optional[NodeNG]]] = None, - type_comment_posonlyargs: Optional[typing.List[Optional[NodeNG]]] = None, - ) -> None: - """Do some setup after initialisation. - - :param args: The names of the required arguments. - - :param defaults: The default values for arguments that can be passed - positionally. - - :param kwonlyargs: The keyword arguments that cannot be passed - positionally. - - :param posonlyargs: The arguments that can only be passed - positionally. - - :param kw_defaults: The default values for keyword arguments that - cannot be passed positionally. - - :param annotations: The type annotations of arguments that can be - passed positionally. - - :param kwonlyargs_annotations: The type annotations of arguments that - cannot be passed positionally. This should always be passed in - Python 3. - - :param posonlyargs_annotations: The type annotations of arguments that - can only be passed positionally. This should always be passed in - Python 3. - - :param varargannotation: The type annotation for the variable length - arguments. - - :param kwargannotation: The type annotation for the variable length - keyword arguments. - - :param type_comment_args: The type annotation, - passed by a type comment, of each argument. - - :param type_comment_args: The type annotation, - passed by a type comment, of each keyword only argument. - - :param type_comment_args: The type annotation, - passed by a type comment, of each positional argument. - """ - self.args = args - self.defaults = defaults - self.kwonlyargs = kwonlyargs - if posonlyargs is not None: - self.posonlyargs = posonlyargs - self.kw_defaults = kw_defaults - self.annotations = annotations - if kwonlyargs_annotations is not None: - self.kwonlyargs_annotations = kwonlyargs_annotations - if posonlyargs_annotations is not None: - self.posonlyargs_annotations = posonlyargs_annotations - self.varargannotation = varargannotation - self.kwargannotation = kwargannotation - if type_comment_args is not None: - self.type_comment_args = type_comment_args - if type_comment_kwonlyargs is not None: - self.type_comment_kwonlyargs = type_comment_kwonlyargs - if type_comment_posonlyargs is not None: - self.type_comment_posonlyargs = type_comment_posonlyargs - - def _infer_name(self, frame, name): - if self.parent is frame: - return name - return None - - @decorators.cachedproperty - def fromlineno(self): - """The first line that this node appears on in the source code. - - :type: int or None - """ - lineno = super().fromlineno - return max(lineno, self.parent.fromlineno or 0) - - @decorators.cachedproperty - def arguments(self): - """Get all the arguments for this node, including positional only and positional and keyword""" - return list(itertools.chain((self.posonlyargs or ()), self.args or ())) - - def format_args(self): - """Get the arguments formatted as string. - - :returns: The formatted arguments. - :rtype: str - """ - result = [] - positional_only_defaults = [] - positional_or_keyword_defaults = self.defaults - if self.defaults: - args = self.args or [] - positional_or_keyword_defaults = self.defaults[-len(args) :] - positional_only_defaults = self.defaults[: len(self.defaults) - len(args)] - - if self.posonlyargs: - result.append( - _format_args( - self.posonlyargs, - positional_only_defaults, - self.posonlyargs_annotations, - ) - ) - result.append("/") - if self.args: - result.append( - _format_args( - self.args, - positional_or_keyword_defaults, - getattr(self, "annotations", None), - ) - ) - if self.vararg: - result.append("*%s" % self.vararg) - if self.kwonlyargs: - if not self.vararg: - result.append("*") - result.append( - _format_args( - self.kwonlyargs, self.kw_defaults, self.kwonlyargs_annotations - ) - ) - if self.kwarg: - result.append("**%s" % self.kwarg) - return ", ".join(result) - - def default_value(self, argname): - """Get the default value for an argument. - - :param argname: The name of the argument to get the default value for. - :type argname: str - - :raises NoDefault: If there is no default value defined for the - given argument. - """ - args = self.arguments - index = _find_arg(argname, args)[0] - if index is not None: - idx = index - (len(args) - len(self.defaults)) - if idx >= 0: - return self.defaults[idx] - index = _find_arg(argname, self.kwonlyargs)[0] - if index is not None and self.kw_defaults[index] is not None: - return self.kw_defaults[index] - raise NoDefault(func=self.parent, name=argname) - - def is_argument(self, name): - """Check if the given name is defined in the arguments. - - :param name: The name to check for. - :type name: str - - :returns: True if the given name is defined in the arguments, - False otherwise. - :rtype: bool - """ - if name == self.vararg: - return True - if name == self.kwarg: - return True - return ( - self.find_argname(name, rec=True)[1] is not None - or self.kwonlyargs - and _find_arg(name, self.kwonlyargs, rec=True)[1] is not None - ) - - def find_argname(self, argname, rec=False): - """Get the index and :class:`AssignName` node for given name. - - :param argname: The name of the argument to search for. - :type argname: str - - :param rec: Whether or not to include arguments in unpacked tuples - in the search. - :type rec: bool - - :returns: The index and node for the argument. - :rtype: tuple(str or None, AssignName or None) - """ - if self.arguments: - return _find_arg(argname, self.arguments, rec) - return None, None - - def get_children(self): - yield from self.posonlyargs or () - - for elt in self.posonlyargs_annotations: - if elt is not None: - yield elt - - yield from self.args or () - - yield from self.defaults - yield from self.kwonlyargs - - for elt in self.kw_defaults: - if elt is not None: - yield elt - - for elt in self.annotations: - if elt is not None: - yield elt - - if self.varargannotation is not None: - yield self.varargannotation - - if self.kwargannotation is not None: - yield self.kwargannotation - - for elt in self.kwonlyargs_annotations: - if elt is not None: - yield elt - - -def _find_arg(argname, args, rec=False): - for i, arg in enumerate(args): - if isinstance(arg, Tuple): - if rec: - found = _find_arg(argname, arg.elts) - if found[0] is not None: - return found - elif arg.name == argname: - return i, arg - return None, None - - -def _format_args(args, defaults=None, annotations=None): - values = [] - if args is None: - return "" - if annotations is None: - annotations = [] - if defaults is not None: - default_offset = len(args) - len(defaults) - packed = itertools.zip_longest(args, annotations) - for i, (arg, annotation) in enumerate(packed): - if isinstance(arg, Tuple): - values.append("(%s)" % _format_args(arg.elts)) - else: - argname = arg.name - default_sep = "=" - if annotation is not None: - argname += ": " + annotation.as_string() - default_sep = " = " - values.append(argname) - - if defaults is not None and i >= default_offset: - if defaults[i - default_offset] is not None: - values[-1] += default_sep + defaults[i - default_offset].as_string() - return ", ".join(values) - - -class AssignAttr(mixins.ParentAssignTypeMixin, NodeNG): - """Variation of :class:`ast.Assign` representing assignment to an attribute. - - >>> node = astroid.extract_node('self.attribute = range(10)') - >>> node - <Assign l.1 at 0x7effe1d521d0> - >>> list(node.get_children()) - [<AssignAttr.attribute l.1 at 0x7effe1d52320>, <Call l.1 at 0x7effe1d522e8>] - >>> list(node.get_children())[0].as_string() - 'self.attribute' - """ - - _astroid_fields = ("expr",) - _other_fields = ("attrname",) - - def __init__( - self, - attrname: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param attrname: The name of the attribute being assigned to. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.expr: Optional[NodeNG] = None - """What has the attribute that is being assigned to.""" - - self.attrname: Optional[str] = attrname - """The name of the attribute being assigned to.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, expr: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param expr: What has the attribute that is being assigned to. - """ - self.expr = expr - - def get_children(self): - yield self.expr - - -class Assert(Statement): - """Class representing an :class:`ast.Assert` node. - - An :class:`Assert` node represents an assert statement. - - >>> node = astroid.extract_node('assert len(things) == 10, "Not enough things"') - >>> node - <Assert l.1 at 0x7effe1d527b8> - """ - - _astroid_fields = ("test", "fail") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.test: Optional[NodeNG] = None - """The test that passes or fails the assertion.""" - - self.fail: Optional[NodeNG] = None # can be None - """The message shown when the assertion fails.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, test: Optional[NodeNG] = None, fail: Optional[NodeNG] = None - ) -> None: - """Do some setup after initialisation. - - :param test: The test that passes or fails the assertion. - - :param fail: The message shown when the assertion fails. - """ - self.fail = fail - self.test = test - - def get_children(self): - yield self.test - - if self.fail is not None: - yield self.fail - - -class Assign(mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.Assign` node. - - An :class:`Assign` is a statement where something is explicitly - asssigned to. - - >>> node = astroid.extract_node('variable = range(10)') - >>> node - <Assign l.1 at 0x7effe1db8550> - """ - - _astroid_fields = ("targets", "value") - _other_other_fields = ("type_annotation",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.targets: typing.List[NodeNG] = [] - """What is being assigned to.""" - - self.value: Optional[NodeNG] = None - """The value being assigned to the variables.""" - - self.type_annotation: Optional[NodeNG] = None - """If present, this will contain the type annotation passed by a type comment""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - targets: Optional[typing.List[NodeNG]] = None, - value: Optional[NodeNG] = None, - type_annotation: Optional[NodeNG] = None, - ) -> None: - """Do some setup after initialisation. - - :param targets: What is being assigned to. - - :param value: The value being assigned to the variables. - """ - if targets is not None: - self.targets = targets - self.value = value - self.type_annotation = type_annotation - - def get_children(self): - yield from self.targets - - yield self.value - - @decorators.cached - def _get_assign_nodes(self): - return [self] + list(self.value._get_assign_nodes()) - - def _get_yield_nodes_skip_lambdas(self): - yield from self.value._get_yield_nodes_skip_lambdas() - - -class AnnAssign(mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.AnnAssign` node. - - An :class:`AnnAssign` is an assignment with a type annotation. - - >>> node = astroid.extract_node('variable: List[int] = range(10)') - >>> node - <AnnAssign l.1 at 0x7effe1d4c630> - """ - - _astroid_fields = ("target", "annotation", "value") - _other_fields = ("simple",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.target: Optional[NodeNG] = None - """What is being assigned to.""" - - self.annotation: Optional[NodeNG] = None - """The type annotation of what is being assigned to.""" - - self.value: Optional[NodeNG] = None # can be None - """The value being assigned to the variables.""" - - self.simple: Optional[int] = None - """Whether :attr:`target` is a pure name or a complex statement.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - target: NodeNG, - annotation: NodeNG, - simple: int, - value: Optional[NodeNG] = None, - ) -> None: - """Do some setup after initialisation. - - :param target: What is being assigned to. - - :param annotation: The type annotation of what is being assigned to. - - :param simple: Whether :attr:`target` is a pure name - or a complex statement. - - :param value: The value being assigned to the variables. - """ - self.target = target - self.annotation = annotation - self.value = value - self.simple = simple - - def get_children(self): - yield self.target - yield self.annotation - - if self.value is not None: - yield self.value - - -class AugAssign(mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.AugAssign` node. - - An :class:`AugAssign` is an assignment paired with an operator. - - >>> node = astroid.extract_node('variable += 1') - >>> node - <AugAssign l.1 at 0x7effe1db4d68> - """ - - _astroid_fields = ("target", "value") - _other_fields = ("op",) - - def __init__( - self, - op: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param op: The operator that is being combined with the assignment. - This includes the equals sign. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.target: Optional[NodeNG] = None - """What is being assigned to.""" - - self.op: Optional[str] = op - """The operator that is being combined with the assignment. - - This includes the equals sign. - """ - - self.value: Optional[NodeNG] = None - """The value being assigned to the variable.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, target: Optional[NodeNG] = None, value: Optional[NodeNG] = None - ) -> None: - """Do some setup after initialisation. - - :param target: What is being assigned to. - - :param value: The value being assigned to the variable. - """ - self.target = target - self.value = value - - # This is set by inference.py - def _infer_augassign(self, context=None): - raise NotImplementedError - - def type_errors(self, context=None): - """Get a list of type errors which can occur during inference. - - Each TypeError is represented by a :class:`BadBinaryOperationMessage` , - which holds the original exception. - - :returns: The list of possible type errors. - :rtype: list(BadBinaryOperationMessage) - """ - try: - results = self._infer_augassign(context=context) - return [ - result - for result in results - if isinstance(result, util.BadBinaryOperationMessage) - ] - except InferenceError: - return [] - - def get_children(self): - yield self.target - yield self.value - - def _get_yield_nodes_skip_lambdas(self): - """An AugAssign node can contain a Yield node in the value""" - yield from self.value._get_yield_nodes_skip_lambdas() - yield from super()._get_yield_nodes_skip_lambdas() - - -class BinOp(NodeNG): - """Class representing an :class:`ast.BinOp` node. - - A :class:`BinOp` node is an application of a binary operator. - - >>> node = astroid.extract_node('a + b') - >>> node - <BinOp l.1 at 0x7f23b2e8cfd0> - """ - - _astroid_fields = ("left", "right") - _other_fields = ("op",) - - def __init__( - self, - op: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param op: The operator. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.left: Optional[NodeNG] = None - """What is being applied to the operator on the left side.""" - - self.op: Optional[str] = op - """The operator.""" - - self.right: Optional[NodeNG] = None - """What is being applied to the operator on the right side.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, left: Optional[NodeNG] = None, right: Optional[NodeNG] = None - ) -> None: - """Do some setup after initialisation. - - :param left: What is being applied to the operator on the left side. - - :param right: What is being applied to the operator on the right side. - """ - self.left = left - self.right = right - - # This is set by inference.py - def _infer_binop(self, context=None): - raise NotImplementedError - - def type_errors(self, context=None): - """Get a list of type errors which can occur during inference. - - Each TypeError is represented by a :class:`BadBinaryOperationMessage`, - which holds the original exception. - - :returns: The list of possible type errors. - :rtype: list(BadBinaryOperationMessage) - """ - try: - results = self._infer_binop(context=context) - return [ - result - for result in results - if isinstance(result, util.BadBinaryOperationMessage) - ] - except InferenceError: - return [] - - def get_children(self): - yield self.left - yield self.right - - def op_precedence(self): - return OP_PRECEDENCE[self.op] - - def op_left_associative(self): - # 2**3**4 == 2**(3**4) - return self.op != "**" - - -class BoolOp(NodeNG): - """Class representing an :class:`ast.BoolOp` node. - - A :class:`BoolOp` is an application of a boolean operator. - - >>> node = astroid.extract_node('a and b') - >>> node - <BinOp l.1 at 0x7f23b2e71c50> - """ - - _astroid_fields = ("values",) - _other_fields = ("op",) - - def __init__( - self, - op: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param op: The operator. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.op: Optional[str] = op - """The operator.""" - - self.values: typing.List[NodeNG] = [] - """The values being applied to the operator.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, values: Optional[typing.List[NodeNG]] = None) -> None: - """Do some setup after initialisation. - - :param values: The values being applied to the operator. - """ - if values is not None: - self.values = values - - def get_children(self): - yield from self.values - - def op_precedence(self): - return OP_PRECEDENCE[self.op] - - -class Break(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Break` node. - - >>> node = astroid.extract_node('break') - >>> node - <Break l.1 at 0x7f23b2e9e5c0> - """ - - -class Call(NodeNG): - """Class representing an :class:`ast.Call` node. - - A :class:`Call` node is a call to a function, method, etc. - - >>> node = astroid.extract_node('function()') - >>> node - <Call l.1 at 0x7f23b2e71eb8> - """ - - _astroid_fields = ("func", "args", "keywords") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.func: Optional[NodeNG] = None - """What is being called.""" - - self.args: typing.List[NodeNG] = [] - """The positional arguments being given to the call.""" - - self.keywords: typing.List["Keyword"] = [] - """The keyword arguments being given to the call.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - func: Optional[NodeNG] = None, - args: Optional[typing.List[NodeNG]] = None, - keywords: Optional[typing.List["Keyword"]] = None, - ) -> None: - """Do some setup after initialisation. - - :param func: What is being called. - - :param args: The positional arguments being given to the call. - - :param keywords: The keyword arguments being given to the call. - """ - self.func = func - if args is not None: - self.args = args - if keywords is not None: - self.keywords = keywords - - @property - def starargs(self) -> typing.List["Starred"]: - """The positional arguments that unpack something.""" - return [arg for arg in self.args if isinstance(arg, Starred)] - - @property - def kwargs(self) -> typing.List["Keyword"]: - """The keyword arguments that unpack something.""" - return [keyword for keyword in self.keywords if keyword.arg is None] - - def get_children(self): - yield self.func - - yield from self.args - - yield from self.keywords - - -class Compare(NodeNG): - """Class representing an :class:`ast.Compare` node. - - A :class:`Compare` node indicates a comparison. - - >>> node = astroid.extract_node('a <= b <= c') - >>> node - <Compare l.1 at 0x7f23b2e9e6d8> - >>> node.ops - [('<=', <Name.b l.1 at 0x7f23b2e9e2b0>), ('<=', <Name.c l.1 at 0x7f23b2e9e390>)] - """ - - _astroid_fields = ("left", "ops") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.left: Optional[NodeNG] = None - """The value at the left being applied to a comparison operator.""" - - self.ops: typing.List[typing.Tuple[str, NodeNG]] = [] - """The remainder of the operators and their relevant right hand value.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - left: Optional[NodeNG] = None, - ops: Optional[typing.List[typing.Tuple[str, NodeNG]]] = None, - ) -> None: - """Do some setup after initialisation. - - :param left: The value at the left being applied to a comparison - operator. - - :param ops: The remainder of the operators - and their relevant right hand value. - """ - self.left = left - if ops is not None: - self.ops = ops - - def get_children(self): - """Get the child nodes below this node. - - Overridden to handle the tuple fields and skip returning the operator - strings. - - :returns: The children. - :rtype: iterable(NodeNG) - """ - yield self.left - for _, comparator in self.ops: - yield comparator # we don't want the 'op' - - def last_child(self): - """An optimized version of list(get_children())[-1] - - :returns: The last child. - :rtype: NodeNG - """ - # XXX maybe if self.ops: - return self.ops[-1][1] - # return self.left - - -class Comprehension(NodeNG): - """Class representing an :class:`ast.comprehension` node. - - A :class:`Comprehension` indicates the loop inside any type of - comprehension including generator expressions. - - >>> node = astroid.extract_node('[x for x in some_values]') - >>> list(node.get_children()) - [<Name.x l.1 at 0x7f23b2e352b0>, <Comprehension l.1 at 0x7f23b2e35320>] - >>> list(node.get_children())[1].as_string() - 'for x in some_values' - """ - - _astroid_fields = ("target", "iter", "ifs") - _other_fields = ("is_async",) - - optional_assign = True - """Whether this node optionally assigns a variable.""" - - def __init__(self, parent: Optional[NodeNG] = None) -> None: - """ - :param parent: The parent node in the syntax tree. - """ - self.target: Optional[NodeNG] = None - """What is assigned to by the comprehension.""" - - self.iter: Optional[NodeNG] = None - """What is iterated over by the comprehension.""" - - self.ifs: typing.List[NodeNG] = [] - """The contents of any if statements that filter the comprehension.""" - - self.is_async: Optional[bool] = None - """Whether this is an asynchronous comprehension or not.""" - - super().__init__(parent=parent) - - # pylint: disable=redefined-builtin; same name as builtin ast module. - def postinit( - self, - target: Optional[NodeNG] = None, - iter: Optional[NodeNG] = None, - ifs: Optional[typing.List[NodeNG]] = None, - is_async: Optional[bool] = None, - ) -> None: - """Do some setup after initialisation. - - :param target: What is assigned to by the comprehension. - - :param iter: What is iterated over by the comprehension. - - :param ifs: The contents of any if statements that filter - the comprehension. - - :param is_async: Whether this is an asynchronous comprehension or not. - """ - self.target = target - self.iter = iter - if ifs is not None: - self.ifs = ifs - self.is_async = is_async - - def assign_type(self): - """The type of assignment that this node performs. - - :returns: The assignment type. - :rtype: NodeNG - """ - return self - - def _get_filtered_stmts(self, lookup_node, node, stmts, mystmt): - """method used in filter_stmts""" - if self is mystmt: - if isinstance(lookup_node, (Const, Name)): - return [lookup_node], True - - elif self.statement() is mystmt: - # original node's statement is the assignment, only keeps - # current node (gen exp, list comp) - - return [node], True - - return stmts, False - - def get_children(self): - yield self.target - yield self.iter - - yield from self.ifs - - -class Const(mixins.NoChildrenMixin, NodeNG, bases.Instance): - """Class representing any constant including num, str, bool, None, bytes. - - >>> node = astroid.extract_node('(5, "This is a string.", True, None, b"bytes")') - >>> node - <Tuple.tuple l.1 at 0x7f23b2e358d0> - >>> list(node.get_children()) - [<Const.int l.1 at 0x7f23b2e35940>, - <Const.str l.1 at 0x7f23b2e35978>, - <Const.bool l.1 at 0x7f23b2e359b0>, - <Const.NoneType l.1 at 0x7f23b2e359e8>, - <Const.bytes l.1 at 0x7f23b2e35a20>] - """ - - _other_fields = ("value",) - - def __init__( - self, - value: typing.Any, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - kind: Optional[str] = None, - ) -> None: - """ - :param value: The value that the constant represents. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - - :param kind: The string prefix. "u" for u-prefixed strings and ``None`` otherwise. Python 3.8+ only. - """ - self.value: typing.Any = value - """The value that the constant represents.""" - - self.kind: Optional[str] = kind # can be None - """"The string prefix. "u" for u-prefixed strings and ``None`` otherwise. Python 3.8+ only.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def __getattr__(self, name): - # This is needed because of Proxy's __getattr__ method. - # Calling object.__new__ on this class without calling - # __init__ would result in an infinite loop otherwise - # since __getattr__ is called when an attribute doesn't - # exist and self._proxied indirectly calls self.value - # and Proxy __getattr__ calls self.value - if name == "value": - raise AttributeError - return super().__getattr__(name) - - def getitem(self, index, context=None): - """Get an item from this node if subscriptable. - - :param index: The node to use as a subscript index. - :type index: Const or Slice - - :raises AstroidTypeError: When the given index cannot be used as a - subscript index, or if this node is not subscriptable. - """ - if isinstance(index, Const): - index_value = index.value - elif isinstance(index, Slice): - index_value = _infer_slice(index, context=context) - - else: - raise AstroidTypeError( - f"Could not use type {type(index)} as subscript index" - ) - - try: - if isinstance(self.value, (str, bytes)): - return Const(self.value[index_value]) - except IndexError as exc: - raise AstroidIndexError( - message="Index {index!r} out of range", - node=self, - index=index, - context=context, - ) from exc - except TypeError as exc: - raise AstroidTypeError( - message="Type error {error!r}", node=self, index=index, context=context - ) from exc - - raise AstroidTypeError(f"{self!r} (value={self.value})") - - def has_dynamic_getattr(self): - """Check if the node has a custom __getattr__ or __getattribute__. - - :returns: True if the class has a custom - __getattr__ or __getattribute__, False otherwise. - For a :class:`Const` this is always ``False``. - :rtype: bool - """ - return False - - def itered(self): - """An iterator over the elements this node contains. - - :returns: The contents of this node. - :rtype: iterable(Const) - - :raises TypeError: If this node does not represent something that is iterable. - """ - if isinstance(self.value, str): - return [const_factory(elem) for elem in self.value] - raise TypeError(f"Cannot iterate over type {type(self.value)!r}") - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return self._proxied.qname() - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - :rtype: bool - """ - return bool(self.value) - - -class Continue(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Continue` node. - - >>> node = astroid.extract_node('continue') - >>> node - <Continue l.1 at 0x7f23b2e35588> - """ - - -class Decorators(NodeNG): - """A node representing a list of decorators. - - A :class:`Decorators` is the decorators that are applied to - a method or function. - - >>> node = astroid.extract_node(''' - @property - def my_property(self): - return 3 - ''') - >>> node - <FunctionDef.my_property l.2 at 0x7f23b2e35d30> - >>> list(node.get_children())[0] - <Decorators l.1 at 0x7f23b2e35d68> - """ - - _astroid_fields = ("nodes",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.nodes: typing.List[NodeNG] - """The decorators that this node contains. - - :type: list(Name or Call) or None - """ - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, nodes: typing.List[NodeNG]) -> None: - """Do some setup after initialisation. - - :param nodes: The decorators that this node contains. - :type nodes: list(Name or Call) - """ - self.nodes = nodes - - def scope(self): - """The first parent node defining a new scope. - - :returns: The first parent scope node. - :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr - """ - # skip the function node to go directly to the upper level scope - return self.parent.parent.scope() - - def get_children(self): - yield from self.nodes - - -class DelAttr(mixins.ParentAssignTypeMixin, NodeNG): - """Variation of :class:`ast.Delete` representing deletion of an attribute. - - >>> node = astroid.extract_node('del self.attr') - >>> node - <Delete l.1 at 0x7f23b2e35f60> - >>> list(node.get_children())[0] - <DelAttr.attr l.1 at 0x7f23b2e411d0> - """ - - _astroid_fields = ("expr",) - _other_fields = ("attrname",) - - def __init__( - self, - attrname: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param attrname: The name of the attribute that is being deleted. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.expr: Optional[NodeNG] = None - """The name that this node represents. - - :type: Name or None - """ - - self.attrname: Optional[str] = attrname - """The name of the attribute that is being deleted.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, expr: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param expr: The name that this node represents. - :type expr: Name or None - """ - self.expr = expr - - def get_children(self): - yield self.expr - - -class Delete(mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.Delete` node. - - A :class:`Delete` is a ``del`` statement this is deleting something. - - >>> node = astroid.extract_node('del self.attr') - >>> node - <Delete l.1 at 0x7f23b2e35f60> - """ - - _astroid_fields = ("targets",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.targets: typing.List[NodeNG] = [] - """What is being deleted.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, targets: Optional[typing.List[NodeNG]] = None) -> None: - """Do some setup after initialisation. - - :param targets: What is being deleted. - """ - if targets is not None: - self.targets = targets - - def get_children(self): - yield from self.targets - - -class Dict(NodeNG, bases.Instance): - """Class representing an :class:`ast.Dict` node. - - A :class:`Dict` is a dictionary that is created with ``{}`` syntax. - - >>> node = astroid.extract_node('{1: "1"}') - >>> node - <Dict.dict l.1 at 0x7f23b2e35cc0> - """ - - _astroid_fields = ("items",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.items: typing.List[typing.Tuple[NodeNG, NodeNG]] = [] - """The key-value pairs contained in the dictionary.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, items: typing.List[typing.Tuple[NodeNG, NodeNG]]) -> None: - """Do some setup after initialisation. - - :param items: The key-value pairs contained in the dictionary. - """ - self.items = items - - @classmethod - def from_elements(cls, items=None): - """Create a :class:`Dict` of constants from a live dictionary. - - :param items: The items to store in the node. - :type items: dict - - :returns: The created dictionary node. - :rtype: Dict - """ - node = cls() - if items is None: - node.items = [] - else: - node.items = [ - (const_factory(k), const_factory(v) if _is_const(v) else v) - for k, v in items.items() - # The keys need to be constants - if _is_const(k) - ] - return node - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.dict" % BUILTINS - - def get_children(self): - """Get the key and value nodes below this node. - - Children are returned in the order that they are defined in the source - code, key first then the value. - - :returns: The children. - :rtype: iterable(NodeNG) - """ - for key, value in self.items: - yield key - yield value - - def last_child(self): - """An optimized version of list(get_children())[-1] - - :returns: The last child, or None if no children exist. - :rtype: NodeNG or None - """ - if self.items: - return self.items[-1][1] - return None - def itered(self): - """An iterator over the keys this node contains. - - :returns: The keys of this node. - :rtype: iterable(NodeNG) - """ - return [key for (key, _) in self.items] - - def getitem(self, index, context=None): - """Get an item from this node. - - :param index: The node to use as a subscript index. - :type index: Const or Slice - - :raises AstroidTypeError: When the given index cannot be used as a - subscript index, or if this node is not subscriptable. - :raises AstroidIndexError: If the given index does not exist in the - dictionary. - """ - for key, value in self.items: - # TODO(cpopa): no support for overriding yet, {1:2, **{1: 3}}. - if isinstance(key, DictUnpack): - try: - return value.getitem(index, context) - except (AstroidTypeError, AstroidIndexError): - continue - for inferredkey in key.infer(context): - if inferredkey is util.Uninferable: - continue - if isinstance(inferredkey, Const) and isinstance(index, Const): - if inferredkey.value == index.value: - return value - - raise AstroidIndexError(index) - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - :rtype: bool - """ - return bool(self.items) - - -class Expr(Statement): - """Class representing an :class:`ast.Expr` node. - - An :class:`Expr` is any expression that does not have its value used or - stored. - - >>> node = astroid.extract_node('method()') - >>> node - <Call l.1 at 0x7f23b2e352b0> - >>> node.parent - <Expr l.1 at 0x7f23b2e35278> - """ - - _astroid_fields = ("value",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.value: Optional[NodeNG] = None - """What the expression does.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, value: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param value: What the expression does. - """ - self.value = value - - def get_children(self): - yield self.value - - def _get_yield_nodes_skip_lambdas(self): - if not self.value.is_lambda: - yield from self.value._get_yield_nodes_skip_lambdas() - - -class Ellipsis(mixins.NoChildrenMixin, NodeNG): # pylint: disable=redefined-builtin - """Class representing an :class:`ast.Ellipsis` node. - - An :class:`Ellipsis` is the ``...`` syntax. - - Deprecated since v2.6.0 - Use :class:`Const` instead. - Will be removed with the release v2.7.0 - """ - - -class EmptyNode(mixins.NoChildrenMixin, NodeNG): - """Holds an arbitrary object in the :attr:`LocalsDictNodeNG.locals`.""" - - object = None - - -class ExceptHandler(mixins.MultiLineBlockMixin, mixins.AssignTypeMixin, Statement): - """Class representing an :class:`ast.ExceptHandler`. node. - - An :class:`ExceptHandler` is an ``except`` block on a try-except. - - >>> node = astroid.extract_node(''' - try: - do_something() - except Exception as error: - print("Error!") - ''') - >>> node - <TryExcept l.2 at 0x7f23b2e9d908> - >>> >>> node.handlers - [<ExceptHandler l.4 at 0x7f23b2e9e860>] - """ - - _astroid_fields = ("type", "name", "body") - _multi_line_block_fields = ("body",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.type: Optional[NodeNG] = None # can be None - """The types that the block handles. - - :type: Tuple or NodeNG or None - """ - - self.name: Optional[AssignName] = None # can be None - """The name that the caught exception is assigned to.""" - - self.body: typing.List[NodeNG] = [] - """The contents of the block.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def get_children(self): - if self.type is not None: - yield self.type - - if self.name is not None: - yield self.name - - yield from self.body - - # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. - def postinit( - self, - type: Optional[NodeNG] = None, - name: Optional[AssignName] = None, - body: Optional[typing.List[NodeNG]] = None, - ) -> None: - """Do some setup after initialisation. - - :param type: The types that the block handles. - :type type: Tuple or NodeNG or None - - :param name: The name that the caught exception is assigned to. - - :param body:The contents of the block. - """ - self.type = type - self.name = name - if body is not None: - self.body = body - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - if self.name: - return self.name.tolineno - if self.type: - return self.type.tolineno - return self.lineno - - def catch(self, exceptions: Optional[typing.List[str]]) -> bool: - """Check if this node handles any of the given - - :param exceptions: The names of the exceptions to check for. - """ - if self.type is None or exceptions is None: - return True - for node in self.type._get_name_nodes(): - if node.name in exceptions: - return True - return False - - -class ExtSlice(NodeNG): - """Class representing an :class:`ast.ExtSlice` node. - - An :class:`ExtSlice` is a complex slice expression. - - Deprecated since v2.6.0 - Now part of the :class:`Subscript` node. - Will be removed with the release of v2.7.0 - """ - - -class For( - mixins.MultiLineBlockMixin, - mixins.BlockRangeMixIn, - mixins.AssignTypeMixin, - Statement, -): - """Class representing an :class:`ast.For` node. - - >>> node = astroid.extract_node('for thing in things: print(thing)') - >>> node - <For l.1 at 0x7f23b2e8cf28> - """ - - _astroid_fields = ("target", "iter", "body", "orelse") - _other_other_fields = ("type_annotation",) - _multi_line_block_fields = ("body", "orelse") - - optional_assign = True - """Whether this node optionally assigns a variable. - - This is always ``True`` for :class:`For` nodes. - """ - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.target: Optional[NodeNG] = None - """What the loop assigns to.""" - - self.iter: Optional[NodeNG] = None - """What the loop iterates over.""" - - self.body: typing.List[NodeNG] = [] - """The contents of the body of the loop.""" - - self.orelse: typing.List[NodeNG] = [] - """The contents of the ``else`` block of the loop.""" - - self.type_annotation: Optional[NodeNG] = None # can be None - """If present, this will contain the type annotation passed by a type comment""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. - def postinit( - self, - target: Optional[NodeNG] = None, - iter: Optional[NodeNG] = None, - body: Optional[typing.List[NodeNG]] = None, - orelse: Optional[typing.List[NodeNG]] = None, - type_annotation: Optional[NodeNG] = None, - ) -> None: - """Do some setup after initialisation. - - :param target: What the loop assigns to. - - :param iter: What the loop iterates over. - - :param body: The contents of the body of the loop. - - :param orelse: The contents of the ``else`` block of the loop. - """ - self.target = target - self.iter = iter - if body is not None: - self.body = body - if orelse is not None: - self.orelse = orelse - self.type_annotation = type_annotation - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.iter.tolineno - - def get_children(self): - yield self.target - yield self.iter - - yield from self.body - yield from self.orelse - - -class AsyncFor(For): - """Class representing an :class:`ast.AsyncFor` node. - - An :class:`AsyncFor` is an asynchronous :class:`For` built with - the ``async`` keyword. - - >>> node = astroid.extract_node(''' - async def func(things): - async for thing in things: - print(thing) - ''') - >>> node - <AsyncFunctionDef.func l.2 at 0x7f23b2e416d8> - >>> node.body[0] - <AsyncFor l.3 at 0x7f23b2e417b8> - """ - - -class Await(NodeNG): - """Class representing an :class:`ast.Await` node. - - An :class:`Await` is the ``await`` keyword. - - >>> node = astroid.extract_node(''' - async def func(things): - await other_func() - ''') - >>> node - <AsyncFunctionDef.func l.2 at 0x7f23b2e41748> - >>> node.body[0] - <Expr l.3 at 0x7f23b2e419e8> - >>> list(node.body[0].get_children())[0] - <Await l.3 at 0x7f23b2e41a20> - """ - - _astroid_fields = ("value",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.value: Optional[NodeNG] = None - """What to wait for.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, value: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param value: What to wait for. - """ - self.value = value - - def get_children(self): - yield self.value - - -class ImportFrom(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement): - """Class representing an :class:`ast.ImportFrom` node. - - >>> node = astroid.extract_node('from my_package import my_module') - >>> node - <ImportFrom l.1 at 0x7f23b2e415c0> - """ - - _other_fields = ("modname", "names", "level") - - def __init__( - self, - fromname: Optional[str], - names: typing.List[typing.Tuple[str, Optional[str]]], - level: Optional[int] = 0, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param fromname: The module that is being imported from. - - :param names: What is being imported from the module. - - :param level: The level of relative import. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.modname: Optional[str] = fromname # can be None - """The module that is being imported from. - - This is ``None`` for relative imports. - """ - - self.names: typing.List[typing.Tuple[str, Optional[str]]] = names - """What is being imported from the module. - - Each entry is a :class:`tuple` of the name being imported, - and the alias that the name is assigned to (if any). - """ - - # TODO When is 'level' None? - self.level: Optional[int] = level # can be None - """The level of relative import. - - Essentially this is the number of dots in the import. - This is always 0 for absolute imports. - """ - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - -class Attribute(NodeNG): - """Class representing an :class:`ast.Attribute` node.""" - - _astroid_fields = ("expr",) - _other_fields = ("attrname",) - - def __init__( - self, - attrname: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param attrname: The name of the attribute. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.expr: Optional[NodeNG] = None - """The name that this node represents. - - :type: Name or None - """ - - self.attrname: Optional[str] = attrname - """The name of the attribute.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, expr: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param expr: The name that this node represents. - :type expr: Name or None - """ - self.expr = expr - - def get_children(self): - yield self.expr - - -class Global(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Global` node. - - >>> node = astroid.extract_node('global a_global') - >>> node - <Global l.1 at 0x7f23b2e9de10> - """ - - _other_fields = ("names",) - - def __init__( - self, - names: typing.List[str], - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param names: The names being declared as global. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.names: typing.List[str] = names - """The names being declared as global.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def _infer_name(self, frame, name): - return name - - -class If(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): - """Class representing an :class:`ast.If` node. - - >>> node = astroid.extract_node('if condition: print(True)') - >>> node - <If l.1 at 0x7f23b2e9dd30> - """ - - _astroid_fields = ("test", "body", "orelse") - _multi_line_block_fields = ("body", "orelse") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.test: Optional[NodeNG] = None - """The condition that the statement tests.""" - - self.body: typing.List[NodeNG] = [] - """The contents of the block.""" - - self.orelse: typing.List[NodeNG] = [] - """The contents of the ``else`` block.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - test: Optional[NodeNG] = None, - body: Optional[typing.List[NodeNG]] = None, - orelse: Optional[typing.List[NodeNG]] = None, - ) -> None: - """Do some setup after initialisation. - - :param test: The condition that the statement tests. - - :param body: The contents of the block. - - :param orelse: The contents of the ``else`` block. - """ - self.test = test - if body is not None: - self.body = body - if orelse is not None: - self.orelse = orelse - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.test.tolineno - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int) - """ - if lineno == self.body[0].fromlineno: - return lineno, lineno - if lineno <= self.body[-1].tolineno: - return lineno, self.body[-1].tolineno - return self._elsed_block_range(lineno, self.orelse, self.body[0].fromlineno - 1) - - def get_children(self): - yield self.test - - yield from self.body - yield from self.orelse - - def has_elif_block(self): - return len(self.orelse) == 1 and isinstance(self.orelse[0], If) - - def _get_yield_nodes_skip_lambdas(self): - """An If node can contain a Yield node in the test""" - yield from self.test._get_yield_nodes_skip_lambdas() - yield from super()._get_yield_nodes_skip_lambdas() - - def is_sys_guard(self) -> bool: - """Return True if IF stmt is a sys.version_info guard. - - >>> node = astroid.extract_node(''' - import sys - if sys.version_info > (3, 8): - from typing import Literal - else: - from typing_extensions import Literal - ''') - >>> node.is_sys_guard() - True - """ - if isinstance(self.test, Compare): - value = self.test.left - if isinstance(value, Subscript): - value = value.value - if isinstance(value, Attribute) and value.as_string() == "sys.version_info": - return True - - return False - - def is_typing_guard(self) -> bool: - """Return True if IF stmt is a typing guard. - - >>> node = astroid.extract_node(''' - from typing import TYPE_CHECKING - if TYPE_CHECKING: - from xyz import a - ''') - >>> node.is_typing_guard() - True - """ - return isinstance( - self.test, (Name, Attribute) - ) and self.test.as_string().endswith("TYPE_CHECKING") - - -class IfExp(NodeNG): - """Class representing an :class:`ast.IfExp` node. - - >>> node = astroid.extract_node('value if condition else other') - >>> node - <IfExp l.1 at 0x7f23b2e9dbe0> - """ - - _astroid_fields = ("test", "body", "orelse") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.test: Optional[NodeNG] = None - """The condition that the statement tests.""" - - self.body: Optional[NodeNG] = None - """The contents of the block.""" - - self.orelse: Optional[NodeNG] = None - """The contents of the ``else`` block.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - test: Optional[NodeNG] = None, - body: Optional[NodeNG] = None, - orelse: Optional[NodeNG] = None, - ) -> None: - """Do some setup after initialisation. - - :param test: The condition that the statement tests. - - :param body: The contents of the block. - - :param orelse: The contents of the ``else`` block. - """ - self.test = test - self.body = body - self.orelse = orelse - - def get_children(self): - yield self.test - yield self.body - yield self.orelse - - def op_left_associative(self): - # `1 if True else 2 if False else 3` is parsed as - # `1 if True else (2 if False else 3)` - return False - - -class Import(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement): - """Class representing an :class:`ast.Import` node. - - >>> node = astroid.extract_node('import astroid') - >>> node - <Import l.1 at 0x7f23b2e4e5c0> - """ - - _other_fields = ("names",) - - def __init__( - self, - names: Optional[typing.List[typing.Tuple[str, Optional[str]]]] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param names: The names being imported. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.names: typing.List[typing.Tuple[str, Optional[str]]] = names or [] - """The names being imported. - - Each entry is a :class:`tuple` of the name being imported, - and the alias that the name is assigned to (if any). - """ - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - -class Index(NodeNG): - """Class representing an :class:`ast.Index` node. - - An :class:`Index` is a simple subscript. - - Deprecated since v2.6.0 - Now part of the :class:`Subscript` node. - Will be removed with the release of v2.7.0 - """ - - -class Keyword(NodeNG): - """Class representing an :class:`ast.keyword` node. - - >>> node = astroid.extract_node('function(a_kwarg=True)') - >>> node - <Call l.1 at 0x7f23b2e9e320> - >>> node.keywords - [<Keyword l.1 at 0x7f23b2e9e9b0>] - """ - - _astroid_fields = ("value",) - _other_fields = ("arg",) - - def __init__( - self, - arg: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param arg: The argument being assigned to. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.arg: Optional[str] = arg # can be None - """The argument being assigned to.""" - - self.value: Optional[NodeNG] = None - """The value being assigned to the keyword argument.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, value: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param value: The value being assigned to the ketword argument. - """ - self.value = value - - def get_children(self): - yield self.value - - -class List(_BaseContainer): - """Class representing an :class:`ast.List` node. - - >>> node = astroid.extract_node('[1, 2, 3]') - >>> node - <List.list l.1 at 0x7f23b2e9e128> - """ - - _other_fields = ("ctx",) - - def __init__( - self, - ctx: Optional[Context] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param ctx: Whether the list is assigned to or loaded from. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.ctx: Optional[Context] = ctx - """Whether the list is assigned to or loaded from.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.list" % BUILTINS - - def getitem(self, index, context=None): - """Get an item from this node. - - :param index: The node to use as a subscript index. - :type index: Const or Slice - """ - return _container_getitem(self, self.elts, index, context=context) - - -class Nonlocal(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Nonlocal` node. - - >>> node = astroid.extract_node(''' - def function(): - nonlocal var - ''') - >>> node - <FunctionDef.function l.2 at 0x7f23b2e9e208> - >>> node.body[0] - <Nonlocal l.3 at 0x7f23b2e9e908> - """ - - _other_fields = ("names",) - - def __init__( - self, - names: typing.List[str], - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param names: The names being declared as not local. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.names: typing.List[str] = names - """The names being declared as not local.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def _infer_name(self, frame, name): - return name - - -class Pass(mixins.NoChildrenMixin, Statement): - """Class representing an :class:`ast.Pass` node. - - >>> node = astroid.extract_node('pass') - >>> node - <Pass l.1 at 0x7f23b2e9e748> - """ - - -class Raise(Statement): - """Class representing an :class:`ast.Raise` node. - - >>> node = astroid.extract_node('raise RuntimeError("Something bad happened!")') - >>> node - <Raise l.1 at 0x7f23b2e9e828> - """ - - _astroid_fields = ("exc", "cause") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.exc: Optional[NodeNG] = None # can be None - """What is being raised.""" - - self.cause: Optional[NodeNG] = None # can be None - """The exception being used to raise this one.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - exc: Optional[NodeNG] = None, - cause: Optional[NodeNG] = None, - ) -> None: - """Do some setup after initialisation. - - :param exc: What is being raised. - - :param cause: The exception being used to raise this one. - """ - self.exc = exc - self.cause = cause - - def raises_not_implemented(self): - """Check if this node raises a :class:`NotImplementedError`. - - :returns: True if this node raises a :class:`NotImplementedError`, - False otherwise. - :rtype: bool - """ - if not self.exc: - return False - for name in self.exc._get_name_nodes(): - if name.name == "NotImplementedError": - return True - return False - - def get_children(self): - if self.exc is not None: - yield self.exc - - if self.cause is not None: - yield self.cause - - -class Return(Statement): - """Class representing an :class:`ast.Return` node. - - >>> node = astroid.extract_node('return True') - >>> node - <Return l.1 at 0x7f23b8211908> - """ - - _astroid_fields = ("value",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.value: Optional[NodeNG] = None # can be None - """The value being returned.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, value: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param value: The value being returned. - """ - self.value = value - - def get_children(self): - if self.value is not None: - yield self.value - - def is_tuple_return(self): - return isinstance(self.value, Tuple) - - def _get_return_nodes_skip_functions(self): - yield self - - -class Set(_BaseContainer): - """Class representing an :class:`ast.Set` node. - - >>> node = astroid.extract_node('{1, 2, 3}') - >>> node - <Set.set l.1 at 0x7f23b2e71d68> - """ - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.set" % BUILTINS - - -class Slice(NodeNG): - """Class representing an :class:`ast.Slice` node. - - >>> node = astroid.extract_node('things[1:3]') - >>> node - <Subscript l.1 at 0x7f23b2e71f60> - >>> node.slice - <Slice l.1 at 0x7f23b2e71e80> - """ - - _astroid_fields = ("lower", "upper", "step") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.lower: Optional[NodeNG] = None # can be None - """The lower index in the slice.""" - - self.upper: Optional[NodeNG] = None # can be None - """The upper index in the slice.""" - - self.step: Optional[NodeNG] = None # can be None - """The step to take between indexes.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - lower: Optional[NodeNG] = None, - upper: Optional[NodeNG] = None, - step: Optional[NodeNG] = None, - ) -> None: - """Do some setup after initialisation. - - :param lower: The lower index in the slice. - - :param upper: The upper index in the slice. - - :param step: The step to take between index. - """ - self.lower = lower - self.upper = upper - self.step = step - - def _wrap_attribute(self, attr): - """Wrap the empty attributes of the Slice in a Const node.""" - if not attr: - const = const_factory(attr) - const.parent = self - return const - return attr - - @decorators.cachedproperty - def _proxied(self): - builtins = AstroidManager().builtins_module - return builtins.getattr("slice")[0] - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.slice" % BUILTINS - - def igetattr(self, attrname, context=None): - """Infer the possible values of the given attribute on the slice. - - :param attrname: The name of the attribute to infer. - :type attrname: str - - :returns: The inferred possible values. - :rtype: iterable(NodeNG) - """ - if attrname == "start": - yield self._wrap_attribute(self.lower) - elif attrname == "stop": - yield self._wrap_attribute(self.upper) - elif attrname == "step": - yield self._wrap_attribute(self.step) - else: - yield from self.getattr(attrname, context=context) - - def getattr(self, attrname, context=None): - return self._proxied.getattr(attrname, context) - - def get_children(self): - if self.lower is not None: - yield self.lower - - if self.upper is not None: - yield self.upper - - if self.step is not None: - yield self.step - - -class Starred(mixins.ParentAssignTypeMixin, NodeNG): - """Class representing an :class:`ast.Starred` node. - - >>> node = astroid.extract_node('*args') - >>> node - <Starred l.1 at 0x7f23b2e41978> - """ - - _astroid_fields = ("value",) - _other_fields = ("ctx",) - - def __init__( - self, - ctx: Optional[Context] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param ctx: Whether the list is assigned to or loaded from. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.value: Optional[NodeNG] = None - """What is being unpacked.""" - - self.ctx: Optional[Context] = ctx - """Whether the starred item is assigned to or loaded from.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, value: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param value: What is being unpacked. - """ - self.value = value - - def get_children(self): - yield self.value - - -class Subscript(NodeNG): - """Class representing an :class:`ast.Subscript` node. - - >>> node = astroid.extract_node('things[1:3]') - >>> node - <Subscript l.1 at 0x7f23b2e71f60> - """ - - _astroid_fields = ("value", "slice") - _other_fields = ("ctx",) - - def __init__( - self, - ctx: Optional[Context] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param ctx: Whether the subscripted item is assigned to or loaded from. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.value: Optional[NodeNG] = None - """What is being indexed.""" - - self.slice: Optional[NodeNG] = None - """The slice being used to lookup.""" - - self.ctx: Optional[Context] = ctx - """Whether the subscripted item is assigned to or loaded from.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. - def postinit( - self, value: Optional[NodeNG] = None, slice: Optional[NodeNG] = None - ) -> None: - """Do some setup after initialisation. - - :param value: What is being indexed. - - :param slice: The slice being used to lookup. - """ - self.value = value - self.slice = slice - - def get_children(self): - yield self.value - yield self.slice - - -class TryExcept(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): - """Class representing an :class:`ast.TryExcept` node. - - >>> node = astroid.extract_node(''' - try: - do_something() - except Exception as error: - print("Error!") - ''') - >>> node - <TryExcept l.2 at 0x7f23b2e9d908> - """ - - _astroid_fields = ("body", "handlers", "orelse") - _multi_line_block_fields = ("body", "handlers", "orelse") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.body: typing.List[NodeNG] = [] - """The contents of the block to catch exceptions from.""" - - self.handlers: typing.List[ExceptHandler] = [] - """The exception handlers.""" - - self.orelse: typing.List[NodeNG] = [] - """The contents of the ``else`` block.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - body: Optional[typing.List[NodeNG]] = None, - handlers: Optional[typing.List[ExceptHandler]] = None, - orelse: Optional[typing.List[NodeNG]] = None, - ) -> None: - """Do some setup after initialisation. - - :param body: The contents of the block to catch exceptions from. - - :param handlers: The exception handlers. - - :param orelse: The contents of the ``else`` block. - """ - if body is not None: - self.body = body - if handlers is not None: - self.handlers = handlers - if orelse is not None: - self.orelse = orelse - - def _infer_name(self, frame, name): - return name - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int) - """ - last = None - for exhandler in self.handlers: - if exhandler.type and lineno == exhandler.type.fromlineno: - return lineno, lineno - if exhandler.body[0].fromlineno <= lineno <= exhandler.body[-1].tolineno: - return lineno, exhandler.body[-1].tolineno - if last is None: - last = exhandler.body[0].fromlineno - 1 - return self._elsed_block_range(lineno, self.orelse, last) - - def get_children(self): - yield from self.body - - yield from self.handlers or () - yield from self.orelse or () - - -class TryFinally(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): - """Class representing an :class:`ast.TryFinally` node. - - >>> node = astroid.extract_node(''' - try: - do_something() - except Exception as error: - print("Error!") - finally: - print("Cleanup!") - ''') - >>> node - <TryFinally l.2 at 0x7f23b2e41d68> - """ - - _astroid_fields = ("body", "finalbody") - _multi_line_block_fields = ("body", "finalbody") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.body: typing.Union[typing.List[TryExcept], typing.List[NodeNG]] = [] - """The try-except that the finally is attached to.""" - - self.finalbody: typing.List[NodeNG] = [] - """The contents of the ``finally`` block.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - body: typing.Union[typing.List[TryExcept], typing.List[NodeNG], None] = None, - finalbody: Optional[typing.List[NodeNG]] = None, - ) -> None: - """Do some setup after initialisation. - - :param body: The try-except that the finally is attached to. - - :param finalbody: The contents of the ``finally`` block. - """ - if body is not None: - self.body = body - if finalbody is not None: - self.finalbody = finalbody - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int) - """ - child = self.body[0] - # py2.5 try: except: finally: - if ( - isinstance(child, TryExcept) - and child.fromlineno == self.fromlineno - and child.tolineno >= lineno > self.fromlineno - ): - return child.block_range(lineno) - return self._elsed_block_range(lineno, self.finalbody) - - def get_children(self): - yield from self.body - yield from self.finalbody - - -class Tuple(_BaseContainer): - """Class representing an :class:`ast.Tuple` node. - - >>> node = astroid.extract_node('(1, 2, 3)') - >>> node - <Tuple.tuple l.1 at 0x7f23b2e41780> - """ - - _other_fields = ("ctx",) - - def __init__( - self, - ctx: Optional[Context] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param ctx: Whether the tuple is assigned to or loaded from. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.ctx: Optional[Context] = ctx - """Whether the tuple is assigned to or loaded from.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.tuple" % BUILTINS - - def getitem(self, index, context=None): - """Get an item from this node. - - :param index: The node to use as a subscript index. - :type index: Const or Slice - """ - return _container_getitem(self, self.elts, index, context=context) - - -class UnaryOp(NodeNG): - """Class representing an :class:`ast.UnaryOp` node. - - >>> node = astroid.extract_node('-5') - >>> node - <UnaryOp l.1 at 0x7f23b2e4e198> - """ - - _astroid_fields = ("operand",) - _other_fields = ("op",) - - def __init__( - self, - op: Optional[str] = None, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param op: The operator. - - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.op: Optional[str] = op - """The operator.""" - - self.operand: Optional[NodeNG] = None - """What the unary operator is applied to.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, operand: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param operand: What the unary operator is applied to. - """ - self.operand = operand - - # This is set by inference.py - def _infer_unaryop(self, context=None): - raise NotImplementedError - - def type_errors(self, context=None): - """Get a list of type errors which can occur during inference. - - Each TypeError is represented by a :class:`BadBinaryOperationMessage`, - which holds the original exception. - - :returns: The list of possible type errors. - :rtype: list(BadBinaryOperationMessage) - """ - try: - results = self._infer_unaryop(context=context) - return [ - result - for result in results - if isinstance(result, util.BadUnaryOperationMessage) - ] - except InferenceError: - return [] - - def get_children(self): - yield self.operand - - def op_precedence(self): - if self.op == "not": - return OP_PRECEDENCE[self.op] - - return super().op_precedence() - - -class While(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): - """Class representing an :class:`ast.While` node. - - >>> node = astroid.extract_node(''' - while condition(): - print("True") - ''') - >>> node - <While l.2 at 0x7f23b2e4e390> - """ - - _astroid_fields = ("test", "body", "orelse") - _multi_line_block_fields = ("body", "orelse") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.test: Optional[NodeNG] = None - """The condition that the loop tests.""" - - self.body: typing.List[NodeNG] = [] - """The contents of the loop.""" - - self.orelse: typing.List[NodeNG] = [] - """The contents of the ``else`` block.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - test: Optional[NodeNG] = None, - body: Optional[typing.List[NodeNG]] = None, - orelse: Optional[typing.List[NodeNG]] = None, - ) -> None: - """Do some setup after initialisation. - - :param test: The condition that the loop tests. - - :param body: The contents of the loop. - - :param orelse: The contents of the ``else`` block. - """ - self.test = test - if body is not None: - self.body = body - if orelse is not None: - self.orelse = orelse - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.test.tolineno - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: The line number to start the range at. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - starting at the given line number. - :rtype: tuple(int, int) - """ - return self._elsed_block_range(lineno, self.orelse) - - def get_children(self): - yield self.test - - yield from self.body - yield from self.orelse - - def _get_yield_nodes_skip_lambdas(self): - """A While node can contain a Yield node in the test""" - yield from self.test._get_yield_nodes_skip_lambdas() - yield from super()._get_yield_nodes_skip_lambdas() - - -class With( - mixins.MultiLineBlockMixin, - mixins.BlockRangeMixIn, - mixins.AssignTypeMixin, - Statement, -): - """Class representing an :class:`ast.With` node. - - >>> node = astroid.extract_node(''' - with open(file_path) as file_: - print(file_.read()) - ''') - >>> node - <With l.2 at 0x7f23b2e4e710> - """ - - _astroid_fields = ("items", "body") - _other_other_fields = ("type_annotation",) - _multi_line_block_fields = ("body",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.items: typing.List[typing.Tuple[NodeNG, Optional[NodeNG]]] = [] - """The pairs of context managers and the names they are assigned to.""" - - self.body: typing.List[NodeNG] = [] - """The contents of the ``with`` block.""" - - self.type_annotation: Optional[NodeNG] = None # can be None - """If present, this will contain the type annotation passed by a type comment""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - items: Optional[typing.List[typing.Tuple[NodeNG, Optional[NodeNG]]]] = None, - body: Optional[typing.List[NodeNG]] = None, - type_annotation: Optional[NodeNG] = None, - ) -> None: - """Do some setup after initialisation. - - :param items: The pairs of context managers and the names - they are assigned to. - - :param body: The contents of the ``with`` block. - """ - if items is not None: - self.items = items - if body is not None: - self.body = body - self.type_annotation = type_annotation - - @decorators.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.items[-1][0].tolineno - - def get_children(self): - """Get the child nodes below this node. - - :returns: The children. - :rtype: iterable(NodeNG) - """ - for expr, var in self.items: - yield expr - if var: - yield var - yield from self.body - - -class AsyncWith(With): - """Asynchronous ``with`` built with the ``async`` keyword.""" - - -class Yield(NodeNG): - """Class representing an :class:`ast.Yield` node. - - >>> node = astroid.extract_node('yield True') - >>> node - <Yield l.1 at 0x7f23b2e4e5f8> - """ - - _astroid_fields = ("value",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.value: Optional[NodeNG] = None # can be None - """The value to yield.""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, value: Optional[NodeNG] = None) -> None: - """Do some setup after initialisation. - - :param value: The value to yield. - """ - self.value = value - - def get_children(self): - if self.value is not None: - yield self.value - - def _get_yield_nodes_skip_lambdas(self): - yield self - - -class YieldFrom(Yield): # TODO value is required, not optional - """Class representing an :class:`ast.YieldFrom` node.""" - - -class DictUnpack(mixins.NoChildrenMixin, NodeNG): - """Represents the unpacking of dicts into dicts using :pep:`448`.""" - - -class FormattedValue(NodeNG): - """Class representing an :class:`ast.FormattedValue` node. - - Represents a :pep:`498` format string. - - >>> node = astroid.extract_node('f"Format {type_}"') - >>> node - <JoinedStr l.1 at 0x7f23b2e4ed30> - >>> node.values - [<Const.str l.1 at 0x7f23b2e4eda0>, <FormattedValue l.1 at 0x7f23b2e4edd8>] - """ - - _astroid_fields = ("value", "format_spec") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.value: NodeNG - """The value to be formatted into the string.""" - - self.conversion: Optional[int] = None # can be None - """The type of formatting to be applied to the value. - - .. seealso:: - :class:`ast.FormattedValue` - """ - - self.format_spec: Optional[NodeNG] = None # can be None - """The formatting to be applied to the value. - - .. seealso:: - :class:`ast.FormattedValue` - - :type: JoinedStr or None - """ - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - value: NodeNG, - conversion: Optional[int] = None, - format_spec: Optional[NodeNG] = None, - ) -> None: - """Do some setup after initialisation. - - :param value: The value to be formatted into the string. - - :param conversion: The type of formatting to be applied to the value. - - :param format_spec: The formatting to be applied to the value. - :type format_spec: JoinedStr or None - """ - self.value = value - self.conversion = conversion - self.format_spec = format_spec - - def get_children(self): - yield self.value - - if self.format_spec is not None: - yield self.format_spec - - -class JoinedStr(NodeNG): - """Represents a list of string expressions to be joined. - - >>> node = astroid.extract_node('f"Format {type_}"') - >>> node - <JoinedStr l.1 at 0x7f23b2e4ed30> - """ - - _astroid_fields = ("values",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.values: typing.List[NodeNG] = [] - """The string expressions to be joined. - - :type: list(FormattedValue or Const) - """ - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, values: Optional[typing.List[NodeNG]] = None) -> None: - """Do some setup after initialisation. - - :param value: The string expressions to be joined. - - :type: list(FormattedValue or Const) - """ - if values is not None: - self.values = values - - def get_children(self): - yield from self.values - - -class NamedExpr(mixins.AssignTypeMixin, NodeNG): - """Represents the assignment from the assignment expression - - >>> module = astroid.parse('if a := 1: pass') - >>> module.body[0].test - <NamedExpr l.1 at 0x7f23b2e4ed30> - """ - - _astroid_fields = ("target", "value") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - """ - :param lineno: The line that this node appears on in the source code. - - :param col_offset: The column that this node appears on in the - source code. - - :param parent: The parent node in the syntax tree. - """ - self.target: NodeNG - """The assignment target - - :type: Name - """ - - self.value: NodeNG - """The value that gets assigned in the expression""" - - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, target: NodeNG, value: NodeNG) -> None: - self.target = target - self.value = value - - -class Unknown(mixins.AssignTypeMixin, NodeNG): - """This node represents a node in a constructed AST where - introspection is not possible. At the moment, it's only used in - the args attribute of FunctionDef nodes where function signature - introspection failed. - """ - - name = "Unknown" - - def qname(self): - return "Unknown" - - def infer(self, context=None, **kwargs): - """Inference on an Unknown node immediately terminates.""" - yield util.Uninferable - - -class EvaluatedObject(NodeNG): - """Contains an object that has already been inferred - - This class is useful to pre-evaluate a particular node, - with the resulting class acting as the non-evaluated node. - """ - - name = "EvaluatedObject" - _astroid_fields = ("original",) - _other_fields = ("value",) - - def __init__( - self, original: NodeNG, value: typing.Union[NodeNG, util.Uninferable] - ) -> None: - self.original: NodeNG = original - """The original node that has already been evaluated""" - - self.value: typing.Union[NodeNG, util.Uninferable] = value - """The inferred value""" - - super().__init__( - lineno=self.original.lineno, - col_offset=self.original.col_offset, - parent=self.original.parent, - ) - - def infer(self, context=None, **kwargs): - yield self.value - - -# Pattern matching ####################################################### - - -class Match(Statement): - """Class representing a :class:`ast.Match` node. - - >>> node = astroid.extract_node(''' - match x: - case 200: - ... - case _: - ... - ''') - >>> node - <Match l.2 at 0x10c24e170> - """ - - _astroid_fields = ("subject", "cases") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - self.subject: NodeNG - self.cases: typing.List["MatchCase"] - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - *, - subject: NodeNG, - cases: typing.List["MatchCase"], - ) -> None: - self.subject = subject - self.cases = cases - - -class Pattern(NodeNG): - """Base class for all Pattern nodes.""" - - -class MatchCase(mixins.MultiLineBlockMixin, NodeNG): - """Class representing a :class:`ast.match_case` node. - - >>> node = astroid.extract_node(''' - match x: - case 200: - ... - ''') - >>> node.cases[0] - <MatchCase l.3 at 0x10c24e590> - """ - - _astroid_fields = ("pattern", "guard", "body") - _multi_line_block_fields = ("body",) - - def __init__(self, *, parent: Optional[NodeNG] = None) -> None: - self.pattern: Pattern - self.guard: Optional[NodeNG] - self.body: typing.List[NodeNG] - super().__init__(parent=parent) - - def postinit( - self, - *, - pattern: Pattern, - guard: Optional[NodeNG], - body: typing.List[NodeNG], - ) -> None: - self.pattern = pattern - self.guard = guard - self.body = body - - -class MatchValue(Pattern): - """Class representing a :class:`ast.MatchValue` node. - - >>> node = astroid.extract_node(''' - match x: - case 200: - ... - ''') - >>> node.cases[0].pattern - <MatchValue l.3 at 0x10c24e200> - """ - - _astroid_fields = ("value",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - self.value: NodeNG - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, *, value: NodeNG) -> None: - self.value = value - - -class MatchSingleton(Pattern): - """Class representing a :class:`ast.MatchSingleton` node. - - >>> node = astroid.extract_node(''' - match x: - case True: - ... - case False: - ... - case None: - ... - ''') - >>> node.cases[0].pattern - <MatchSingleton l.3 at 0x10c2282e0> - >>> node.cases[1].pattern - <MatchSingleton l.5 at 0x10c228af0> - >>> node.cases[2].pattern - <MatchSingleton l.7 at 0x10c229f90> - """ - - _other_fields = ("value",) - - def __init__( - self, - *, - value: Literal[True, False, None], - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - self.value: Literal[True, False, None] = value - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - -class MatchSequence(Pattern): - """Class representing a :class:`ast.MatchSequence` node. - - >>> node = astroid.extract_node(''' - match x: - case [1, 2]: - ... - case (1, 2, *_): - ... - ''') - >>> node.cases[0].pattern - <MatchSequence l.3 at 0x10ca80d00> - >>> node.cases[1].pattern - <MatchSequence l.5 at 0x10ca80b20> - """ - - _astroid_fields = ("patterns",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - self.patterns: typing.List[Pattern] - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, *, patterns: typing.List[Pattern]) -> None: - self.patterns = patterns - - -class MatchMapping(mixins.AssignTypeMixin, Pattern): - """Class representing a :class:`ast.MatchMapping` node. - - >>> node = astroid.extract_node(''' - match x: - case {1: "Hello", 2: "World", 3: _, **rest}: - ... - ''') - >>> node.cases[0].pattern - <MatchMapping l.3 at 0x10c8a8850> - """ - - _astroid_fields = ("keys", "patterns", "rest") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - self.keys: typing.List[NodeNG] - self.patterns: typing.List[Pattern] - self.rest: Optional[AssignName] - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - *, - keys: typing.List[NodeNG], - patterns: typing.List[Pattern], - rest: Optional[AssignName], - ) -> None: - self.keys = keys - self.patterns = patterns - self.rest = rest - - assigned_stmts: Callable[ - [ - "MatchMapping", - AssignName, - Optional[contextmod.InferenceContext], - Literal[None], - ], - Generator[NodeNG, None, None], - ] - - -class MatchClass(Pattern): - """Class representing a :class:`ast.MatchClass` node. - - >>> node = astroid.extract_node(''' - match x: - case Point2D(0, 0): - ... - case Point3D(x=0, y=0, z=0): - ... - ''') - >>> node.cases[0].pattern - <MatchClass l.3 at 0x10ca83940> - >>> node.cases[1].pattern - <MatchClass l.5 at 0x10ca80880> - """ - - _astroid_fields = ("cls", "patterns", "kwd_patterns") - _other_fields = ("kwd_attrs",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - self.cls: NodeNG - self.patterns: typing.List[Pattern] - self.kwd_attrs: typing.List[str] - self.kwd_patterns: typing.List[Pattern] - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - *, - cls: NodeNG, - patterns: typing.List[Pattern], - kwd_attrs: typing.List[str], - kwd_patterns: typing.List[Pattern], - ) -> None: - self.cls = cls - self.patterns = patterns - self.kwd_attrs = kwd_attrs - self.kwd_patterns = kwd_patterns - - -class MatchStar(mixins.AssignTypeMixin, Pattern): - """Class representing a :class:`ast.MatchStar` node. - - >>> node = astroid.extract_node(''' - match x: - case [1, *_]: - ... - ''') - >>> node.cases[0].pattern.patterns[1] - <MatchStar l.3 at 0x10ca809a0> - """ - - _astroid_fields = ("name",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - self.name: Optional[AssignName] - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, *, name: Optional[AssignName]) -> None: - self.name = name - - assigned_stmts: Callable[ - [ - "MatchStar", - AssignName, - Optional[contextmod.InferenceContext], - Literal[None], - ], - Generator[NodeNG, None, None], - ] - - -class MatchAs(mixins.AssignTypeMixin, Pattern): - """Class representing a :class:`ast.MatchAs` node. - - >>> node = astroid.extract_node(''' - match x: - case [1, a]: - ... - case {'key': b}: - ... - case Point2D(0, 0) as c: - ... - case d: - ... - ''') - >>> node.cases[0].pattern.patterns[1] - <MatchAs l.3 at 0x10d0b2da0> - >>> node.cases[1].pattern.patterns[0] - <MatchAs l.5 at 0x10d0b2920> - >>> node.cases[2].pattern - <MatchAs l.7 at 0x10d0b06a0> - >>> node.cases[3].pattern - <MatchAs l.9 at 0x10d09b880> - """ - - _astroid_fields = ("pattern", "name") - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - self.pattern: Optional[Pattern] - self.name: Optional[AssignName] - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit( - self, - *, - pattern: Optional[Pattern], - name: Optional[AssignName], - ) -> None: - self.pattern = pattern - self.name = name - - assigned_stmts: Callable[ - [ - "MatchAs", - AssignName, - Optional[contextmod.InferenceContext], - Literal[None], - ], - Generator[NodeNG, None, None], - ] - - -class MatchOr(Pattern): - """Class representing a :class:`ast.MatchOr` node. - - >>> node = astroid.extract_node(''' - match x: - case 400 | 401 | 402: - ... - ''') - >>> node.cases[0].pattern - <MatchOr l.3 at 0x10d0b0b50> - """ - - _astroid_fields = ("patterns",) - - def __init__( - self, - lineno: Optional[int] = None, - col_offset: Optional[int] = None, - parent: Optional[NodeNG] = None, - ) -> None: - self.patterns: typing.List[Pattern] - super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) - - def postinit(self, *, patterns: typing.List[Pattern]) -> None: - self.patterns = patterns - - -# constants ############################################################## - -CONST_CLS = { - list: List, - tuple: Tuple, - dict: Dict, - set: Set, - type(None): Const, - type(NotImplemented): Const, - type(...): Const, -} - - -def _update_const_classes(): - """update constant classes, so the keys of CONST_CLS can be reused""" - klasses = (bool, int, float, complex, str, bytes) - for kls in klasses: - CONST_CLS[kls] = Const - - -_update_const_classes() - - -def _two_step_initialization(cls, value): - instance = cls() - instance.postinit(value) - return instance - - -def _dict_initialization(cls, value): - if isinstance(value, dict): - value = tuple(value.items()) - return _two_step_initialization(cls, value) - - -_CONST_CLS_CONSTRUCTORS = { - List: _two_step_initialization, - Tuple: _two_step_initialization, - Dict: _dict_initialization, - Set: _two_step_initialization, - Const: lambda cls, value: cls(value), -} - - -def const_factory(value): - """return an astroid node for a python value""" - # XXX we should probably be stricter here and only consider stuff in - # CONST_CLS or do better treatment: in case where value is not in CONST_CLS, - # we should rather recall the builder on this value than returning an empty - # node (another option being that const_factory shouldn't be called with something - # not in CONST_CLS) - assert not isinstance(value, NodeNG) - - # Hack for ignoring elements of a sequence - # or a mapping, in order to avoid transforming - # each element to an AST. This is fixed in 2.0 - # and this approach is a temporary hack. - if isinstance(value, (list, set, tuple, dict)): - elts = [] - else: - elts = value - - try: - initializer_cls = CONST_CLS[value.__class__] - initializer = _CONST_CLS_CONSTRUCTORS[initializer_cls] - return initializer(initializer_cls, elts) - except (KeyError, AttributeError): - node = EmptyNode() - node.object = value - return node - - -def is_from_decorator(node): - """Return True if the given node is the child of a decorator""" - parent = node.parent - while parent is not None: - if isinstance(parent, Decorators): - return True - parent = parent.parent - return False +# We cannot create a __all__ here because it would create a circular import +# Please remove astroid/scoped_nodes.py|astroid/node_classes.py in autoflake +# exclude when removing this file. +warnings.warn( + "The 'astroid.node_classes' module is deprecated and will be replaced by 'astroid.nodes' in astroid 3.0.0", + DeprecationWarning, +) diff --git a/astroid/nodes/__init__.py b/astroid/nodes/__init__.py new file mode 100644 index 00000000..d2101020 --- /dev/null +++ b/astroid/nodes/__init__.py @@ -0,0 +1,214 @@ +# Copyright (c) 2006-2011, 2013 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> +# Copyright (c) 2010 Daniel Harding <dharding@gmail.com> +# Copyright (c) 2014-2020 Claudiu Popa <pcmanticore@gmail.com> +# Copyright (c) 2014 Google, Inc. +# Copyright (c) 2015-2016 Ceridwen <ceridwenv@gmail.com> +# Copyright (c) 2016 Jared Garst <jgarst@users.noreply.github.com> +# Copyright (c) 2017 Ashley Whetter <ashley@awhetter.co.uk> +# Copyright (c) 2017 rr- <rr-@sakuya.pl> +# Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com> +# Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com> +# Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com> + +# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html +# For details: https://github.com/PyCQA/astroid/blob/master/LICENSE + +"""Every available node class. + +.. seealso:: + :doc:`ast documentation <green_tree_snakes:nodes>` + +All nodes inherit from :class:`~astroid.nodes.node_classes.NodeNG`. +""" + +# Nodes not present in the builtin ast module: DictUnpack, Unknown, and EvaluatedObject. + +from astroid.nodes.node_classes import ( # pylint: disable=redefined-builtin (Ellipsis) + CONST_CLS, + AnnAssign, + Arguments, + Assert, + Assign, + AssignAttr, + AssignName, + AsyncFor, + AsyncWith, + Attribute, + AugAssign, + Await, + BinOp, + BoolOp, + Break, + Call, + Compare, + Comprehension, + Const, + Continue, + Decorators, + DelAttr, + Delete, + DelName, + Dict, + DictUnpack, + Ellipsis, + EmptyNode, + EvaluatedObject, + ExceptHandler, + Expr, + ExtSlice, + For, + FormattedValue, + Global, + If, + IfExp, + Import, + ImportFrom, + Index, + JoinedStr, + Keyword, + List, + Match, + MatchAs, + MatchCase, + MatchClass, + MatchMapping, + MatchOr, + MatchSequence, + MatchSingleton, + MatchStar, + MatchValue, + Name, + NamedExpr, + NodeNG, + Nonlocal, + Pass, + Raise, + Return, + Set, + Slice, + Starred, + Subscript, + TryExcept, + TryFinally, + Tuple, + UnaryOp, + Unknown, + While, + With, + Yield, + YieldFrom, + are_exclusive, + const_factory, + unpack_infer, +) +from astroid.nodes.scoped_nodes import ( + AsyncFunctionDef, + ClassDef, + ComprehensionScope, + DictComp, + FunctionDef, + GeneratorExp, + Lambda, + ListComp, + Module, + SetComp, + builtin_lookup, + function_to_method, +) + +ALL_NODE_CLASSES = ( + AnnAssign, + Arguments, + Assert, + Assign, + AssignAttr, + AssignName, + AsyncFor, + AsyncFunctionDef, + AsyncWith, + Attribute, + AugAssign, + Await, + BinOp, + BoolOp, + Break, + Call, + ClassDef, + Compare, + Comprehension, + ComprehensionScope, + Const, + const_factory, + Continue, + Decorators, + DelAttr, + Delete, + DelName, + Dict, + DictComp, + DictUnpack, + Ellipsis, + EmptyNode, + EvaluatedObject, + ExceptHandler, + Expr, + ExtSlice, + For, + FormattedValue, + FunctionDef, + GeneratorExp, + Global, + If, + IfExp, + Import, + ImportFrom, + Index, + JoinedStr, + Keyword, + Lambda, + List, + ListComp, + Match, + MatchAs, + MatchCase, + MatchClass, + MatchMapping, + MatchOr, + MatchSequence, + MatchSingleton, + MatchStar, + MatchValue, + Module, + Name, + NamedExpr, + NodeNG, + Nonlocal, + Pass, + Raise, + Return, + Set, + SetComp, + Slice, + Starred, + Subscript, + TryExcept, + TryFinally, + Tuple, + UnaryOp, + Unknown, + While, + With, + Yield, + YieldFrom, +) + +# Can't create a proper __all__ with string because of a cyclic import for ClassDef +__all__ = [ + "CONST_CLS", + "builtin_lookup", + "are_exclusive", + "const_factory", + "unpack_infer", + "function_to_method", +] +__all__ += [c.__name__ for c in ALL_NODE_CLASSES] diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py new file mode 100644 index 00000000..e087b91b --- /dev/null +++ b/astroid/nodes/node_classes.py @@ -0,0 +1,5343 @@ +# Copyright (c) 2009-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> +# Copyright (c) 2010 Daniel Harding <dharding@gmail.com> +# Copyright (c) 2012 FELD Boris <lothiraldan@gmail.com> +# Copyright (c) 2013-2014 Google, Inc. +# Copyright (c) 2014-2021 Claudiu Popa <pcmanticore@gmail.com> +# Copyright (c) 2014 Eevee (Alex Munroe) <amunroe@yelp.com> +# Copyright (c) 2015-2016 Ceridwen <ceridwenv@gmail.com> +# Copyright (c) 2015 Florian Bruhin <me@the-compiler.org> +# Copyright (c) 2016-2017 Derek Gustafson <degustaf@gmail.com> +# Copyright (c) 2016 Jared Garst <jgarst@users.noreply.github.com> +# Copyright (c) 2016 Jakub Wilk <jwilk@jwilk.net> +# Copyright (c) 2016 Dave Baum <dbaum@google.com> +# Copyright (c) 2017-2020 Ashley Whetter <ashley@awhetter.co.uk> +# Copyright (c) 2017, 2019 Łukasz Rogalski <rogalski.91@gmail.com> +# Copyright (c) 2017 rr- <rr-@sakuya.pl> +# Copyright (c) 2018-2021 hippo91 <guillaume.peillex@gmail.com> +# Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com> +# Copyright (c) 2018 Nick Drozd <nicholasdrozd@gmail.com> +# Copyright (c) 2018 Ville Skyttä <ville.skytta@iki.fi> +# Copyright (c) 2018 brendanator <brendan.maginnis@gmail.com> +# Copyright (c) 2018 HoverHell <hoverhell@gmail.com> +# Copyright (c) 2019 kavins14 <kavin.singh@mail.utoronto.ca> +# Copyright (c) 2019 kavins14 <kavinsingh@hotmail.com> +# Copyright (c) 2020 Raphael Gaschignard <raphael@rtpg.co> +# Copyright (c) 2020 Bryce Guinta <bryce.guinta@protonmail.com> +# Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com> +# Copyright (c) 2021 David Liu <david@cs.toronto.edu> +# Copyright (c) 2021 Alphadelta14 <alpha@alphaservcomputing.solutions> +# Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com> +# Copyright (c) 2021 Andrew Haigh <hello@nelf.in> +# Copyright (c) 2021 Federico Bond <federicobond@gmail.com> + +# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html +# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE + +"""Module for some node classes. More nodes in scoped_nodes.py""" + +import abc +import itertools +import pprint +import sys +import typing +from functools import lru_cache +from functools import singledispatch as _singledispatch +from typing import Callable, ClassVar, Generator, Optional + +from astroid import as_string, bases +from astroid import context as contextmod +from astroid import decorators, mixins, util +from astroid.const import BUILTINS, Context +from astroid.exceptions import ( + AstroidError, + AstroidIndexError, + AstroidTypeError, + InferenceError, + NoDefault, + UseInferenceDefault, +) +from astroid.manager import AstroidManager + +if sys.version_info >= (3, 8): + from typing import Literal +else: + from typing_extensions import Literal + + +def _is_const(value): + return isinstance(value, tuple(CONST_CLS)) + + +@decorators.raise_if_nothing_inferred +def unpack_infer(stmt, context=None): + """recursively generate nodes inferred by the given statement. + If the inferred value is a list or a tuple, recurse on the elements + """ + if isinstance(stmt, (List, Tuple)): + for elt in stmt.elts: + if elt is util.Uninferable: + yield elt + continue + yield from unpack_infer(elt, context) + return dict(node=stmt, context=context) + # if inferred is a final node, return it and stop + inferred = next(stmt.infer(context), util.Uninferable) + if inferred is stmt: + yield inferred + return dict(node=stmt, context=context) + # else, infer recursively, except Uninferable object that should be returned as is + for inferred in stmt.infer(context): + if inferred is util.Uninferable: + yield inferred + else: + yield from unpack_infer(inferred, context) + + return dict(node=stmt, context=context) + + +def are_exclusive(stmt1, stmt2, exceptions: Optional[typing.List[str]] = None) -> bool: + """return true if the two given statements are mutually exclusive + + `exceptions` may be a list of exception names. If specified, discard If + branches and check one of the statement is in an exception handler catching + one of the given exceptions. + + algorithm : + 1) index stmt1's parents + 2) climb among stmt2's parents until we find a common parent + 3) if the common parent is a If or TryExcept statement, look if nodes are + in exclusive branches + """ + # index stmt1's parents + stmt1_parents = {} + children = {} + node = stmt1.parent + previous = stmt1 + while node: + stmt1_parents[node] = 1 + children[node] = previous + previous = node + node = node.parent + # climb among stmt2's parents until we find a common parent + node = stmt2.parent + previous = stmt2 + while node: + if node in stmt1_parents: + # if the common parent is a If or TryExcept statement, look if + # nodes are in exclusive branches + if isinstance(node, If) and exceptions is None: + if ( + node.locate_child(previous)[1] + is not node.locate_child(children[node])[1] + ): + return True + elif isinstance(node, TryExcept): + c2attr, c2node = node.locate_child(previous) + c1attr, c1node = node.locate_child(children[node]) + if c1node is not c2node: + first_in_body_caught_by_handlers = ( + c2attr == "handlers" + and c1attr == "body" + and previous.catch(exceptions) + ) + second_in_body_caught_by_handlers = ( + c2attr == "body" + and c1attr == "handlers" + and children[node].catch(exceptions) + ) + first_in_else_other_in_handlers = ( + c2attr == "handlers" and c1attr == "orelse" + ) + second_in_else_other_in_handlers = ( + c2attr == "orelse" and c1attr == "handlers" + ) + if any( + ( + first_in_body_caught_by_handlers, + second_in_body_caught_by_handlers, + first_in_else_other_in_handlers, + second_in_else_other_in_handlers, + ) + ): + return True + elif c2attr == "handlers" and c1attr == "handlers": + return previous is not children[node] + return False + previous = node + node = node.parent + return False + + +# getitem() helpers. + +_SLICE_SENTINEL = object() + + +def _slice_value(index, context=None): + """Get the value of the given slice index.""" + + if isinstance(index, Const): + if isinstance(index.value, (int, type(None))): + return index.value + elif index is None: + return None + else: + # Try to infer what the index actually is. + # Since we can't return all the possible values, + # we'll stop at the first possible value. + try: + inferred = next(index.infer(context=context)) + except (InferenceError, StopIteration): + pass + else: + if isinstance(inferred, Const): + if isinstance(inferred.value, (int, type(None))): + return inferred.value + + # Use a sentinel, because None can be a valid + # value that this function can return, + # as it is the case for unspecified bounds. + return _SLICE_SENTINEL + + +def _infer_slice(node, context=None): + lower = _slice_value(node.lower, context) + upper = _slice_value(node.upper, context) + step = _slice_value(node.step, context) + if all(elem is not _SLICE_SENTINEL for elem in (lower, upper, step)): + return slice(lower, upper, step) + + raise AstroidTypeError( + message="Could not infer slice used in subscript", + node=node, + index=node.parent, + context=context, + ) + + +def _container_getitem(instance, elts, index, context=None): + """Get a slice or an item, using the given *index*, for the given sequence.""" + try: + if isinstance(index, Slice): + index_slice = _infer_slice(index, context=context) + new_cls = instance.__class__() + new_cls.elts = elts[index_slice] + new_cls.parent = instance.parent + return new_cls + if isinstance(index, Const): + return elts[index.value] + except IndexError as exc: + raise AstroidIndexError( + message="Index {index!s} out of range", + node=instance, + index=index, + context=context, + ) from exc + except TypeError as exc: + raise AstroidTypeError( + message="Type error {error!r}", node=instance, index=index, context=context + ) from exc + + raise AstroidTypeError("Could not use %s as subscript index" % index) + + +OP_PRECEDENCE = { + op: precedence + for precedence, ops in enumerate( + [ + ["Lambda"], # lambda x: x + 1 + ["IfExp"], # 1 if True else 2 + ["or"], + ["and"], + ["not"], + ["Compare"], # in, not in, is, is not, <, <=, >, >=, !=, == + ["|"], + ["^"], + ["&"], + ["<<", ">>"], + ["+", "-"], + ["*", "@", "/", "//", "%"], + ["UnaryOp"], # +, -, ~ + ["**"], + ["Await"], + ] + ) + for op in ops +} + + +class NodeNG: + """A node of the new Abstract Syntax Tree (AST). + + This is the base class for all Astroid node classes. + """ + + is_statement: ClassVar[bool] = False + """Whether this node indicates a statement.""" + optional_assign: ClassVar[ + bool + ] = False # True for For (and for Comprehension if py <3.0) + """Whether this node optionally assigns a variable. + + This is for loop assignments because loop won't necessarily perform an + assignment if the loop has no iterations. + This is also the case from comprehensions in Python 2. + """ + is_function: ClassVar[bool] = False # True for FunctionDef nodes + """Whether this node indicates a function.""" + is_lambda: ClassVar[bool] = False + + # Attributes below are set by the builder module or by raw factories + _astroid_fields: ClassVar[typing.Tuple[str, ...]] = () + """Node attributes that contain child nodes. + + This is redefined in most concrete classes. + """ + _other_fields: ClassVar[typing.Tuple[str, ...]] = () + """Node attributes that do not contain child nodes.""" + _other_other_fields: ClassVar[typing.Tuple[str, ...]] = () + """Attributes that contain AST-dependent fields.""" + # instance specific inference function infer(node, context) + _explicit_inference = None + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional["NodeNG"] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.lineno: Optional[int] = lineno + """The line that this node appears on in the source code.""" + + self.col_offset: Optional[int] = col_offset + """The column that this node appears on in the source code.""" + + self.parent: Optional["NodeNG"] = parent + """The parent node in the syntax tree.""" + + def infer(self, context=None, **kwargs): + """Get a generator of the inferred values. + + This is the main entry point to the inference system. + + .. seealso:: :ref:`inference` + + If the instance has some explicit inference function set, it will be + called instead of the default interface. + + :returns: The inferred values. + :rtype: iterable + """ + if context is not None: + context = context.extra_context.get(self, context) + if self._explicit_inference is not None: + # explicit_inference is not bound, give it self explicitly + try: + # pylint: disable=not-callable + results = tuple(self._explicit_inference(self, context, **kwargs)) + if context is not None: + context.nodes_inferred += len(results) + yield from results + return + except UseInferenceDefault: + pass + + if not context: + # nodes_inferred? + yield from self._infer(context, **kwargs) + return + + key = (self, context.lookupname, context.callcontext, context.boundnode) + if key in context.inferred: + yield from context.inferred[key] + return + + generator = self._infer(context, **kwargs) + results = [] + + # Limit inference amount to help with performance issues with + # exponentially exploding possible results. + limit = AstroidManager().max_inferable_values + for i, result in enumerate(generator): + if i >= limit or (context.nodes_inferred > context.max_inferred): + yield util.Uninferable + break + results.append(result) + yield result + context.nodes_inferred += 1 + + # Cache generated results for subsequent inferences of the + # same node using the same context + context.inferred[key] = tuple(results) + return + + def _repr_name(self): + """Get a name for nice representation. + + This is either :attr:`name`, :attr:`attrname`, or the empty string. + + :returns: The nice name. + :rtype: str + """ + if all(name not in self._astroid_fields for name in ("name", "attrname")): + return getattr(self, "name", "") or getattr(self, "attrname", "") + return "" + + def __str__(self): + rname = self._repr_name() + cname = type(self).__name__ + if rname: + string = "%(cname)s.%(rname)s(%(fields)s)" + alignment = len(cname) + len(rname) + 2 + else: + string = "%(cname)s(%(fields)s)" + alignment = len(cname) + 1 + result = [] + for field in self._other_fields + self._astroid_fields: + value = getattr(self, field) + width = 80 - len(field) - alignment + lines = pprint.pformat(value, indent=2, width=width).splitlines(True) + + inner = [lines[0]] + for line in lines[1:]: + inner.append(" " * alignment + line) + result.append("{}={}".format(field, "".join(inner))) + + return string % { + "cname": cname, + "rname": rname, + "fields": (",\n" + " " * alignment).join(result), + } + + def __repr__(self): + rname = self._repr_name() + if rname: + string = "<%(cname)s.%(rname)s l.%(lineno)s at 0x%(id)x>" + else: + string = "<%(cname)s l.%(lineno)s at 0x%(id)x>" + return string % { + "cname": type(self).__name__, + "rname": rname, + "lineno": self.fromlineno, + "id": id(self), + } + + def accept(self, visitor): + """Visit this node using the given visitor.""" + func = getattr(visitor, "visit_" + self.__class__.__name__.lower()) + return func(self) + + def get_children(self): + """Get the child nodes below this node. + + :returns: The children. + :rtype: iterable(NodeNG) + """ + for field in self._astroid_fields: + attr = getattr(self, field) + if attr is None: + continue + if isinstance(attr, (list, tuple)): + yield from attr + else: + yield attr + yield from () + + def last_child(self): # -> Optional["NodeNG"] + """An optimized version of list(get_children())[-1]""" + for field in self._astroid_fields[::-1]: + attr = getattr(self, field) + if not attr: # None or empty listy / tuple + continue + if isinstance(attr, (list, tuple)): + return attr[-1] + return attr + return None + + def parent_of(self, node): + """Check if this node is the parent of the given node. + + :param node: The node to check if it is the child. + :type node: NodeNG + + :returns: True if this node is the parent of the given node, + False otherwise. + :rtype: bool + """ + parent = node.parent + while parent is not None: + if self is parent: + return True + parent = parent.parent + return False + + def statement(self): + """The first parent node, including self, marked as statement node. + + :returns: The first parent statement. + :rtype: NodeNG + """ + if self.is_statement: + return self + return self.parent.statement() + + def frame(self): + """The first parent frame node. + + A frame node is a :class:`Module`, :class:`FunctionDef`, + or :class:`ClassDef`. + + :returns: The first parent frame node. + :rtype: Module or FunctionDef or ClassDef + """ + return self.parent.frame() + + def scope(self): + """The first parent node defining a new scope. + + :returns: The first parent scope node. + :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr + """ + if self.parent: + return self.parent.scope() + return None + + def root(self): + """Return the root node of the syntax tree. + + :returns: The root node. + :rtype: Module + """ + if self.parent: + return self.parent.root() + return self + + def child_sequence(self, child): + """Search for the sequence that contains this child. + + :param child: The child node to search sequences for. + :type child: NodeNG + + :returns: The sequence containing the given child node. + :rtype: iterable(NodeNG) + + :raises AstroidError: If no sequence could be found that contains + the given child. + """ + for field in self._astroid_fields: + node_or_sequence = getattr(self, field) + if node_or_sequence is child: + return [node_or_sequence] + # /!\ compiler.ast Nodes have an __iter__ walking over child nodes + if ( + isinstance(node_or_sequence, (tuple, list)) + and child in node_or_sequence + ): + return node_or_sequence + + msg = "Could not find %s in %s's children" + raise AstroidError(msg % (repr(child), repr(self))) + + def locate_child(self, child): + """Find the field of this node that contains the given child. + + :param child: The child node to search fields for. + :type child: NodeNG + + :returns: A tuple of the name of the field that contains the child, + and the sequence or node that contains the child node. + :rtype: tuple(str, iterable(NodeNG) or NodeNG) + + :raises AstroidError: If no field could be found that contains + the given child. + """ + for field in self._astroid_fields: + node_or_sequence = getattr(self, field) + # /!\ compiler.ast Nodes have an __iter__ walking over child nodes + if child is node_or_sequence: + return field, child + if ( + isinstance(node_or_sequence, (tuple, list)) + and child in node_or_sequence + ): + return field, node_or_sequence + msg = "Could not find %s in %s's children" + raise AstroidError(msg % (repr(child), repr(self))) + + # FIXME : should we merge child_sequence and locate_child ? locate_child + # is only used in are_exclusive, child_sequence one time in pylint. + + def next_sibling(self): + """The next sibling statement node. + + :returns: The next sibling statement node. + :rtype: NodeNG or None + """ + return self.parent.next_sibling() + + def previous_sibling(self): + """The previous sibling statement. + + :returns: The previous sibling statement node. + :rtype: NodeNG or None + """ + return self.parent.previous_sibling() + + # these are lazy because they're relatively expensive to compute for every + # single node, and they rarely get looked at + + @decorators.cachedproperty + def fromlineno(self) -> Optional[int]: + """The first line that this node appears on in the source code.""" + if self.lineno is None: + return self._fixed_source_line() + return self.lineno + + @decorators.cachedproperty + def tolineno(self) -> Optional[int]: + """The last line that this node appears on in the source code.""" + if not self._astroid_fields: + # can't have children + last_child = None + else: + last_child = self.last_child() + if last_child is None: + return self.fromlineno + + return last_child.tolineno + + def _fixed_source_line(self) -> Optional[int]: + """Attempt to find the line that this node appears on. + + We need this method since not all nodes have :attr:`lineno` set. + """ + line = self.lineno + _node = self + try: + while line is None: + _node = next(_node.get_children()) + line = _node.lineno + except StopIteration: + _node = self.parent + while _node and line is None: + line = _node.lineno + _node = _node.parent + return line + + def block_range(self, lineno): + """Get a range from the given line number to where this node ends. + + :param lineno: The line number to start the range at. + :type lineno: int + + :returns: The range of line numbers that this node belongs to, + starting at the given line number. + :rtype: tuple(int, int or None) + """ + return lineno, self.tolineno + + def set_local(self, name, stmt): + """Define that the given name is declared in the given statement node. + + This definition is stored on the parent scope node. + + .. seealso:: :meth:`scope` + + :param name: The name that is being defined. + :type name: str + + :param stmt: The statement that defines the given name. + :type stmt: NodeNG + """ + self.parent.set_local(name, stmt) + + def nodes_of_class(self, klass, skip_klass=None): + """Get the nodes (including this one or below) of the given types. + + :param klass: The types of node to search for. + :type klass: builtins.type or tuple(builtins.type) + + :param skip_klass: The types of node to ignore. This is useful to ignore + subclasses of :attr:`klass`. + :type skip_klass: builtins.type or tuple(builtins.type) + + :returns: The node of the given types. + :rtype: iterable(NodeNG) + """ + if isinstance(self, klass): + yield self + + if skip_klass is None: + for child_node in self.get_children(): + yield from child_node.nodes_of_class(klass, skip_klass) + + return + + for child_node in self.get_children(): + if isinstance(child_node, skip_klass): + continue + yield from child_node.nodes_of_class(klass, skip_klass) + + @decorators.cached + def _get_assign_nodes(self): + return [] + + def _get_name_nodes(self): + for child_node in self.get_children(): + yield from child_node._get_name_nodes() + + def _get_return_nodes_skip_functions(self): + yield from () + + def _get_yield_nodes_skip_lambdas(self): + yield from () + + def _infer_name(self, frame, name): + # overridden for ImportFrom, Import, Global, TryExcept and Arguments + pass + + def _infer(self, context=None): + """we don't know how to resolve a statement by default""" + # this method is overridden by most concrete classes + raise InferenceError( + "No inference function for {node!r}.", node=self, context=context + ) + + def inferred(self): + """Get a list of the inferred values. + + .. seealso:: :ref:`inference` + + :returns: The inferred values. + :rtype: list + """ + return list(self.infer()) + + def instantiate_class(self): + """Instantiate an instance of the defined class. + + .. note:: + + On anything other than a :class:`ClassDef` this will return self. + + :returns: An instance of the defined class. + :rtype: object + """ + return self + + def has_base(self, node): + """Check if this node inherits from the given type. + + :param node: The node defining the base to look for. + Usually this is a :class:`Name` node. + :type node: NodeNG + """ + return False + + def callable(self): + """Whether this node defines something that is callable. + + :returns: True if this defines something that is callable, + False otherwise. + :rtype: bool + """ + return False + + def eq(self, value): + return False + + def as_string(self): + """Get the source code that this node represents. + + :returns: The source code. + :rtype: str + """ + return as_string.to_code(self) + + def repr_tree( + self, + ids=False, + include_linenos=False, + ast_state=False, + indent=" ", + max_depth=0, + max_width=80, + ) -> str: + """Get a string representation of the AST from this node. + + :param ids: If true, includes the ids with the node type names. + :type ids: bool + + :param include_linenos: If true, includes the line numbers and + column offsets. + :type include_linenos: bool + + :param ast_state: If true, includes information derived from + the whole AST like local and global variables. + :type ast_state: bool + + :param indent: A string to use to indent the output string. + :type indent: str + + :param max_depth: If set to a positive integer, won't return + nodes deeper than max_depth in the string. + :type max_depth: int + + :param max_width: Attempt to format the output string to stay + within this number of characters, but can exceed it under some + circumstances. Only positive integer values are valid, the default is 80. + :type max_width: int + + :returns: The string representation of the AST. + :rtype: str + """ + + @_singledispatch + def _repr_tree(node, result, done, cur_indent="", depth=1): + """Outputs a representation of a non-tuple/list, non-node that's + contained within an AST, including strings. + """ + lines = pprint.pformat( + node, width=max(max_width - len(cur_indent), 1) + ).splitlines(True) + result.append(lines[0]) + result.extend([cur_indent + line for line in lines[1:]]) + return len(lines) != 1 + + # pylint: disable=unused-variable,useless-suppression; doesn't understand singledispatch + @_repr_tree.register(tuple) + @_repr_tree.register(list) + def _repr_seq(node, result, done, cur_indent="", depth=1): + """Outputs a representation of a sequence that's contained within an AST.""" + cur_indent += indent + result.append("[") + if not node: + broken = False + elif len(node) == 1: + broken = _repr_tree(node[0], result, done, cur_indent, depth) + elif len(node) == 2: + broken = _repr_tree(node[0], result, done, cur_indent, depth) + if not broken: + result.append(", ") + else: + result.append(",\n") + result.append(cur_indent) + broken = _repr_tree(node[1], result, done, cur_indent, depth) or broken + else: + result.append("\n") + result.append(cur_indent) + for child in node[:-1]: + _repr_tree(child, result, done, cur_indent, depth) + result.append(",\n") + result.append(cur_indent) + _repr_tree(node[-1], result, done, cur_indent, depth) + broken = True + result.append("]") + return broken + + # pylint: disable=unused-variable,useless-suppression; doesn't understand singledispatch + @_repr_tree.register(NodeNG) + def _repr_node(node, result, done, cur_indent="", depth=1): + """Outputs a strings representation of an astroid node.""" + if node in done: + result.append( + indent + + "<Recursion on {} with id={}".format( + type(node).__name__, id(node) + ) + ) + return False + done.add(node) + + if max_depth and depth > max_depth: + result.append("...") + return False + depth += 1 + cur_indent += indent + if ids: + result.append(f"{type(node).__name__}<0x{id(node):x}>(\n") + else: + result.append("%s(" % type(node).__name__) + fields = [] + if include_linenos: + fields.extend(("lineno", "col_offset")) + fields.extend(node._other_fields) + fields.extend(node._astroid_fields) + if ast_state: + fields.extend(node._other_other_fields) + if not fields: + broken = False + elif len(fields) == 1: + result.append("%s=" % fields[0]) + broken = _repr_tree( + getattr(node, fields[0]), result, done, cur_indent, depth + ) + else: + result.append("\n") + result.append(cur_indent) + for field in fields[:-1]: + result.append("%s=" % field) + _repr_tree(getattr(node, field), result, done, cur_indent, depth) + result.append(",\n") + result.append(cur_indent) + result.append("%s=" % fields[-1]) + _repr_tree(getattr(node, fields[-1]), result, done, cur_indent, depth) + broken = True + result.append(")") + return broken + + result = [] + _repr_tree(self, result, set()) + return "".join(result) + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + The boolean value of a node can have three + possible values: + + * False: For instance, empty data structures, + False, empty strings, instances which return + explicitly False from the __nonzero__ / __bool__ + method. + * True: Most of constructs are True by default: + classes, functions, modules etc + * Uninferable: The inference engine is uncertain of the + node's value. + + :returns: The boolean value of this node. + :rtype: bool or Uninferable + """ + return util.Uninferable + + def op_precedence(self): + # Look up by class name or default to highest precedence + return OP_PRECEDENCE.get(self.__class__.__name__, len(OP_PRECEDENCE)) + + def op_left_associative(self): + # Everything is left associative except `**` and IfExp + return True + + +class Statement(NodeNG): + """Statement node adding a few attributes""" + + is_statement = True + """Whether this node indicates a statement.""" + + def next_sibling(self): + """The next sibling statement node. + + :returns: The next sibling statement node. + :rtype: NodeNG or None + """ + stmts = self.parent.child_sequence(self) + index = stmts.index(self) + try: + return stmts[index + 1] + except IndexError: + return None + + def previous_sibling(self): + """The previous sibling statement. + + :returns: The previous sibling statement node. + :rtype: NodeNG or None + """ + stmts = self.parent.child_sequence(self) + index = stmts.index(self) + if index >= 1: + return stmts[index - 1] + return None + + +class _BaseContainer( + mixins.ParentAssignTypeMixin, NodeNG, bases.Instance, metaclass=abc.ABCMeta +): + """Base class for Set, FrozenSet, Tuple and List.""" + + _astroid_fields = ("elts",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.elts: typing.List[NodeNG] = [] + """The elements in the node.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, elts: typing.List[NodeNG]) -> None: + """Do some setup after initialisation. + + :param elts: The list of elements the that node contains. + """ + self.elts = elts + + @classmethod + def from_elements(cls, elts=None): + """Create a node of this type from the given list of elements. + + :param elts: The list of elements that the node should contain. + :type elts: list(NodeNG) + + :returns: A new node containing the given elements. + :rtype: NodeNG + """ + node = cls() + if elts is None: + node.elts = [] + else: + node.elts = [const_factory(e) if _is_const(e) else e for e in elts] + return node + + def itered(self): + """An iterator over the elements this node contains. + + :returns: The contents of this node. + :rtype: iterable(NodeNG) + """ + return self.elts + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + :rtype: bool or Uninferable + """ + return bool(self.elts) + + @abc.abstractmethod + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + + def get_children(self): + yield from self.elts + + +class LookupMixIn: + """Mixin to look up a name in the right scope.""" + + @lru_cache(maxsize=None) + def lookup(self, name): + """Lookup where the given variable is assigned. + + The lookup starts from self's scope. If self is not a frame itself + and the name is found in the inner frame locals, statements will be + filtered to remove ignorable statements according to self's location. + + :param name: The name of the variable to find assignments for. + :type name: str + + :returns: The scope node and the list of assignments associated to the + given name according to the scope where it has been found (locals, + globals or builtin). + :rtype: tuple(str, list(NodeNG)) + """ + return self.scope().scope_lookup(self, name) + + def ilookup(self, name): + """Lookup the inferred values of the given variable. + + :param name: The variable name to find values for. + :type name: str + + :returns: The inferred values of the statements returned from + :meth:`lookup`. + :rtype: iterable + """ + frame, stmts = self.lookup(name) + context = contextmod.InferenceContext() + return bases._infer_stmts(stmts, context, frame) + + def _get_filtered_node_statements(self, nodes): + statements = [(node, node.statement()) for node in nodes] + # Next we check if we have ExceptHandlers that are parent + # of the underlying variable, in which case the last one survives + if len(statements) > 1 and all( + isinstance(stmt, ExceptHandler) for _, stmt in statements + ): + statements = [ + (node, stmt) for node, stmt in statements if stmt.parent_of(self) + ] + return statements + + def _filter_stmts(self, stmts, frame, offset): + """Filter the given list of statements to remove ignorable statements. + + If self is not a frame itself and the name is found in the inner + frame locals, statements will be filtered to remove ignorable + statements according to self's location. + + :param stmts: The statements to filter. + :type stmts: list(NodeNG) + + :param frame: The frame that all of the given statements belong to. + :type frame: NodeNG + + :param offset: The line offset to filter statements up to. + :type offset: int + + :returns: The filtered statements. + :rtype: list(NodeNG) + """ + # if offset == -1, my actual frame is not the inner frame but its parent + # + # class A(B): pass + # + # we need this to resolve B correctly + if offset == -1: + myframe = self.frame().parent.frame() + else: + myframe = self.frame() + # If the frame of this node is the same as the statement + # of this node, then the node is part of a class or + # a function definition and the frame of this node should be the + # the upper frame, not the frame of the definition. + # For more information why this is important, + # see Pylint issue #295. + # For example, for 'b', the statement is the same + # as the frame / scope: + # + # def test(b=1): + # ... + + if self.statement() is myframe and myframe.parent: + myframe = myframe.parent.frame() + mystmt = self.statement() + # line filtering if we are in the same frame + # + # take care node may be missing lineno information (this is the case for + # nodes inserted for living objects) + if myframe is frame and mystmt.fromlineno is not None: + assert mystmt.fromlineno is not None, mystmt + mylineno = mystmt.fromlineno + offset + else: + # disabling lineno filtering + mylineno = 0 + + _stmts = [] + _stmt_parents = [] + statements = self._get_filtered_node_statements(stmts) + for node, stmt in statements: + # line filtering is on and we have reached our location, break + if stmt.fromlineno and stmt.fromlineno > mylineno > 0: + break + # Ignore decorators with the same name as the + # decorated function + # Fixes issue #375 + if mystmt is stmt and is_from_decorator(self): + continue + assert hasattr(node, "assign_type"), ( + node, + node.scope(), + node.scope().locals, + ) + assign_type = node.assign_type() + if node.has_base(self): + break + + _stmts, done = assign_type._get_filtered_stmts(self, node, _stmts, mystmt) + if done: + break + + optional_assign = assign_type.optional_assign + if optional_assign and assign_type.parent_of(self): + # we are inside a loop, loop var assignment is hiding previous + # assignment + _stmts = [node] + _stmt_parents = [stmt.parent] + continue + + if isinstance(assign_type, NamedExpr): + _stmts = [node] + continue + + # XXX comment various branches below!!! + try: + pindex = _stmt_parents.index(stmt.parent) + except ValueError: + pass + else: + # we got a parent index, this means the currently visited node + # is at the same block level as a previously visited node + if _stmts[pindex].assign_type().parent_of(assign_type): + # both statements are not at the same block level + continue + # if currently visited node is following previously considered + # assignment and both are not exclusive, we can drop the + # previous one. For instance in the following code :: + # + # if a: + # x = 1 + # else: + # x = 2 + # print x + # + # we can't remove neither x = 1 nor x = 2 when looking for 'x' + # of 'print x'; while in the following :: + # + # x = 1 + # x = 2 + # print x + # + # we can remove x = 1 when we see x = 2 + # + # moreover, on loop assignment types, assignment won't + # necessarily be done if the loop has no iteration, so we don't + # want to clear previous assignments if any (hence the test on + # optional_assign) + if not (optional_assign or are_exclusive(_stmts[pindex], node)): + del _stmt_parents[pindex] + del _stmts[pindex] + + # If self and node are exclusive, then we can ignore node + if are_exclusive(self, node): + continue + + # An AssignName node overrides previous assignments if: + # 1. node's statement always assigns + # 2. node and self are in the same block (i.e., has the same parent as self) + if isinstance(node, AssignName): + if isinstance(stmt, ExceptHandler): + # If node's statement is an ExceptHandler, then it is the variable + # bound to the caught exception. If self is not contained within + # the exception handler block, node should override previous assignments; + # otherwise, node should be ignored, as an exception variable + # is local to the handler block. + if stmt.parent_of(self): + _stmts = [] + _stmt_parents = [] + else: + continue + elif not optional_assign and stmt.parent is mystmt.parent: + _stmts = [] + _stmt_parents = [] + elif isinstance(node, DelName): + # Remove all previously stored assignments + _stmts = [] + _stmt_parents = [] + continue + # Add the new assignment + _stmts.append(node) + if isinstance(node, Arguments) or isinstance(node.parent, Arguments): + # Special case for _stmt_parents when node is a function parameter; + # in this case, stmt is the enclosing FunctionDef, which is what we + # want to add to _stmt_parents, not stmt.parent. This case occurs when + # node is an Arguments node (representing varargs or kwargs parameter), + # and when node.parent is an Arguments node (other parameters). + # See issue #180. + _stmt_parents.append(stmt) + else: + _stmt_parents.append(stmt.parent) + return _stmts + + +# Name classes + + +class AssignName( + mixins.NoChildrenMixin, LookupMixIn, mixins.ParentAssignTypeMixin, NodeNG +): + """Variation of :class:`ast.Assign` representing assignment to a name. + + An :class:`AssignName` is the name of something that is assigned to. + This includes variables defined in a function signature or in a loop. + + >>> node = astroid.extract_node('variable = range(10)') + >>> node + <Assign l.1 at 0x7effe1db8550> + >>> list(node.get_children()) + [<AssignName.variable l.1 at 0x7effe1db8748>, <Call l.1 at 0x7effe1db8630>] + >>> list(node.get_children())[0].as_string() + 'variable' + """ + + _other_fields = ("name",) + + def __init__( + self, + name: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param name: The name that is assigned to. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.name: Optional[str] = name + """The name that is assigned to.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + +class DelName( + mixins.NoChildrenMixin, LookupMixIn, mixins.ParentAssignTypeMixin, NodeNG +): + """Variation of :class:`ast.Delete` representing deletion of a name. + + A :class:`DelName` is the name of something that is deleted. + + >>> node = astroid.extract_node("del variable #@") + >>> list(node.get_children()) + [<DelName.variable l.1 at 0x7effe1da4d30>] + >>> list(node.get_children())[0].as_string() + 'variable' + """ + + _other_fields = ("name",) + + def __init__( + self, + name: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param name: The name that is being deleted. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.name: Optional[str] = name + """The name that is being deleted.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + +class Name(mixins.NoChildrenMixin, LookupMixIn, NodeNG): + """Class representing an :class:`ast.Name` node. + + A :class:`Name` node is something that is named, but not covered by + :class:`AssignName` or :class:`DelName`. + + >>> node = astroid.extract_node('range(10)') + >>> node + <Call l.1 at 0x7effe1db8710> + >>> list(node.get_children()) + [<Name.range l.1 at 0x7effe1db86a0>, <Const.int l.1 at 0x7effe1db8518>] + >>> list(node.get_children())[0].as_string() + 'range' + """ + + _other_fields = ("name",) + + def __init__( + self, + name: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param name: The name that this node refers to. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.name: Optional[str] = name + """The name that this node refers to.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def _get_name_nodes(self): + yield self + + for child_node in self.get_children(): + yield from child_node._get_name_nodes() + + +class Arguments(mixins.AssignTypeMixin, NodeNG): + """Class representing an :class:`ast.arguments` node. + + An :class:`Arguments` node represents that arguments in a + function definition. + + >>> node = astroid.extract_node('def foo(bar): pass') + >>> node + <FunctionDef.foo l.1 at 0x7effe1db8198> + >>> node.args + <Arguments l.1 at 0x7effe1db82e8> + """ + + # Python 3.4+ uses a different approach regarding annotations, + # each argument is a new class, _ast.arg, which exposes an + # 'annotation' attribute. In astroid though, arguments are exposed + # as is in the Arguments node and the only way to expose annotations + # is by using something similar with Python 3.3: + # - we expose 'varargannotation' and 'kwargannotation' of annotations + # of varargs and kwargs. + # - we expose 'annotation', a list with annotations for + # for each normal argument. If an argument doesn't have an + # annotation, its value will be None. + _astroid_fields = ( + "args", + "defaults", + "kwonlyargs", + "posonlyargs", + "posonlyargs_annotations", + "kw_defaults", + "annotations", + "varargannotation", + "kwargannotation", + "kwonlyargs_annotations", + "type_comment_args", + "type_comment_kwonlyargs", + "type_comment_posonlyargs", + ) + + _other_fields = ("vararg", "kwarg") + + def __init__( + self, + vararg: Optional[str] = None, + kwarg: Optional[str] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param vararg: The name of the variable length arguments. + + :param kwarg: The name of the variable length keyword arguments. + + :param parent: The parent node in the syntax tree. + """ + super().__init__(parent=parent) + + self.vararg: Optional[str] = vararg # can be None + """The name of the variable length arguments.""" + + self.kwarg: Optional[str] = kwarg # can be None + """The name of the variable length keyword arguments.""" + + self.args: typing.List[AssignName] + """The names of the required arguments.""" + + self.defaults: typing.List[NodeNG] + """The default values for arguments that can be passed positionally.""" + + self.kwonlyargs: typing.List[AssignName] + """The keyword arguments that cannot be passed positionally.""" + + self.posonlyargs: typing.List[AssignName] = [] + """The arguments that can only be passed positionally.""" + + self.kw_defaults: typing.List[Optional[NodeNG]] + """The default values for keyword arguments that cannot be passed positionally.""" + + self.annotations: typing.List[Optional[NodeNG]] + """The type annotations of arguments that can be passed positionally.""" + + self.posonlyargs_annotations: typing.List[Optional[NodeNG]] = [] + """The type annotations of arguments that can only be passed positionally.""" + + self.kwonlyargs_annotations: typing.List[Optional[NodeNG]] = [] + """The type annotations of arguments that cannot be passed positionally.""" + + self.type_comment_args: typing.List[Optional[NodeNG]] = [] + """The type annotation, passed by a type comment, of each argument. + + If an argument does not have a type comment, + the value for that argument will be None. + """ + + self.type_comment_kwonlyargs: typing.List[Optional[NodeNG]] = [] + """The type annotation, passed by a type comment, of each keyword only argument. + + If an argument does not have a type comment, + the value for that argument will be None. + """ + + self.type_comment_posonlyargs: typing.List[Optional[NodeNG]] = [] + """The type annotation, passed by a type comment, of each positional argument. + + If an argument does not have a type comment, + the value for that argument will be None. + """ + + self.varargannotation: Optional[NodeNG] = None # can be None + """The type annotation for the variable length arguments.""" + + self.kwargannotation: Optional[NodeNG] = None # can be None + """The type annotation for the variable length keyword arguments.""" + + # pylint: disable=too-many-arguments + def postinit( + self, + args: typing.List[AssignName], + defaults: typing.List[NodeNG], + kwonlyargs: typing.List[AssignName], + kw_defaults: typing.List[Optional[NodeNG]], + annotations: typing.List[Optional[NodeNG]], + posonlyargs: Optional[typing.List[AssignName]] = None, + kwonlyargs_annotations: Optional[typing.List[Optional[NodeNG]]] = None, + posonlyargs_annotations: Optional[typing.List[Optional[NodeNG]]] = None, + varargannotation: Optional[NodeNG] = None, + kwargannotation: Optional[NodeNG] = None, + type_comment_args: Optional[typing.List[Optional[NodeNG]]] = None, + type_comment_kwonlyargs: Optional[typing.List[Optional[NodeNG]]] = None, + type_comment_posonlyargs: Optional[typing.List[Optional[NodeNG]]] = None, + ) -> None: + """Do some setup after initialisation. + + :param args: The names of the required arguments. + + :param defaults: The default values for arguments that can be passed + positionally. + + :param kwonlyargs: The keyword arguments that cannot be passed + positionally. + + :param posonlyargs: The arguments that can only be passed + positionally. + + :param kw_defaults: The default values for keyword arguments that + cannot be passed positionally. + + :param annotations: The type annotations of arguments that can be + passed positionally. + + :param kwonlyargs_annotations: The type annotations of arguments that + cannot be passed positionally. This should always be passed in + Python 3. + + :param posonlyargs_annotations: The type annotations of arguments that + can only be passed positionally. This should always be passed in + Python 3. + + :param varargannotation: The type annotation for the variable length + arguments. + + :param kwargannotation: The type annotation for the variable length + keyword arguments. + + :param type_comment_args: The type annotation, + passed by a type comment, of each argument. + + :param type_comment_args: The type annotation, + passed by a type comment, of each keyword only argument. + + :param type_comment_args: The type annotation, + passed by a type comment, of each positional argument. + """ + self.args = args + self.defaults = defaults + self.kwonlyargs = kwonlyargs + if posonlyargs is not None: + self.posonlyargs = posonlyargs + self.kw_defaults = kw_defaults + self.annotations = annotations + if kwonlyargs_annotations is not None: + self.kwonlyargs_annotations = kwonlyargs_annotations + if posonlyargs_annotations is not None: + self.posonlyargs_annotations = posonlyargs_annotations + self.varargannotation = varargannotation + self.kwargannotation = kwargannotation + if type_comment_args is not None: + self.type_comment_args = type_comment_args + if type_comment_kwonlyargs is not None: + self.type_comment_kwonlyargs = type_comment_kwonlyargs + if type_comment_posonlyargs is not None: + self.type_comment_posonlyargs = type_comment_posonlyargs + + def _infer_name(self, frame, name): + if self.parent is frame: + return name + return None + + @decorators.cachedproperty + def fromlineno(self): + """The first line that this node appears on in the source code. + + :type: int or None + """ + lineno = super().fromlineno + return max(lineno, self.parent.fromlineno or 0) + + @decorators.cachedproperty + def arguments(self): + """Get all the arguments for this node, including positional only and positional and keyword""" + return list(itertools.chain((self.posonlyargs or ()), self.args or ())) + + def format_args(self): + """Get the arguments formatted as string. + + :returns: The formatted arguments. + :rtype: str + """ + result = [] + positional_only_defaults = [] + positional_or_keyword_defaults = self.defaults + if self.defaults: + args = self.args or [] + positional_or_keyword_defaults = self.defaults[-len(args) :] + positional_only_defaults = self.defaults[: len(self.defaults) - len(args)] + + if self.posonlyargs: + result.append( + _format_args( + self.posonlyargs, + positional_only_defaults, + self.posonlyargs_annotations, + ) + ) + result.append("/") + if self.args: + result.append( + _format_args( + self.args, + positional_or_keyword_defaults, + getattr(self, "annotations", None), + ) + ) + if self.vararg: + result.append("*%s" % self.vararg) + if self.kwonlyargs: + if not self.vararg: + result.append("*") + result.append( + _format_args( + self.kwonlyargs, self.kw_defaults, self.kwonlyargs_annotations + ) + ) + if self.kwarg: + result.append("**%s" % self.kwarg) + return ", ".join(result) + + def default_value(self, argname): + """Get the default value for an argument. + + :param argname: The name of the argument to get the default value for. + :type argname: str + + :raises NoDefault: If there is no default value defined for the + given argument. + """ + args = self.arguments + index = _find_arg(argname, args)[0] + if index is not None: + idx = index - (len(args) - len(self.defaults)) + if idx >= 0: + return self.defaults[idx] + index = _find_arg(argname, self.kwonlyargs)[0] + if index is not None and self.kw_defaults[index] is not None: + return self.kw_defaults[index] + raise NoDefault(func=self.parent, name=argname) + + def is_argument(self, name): + """Check if the given name is defined in the arguments. + + :param name: The name to check for. + :type name: str + + :returns: True if the given name is defined in the arguments, + False otherwise. + :rtype: bool + """ + if name == self.vararg: + return True + if name == self.kwarg: + return True + return ( + self.find_argname(name, rec=True)[1] is not None + or self.kwonlyargs + and _find_arg(name, self.kwonlyargs, rec=True)[1] is not None + ) + + def find_argname(self, argname, rec=False): + """Get the index and :class:`AssignName` node for given name. + + :param argname: The name of the argument to search for. + :type argname: str + + :param rec: Whether or not to include arguments in unpacked tuples + in the search. + :type rec: bool + + :returns: The index and node for the argument. + :rtype: tuple(str or None, AssignName or None) + """ + if self.arguments: + return _find_arg(argname, self.arguments, rec) + return None, None + + def get_children(self): + yield from self.posonlyargs or () + + for elt in self.posonlyargs_annotations: + if elt is not None: + yield elt + + yield from self.args or () + + yield from self.defaults + yield from self.kwonlyargs + + for elt in self.kw_defaults: + if elt is not None: + yield elt + + for elt in self.annotations: + if elt is not None: + yield elt + + if self.varargannotation is not None: + yield self.varargannotation + + if self.kwargannotation is not None: + yield self.kwargannotation + + for elt in self.kwonlyargs_annotations: + if elt is not None: + yield elt + + +def _find_arg(argname, args, rec=False): + for i, arg in enumerate(args): + if isinstance(arg, Tuple): + if rec: + found = _find_arg(argname, arg.elts) + if found[0] is not None: + return found + elif arg.name == argname: + return i, arg + return None, None + + +def _format_args(args, defaults=None, annotations=None): + values = [] + if args is None: + return "" + if annotations is None: + annotations = [] + if defaults is not None: + default_offset = len(args) - len(defaults) + packed = itertools.zip_longest(args, annotations) + for i, (arg, annotation) in enumerate(packed): + if isinstance(arg, Tuple): + values.append("(%s)" % _format_args(arg.elts)) + else: + argname = arg.name + default_sep = "=" + if annotation is not None: + argname += ": " + annotation.as_string() + default_sep = " = " + values.append(argname) + + if defaults is not None and i >= default_offset: + if defaults[i - default_offset] is not None: + values[-1] += default_sep + defaults[i - default_offset].as_string() + return ", ".join(values) + + +class AssignAttr(mixins.ParentAssignTypeMixin, NodeNG): + """Variation of :class:`ast.Assign` representing assignment to an attribute. + + >>> node = astroid.extract_node('self.attribute = range(10)') + >>> node + <Assign l.1 at 0x7effe1d521d0> + >>> list(node.get_children()) + [<AssignAttr.attribute l.1 at 0x7effe1d52320>, <Call l.1 at 0x7effe1d522e8>] + >>> list(node.get_children())[0].as_string() + 'self.attribute' + """ + + _astroid_fields = ("expr",) + _other_fields = ("attrname",) + + def __init__( + self, + attrname: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param attrname: The name of the attribute being assigned to. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.expr: Optional[NodeNG] = None + """What has the attribute that is being assigned to.""" + + self.attrname: Optional[str] = attrname + """The name of the attribute being assigned to.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, expr: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param expr: What has the attribute that is being assigned to. + """ + self.expr = expr + + def get_children(self): + yield self.expr + + +class Assert(Statement): + """Class representing an :class:`ast.Assert` node. + + An :class:`Assert` node represents an assert statement. + + >>> node = astroid.extract_node('assert len(things) == 10, "Not enough things"') + >>> node + <Assert l.1 at 0x7effe1d527b8> + """ + + _astroid_fields = ("test", "fail") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.test: Optional[NodeNG] = None + """The test that passes or fails the assertion.""" + + self.fail: Optional[NodeNG] = None # can be None + """The message shown when the assertion fails.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, test: Optional[NodeNG] = None, fail: Optional[NodeNG] = None + ) -> None: + """Do some setup after initialisation. + + :param test: The test that passes or fails the assertion. + + :param fail: The message shown when the assertion fails. + """ + self.fail = fail + self.test = test + + def get_children(self): + yield self.test + + if self.fail is not None: + yield self.fail + + +class Assign(mixins.AssignTypeMixin, Statement): + """Class representing an :class:`ast.Assign` node. + + An :class:`Assign` is a statement where something is explicitly + asssigned to. + + >>> node = astroid.extract_node('variable = range(10)') + >>> node + <Assign l.1 at 0x7effe1db8550> + """ + + _astroid_fields = ("targets", "value") + _other_other_fields = ("type_annotation",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.targets: typing.List[NodeNG] = [] + """What is being assigned to.""" + + self.value: Optional[NodeNG] = None + """The value being assigned to the variables.""" + + self.type_annotation: Optional[NodeNG] = None + """If present, this will contain the type annotation passed by a type comment""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + targets: Optional[typing.List[NodeNG]] = None, + value: Optional[NodeNG] = None, + type_annotation: Optional[NodeNG] = None, + ) -> None: + """Do some setup after initialisation. + + :param targets: What is being assigned to. + + :param value: The value being assigned to the variables. + """ + if targets is not None: + self.targets = targets + self.value = value + self.type_annotation = type_annotation + + def get_children(self): + yield from self.targets + + yield self.value + + @decorators.cached + def _get_assign_nodes(self): + return [self] + list(self.value._get_assign_nodes()) + + def _get_yield_nodes_skip_lambdas(self): + yield from self.value._get_yield_nodes_skip_lambdas() + + +class AnnAssign(mixins.AssignTypeMixin, Statement): + """Class representing an :class:`ast.AnnAssign` node. + + An :class:`AnnAssign` is an assignment with a type annotation. + + >>> node = astroid.extract_node('variable: List[int] = range(10)') + >>> node + <AnnAssign l.1 at 0x7effe1d4c630> + """ + + _astroid_fields = ("target", "annotation", "value") + _other_fields = ("simple",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.target: Optional[NodeNG] = None + """What is being assigned to.""" + + self.annotation: Optional[NodeNG] = None + """The type annotation of what is being assigned to.""" + + self.value: Optional[NodeNG] = None # can be None + """The value being assigned to the variables.""" + + self.simple: Optional[int] = None + """Whether :attr:`target` is a pure name or a complex statement.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + target: NodeNG, + annotation: NodeNG, + simple: int, + value: Optional[NodeNG] = None, + ) -> None: + """Do some setup after initialisation. + + :param target: What is being assigned to. + + :param annotation: The type annotation of what is being assigned to. + + :param simple: Whether :attr:`target` is a pure name + or a complex statement. + + :param value: The value being assigned to the variables. + """ + self.target = target + self.annotation = annotation + self.value = value + self.simple = simple + + def get_children(self): + yield self.target + yield self.annotation + + if self.value is not None: + yield self.value + + +class AugAssign(mixins.AssignTypeMixin, Statement): + """Class representing an :class:`ast.AugAssign` node. + + An :class:`AugAssign` is an assignment paired with an operator. + + >>> node = astroid.extract_node('variable += 1') + >>> node + <AugAssign l.1 at 0x7effe1db4d68> + """ + + _astroid_fields = ("target", "value") + _other_fields = ("op",) + + def __init__( + self, + op: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param op: The operator that is being combined with the assignment. + This includes the equals sign. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.target: Optional[NodeNG] = None + """What is being assigned to.""" + + self.op: Optional[str] = op + """The operator that is being combined with the assignment. + + This includes the equals sign. + """ + + self.value: Optional[NodeNG] = None + """The value being assigned to the variable.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, target: Optional[NodeNG] = None, value: Optional[NodeNG] = None + ) -> None: + """Do some setup after initialisation. + + :param target: What is being assigned to. + + :param value: The value being assigned to the variable. + """ + self.target = target + self.value = value + + # This is set by inference.py + def _infer_augassign(self, context=None): + raise NotImplementedError + + def type_errors(self, context=None): + """Get a list of type errors which can occur during inference. + + Each TypeError is represented by a :class:`BadBinaryOperationMessage` , + which holds the original exception. + + :returns: The list of possible type errors. + :rtype: list(BadBinaryOperationMessage) + """ + try: + results = self._infer_augassign(context=context) + return [ + result + for result in results + if isinstance(result, util.BadBinaryOperationMessage) + ] + except InferenceError: + return [] + + def get_children(self): + yield self.target + yield self.value + + def _get_yield_nodes_skip_lambdas(self): + """An AugAssign node can contain a Yield node in the value""" + yield from self.value._get_yield_nodes_skip_lambdas() + yield from super()._get_yield_nodes_skip_lambdas() + + +class BinOp(NodeNG): + """Class representing an :class:`ast.BinOp` node. + + A :class:`BinOp` node is an application of a binary operator. + + >>> node = astroid.extract_node('a + b') + >>> node + <BinOp l.1 at 0x7f23b2e8cfd0> + """ + + _astroid_fields = ("left", "right") + _other_fields = ("op",) + + def __init__( + self, + op: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param op: The operator. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.left: Optional[NodeNG] = None + """What is being applied to the operator on the left side.""" + + self.op: Optional[str] = op + """The operator.""" + + self.right: Optional[NodeNG] = None + """What is being applied to the operator on the right side.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, left: Optional[NodeNG] = None, right: Optional[NodeNG] = None + ) -> None: + """Do some setup after initialisation. + + :param left: What is being applied to the operator on the left side. + + :param right: What is being applied to the operator on the right side. + """ + self.left = left + self.right = right + + # This is set by inference.py + def _infer_binop(self, context=None): + raise NotImplementedError + + def type_errors(self, context=None): + """Get a list of type errors which can occur during inference. + + Each TypeError is represented by a :class:`BadBinaryOperationMessage`, + which holds the original exception. + + :returns: The list of possible type errors. + :rtype: list(BadBinaryOperationMessage) + """ + try: + results = self._infer_binop(context=context) + return [ + result + for result in results + if isinstance(result, util.BadBinaryOperationMessage) + ] + except InferenceError: + return [] + + def get_children(self): + yield self.left + yield self.right + + def op_precedence(self): + return OP_PRECEDENCE[self.op] + + def op_left_associative(self): + # 2**3**4 == 2**(3**4) + return self.op != "**" + + +class BoolOp(NodeNG): + """Class representing an :class:`ast.BoolOp` node. + + A :class:`BoolOp` is an application of a boolean operator. + + >>> node = astroid.extract_node('a and b') + >>> node + <BinOp l.1 at 0x7f23b2e71c50> + """ + + _astroid_fields = ("values",) + _other_fields = ("op",) + + def __init__( + self, + op: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param op: The operator. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.op: Optional[str] = op + """The operator.""" + + self.values: typing.List[NodeNG] = [] + """The values being applied to the operator.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, values: Optional[typing.List[NodeNG]] = None) -> None: + """Do some setup after initialisation. + + :param values: The values being applied to the operator. + """ + if values is not None: + self.values = values + + def get_children(self): + yield from self.values + + def op_precedence(self): + return OP_PRECEDENCE[self.op] + + +class Break(mixins.NoChildrenMixin, Statement): + """Class representing an :class:`ast.Break` node. + + >>> node = astroid.extract_node('break') + >>> node + <Break l.1 at 0x7f23b2e9e5c0> + """ + + +class Call(NodeNG): + """Class representing an :class:`ast.Call` node. + + A :class:`Call` node is a call to a function, method, etc. + + >>> node = astroid.extract_node('function()') + >>> node + <Call l.1 at 0x7f23b2e71eb8> + """ + + _astroid_fields = ("func", "args", "keywords") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.func: Optional[NodeNG] = None + """What is being called.""" + + self.args: typing.List[NodeNG] = [] + """The positional arguments being given to the call.""" + + self.keywords: typing.List["Keyword"] = [] + """The keyword arguments being given to the call.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + func: Optional[NodeNG] = None, + args: Optional[typing.List[NodeNG]] = None, + keywords: Optional[typing.List["Keyword"]] = None, + ) -> None: + """Do some setup after initialisation. + + :param func: What is being called. + + :param args: The positional arguments being given to the call. + + :param keywords: The keyword arguments being given to the call. + """ + self.func = func + if args is not None: + self.args = args + if keywords is not None: + self.keywords = keywords + + @property + def starargs(self) -> typing.List["Starred"]: + """The positional arguments that unpack something.""" + return [arg for arg in self.args if isinstance(arg, Starred)] + + @property + def kwargs(self) -> typing.List["Keyword"]: + """The keyword arguments that unpack something.""" + return [keyword for keyword in self.keywords if keyword.arg is None] + + def get_children(self): + yield self.func + + yield from self.args + + yield from self.keywords + + +class Compare(NodeNG): + """Class representing an :class:`ast.Compare` node. + + A :class:`Compare` node indicates a comparison. + + >>> node = astroid.extract_node('a <= b <= c') + >>> node + <Compare l.1 at 0x7f23b2e9e6d8> + >>> node.ops + [('<=', <Name.b l.1 at 0x7f23b2e9e2b0>), ('<=', <Name.c l.1 at 0x7f23b2e9e390>)] + """ + + _astroid_fields = ("left", "ops") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.left: Optional[NodeNG] = None + """The value at the left being applied to a comparison operator.""" + + self.ops: typing.List[typing.Tuple[str, NodeNG]] = [] + """The remainder of the operators and their relevant right hand value.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + left: Optional[NodeNG] = None, + ops: Optional[typing.List[typing.Tuple[str, NodeNG]]] = None, + ) -> None: + """Do some setup after initialisation. + + :param left: The value at the left being applied to a comparison + operator. + + :param ops: The remainder of the operators + and their relevant right hand value. + """ + self.left = left + if ops is not None: + self.ops = ops + + def get_children(self): + """Get the child nodes below this node. + + Overridden to handle the tuple fields and skip returning the operator + strings. + + :returns: The children. + :rtype: iterable(NodeNG) + """ + yield self.left + for _, comparator in self.ops: + yield comparator # we don't want the 'op' + + def last_child(self): + """An optimized version of list(get_children())[-1] + + :returns: The last child. + :rtype: NodeNG + """ + # XXX maybe if self.ops: + return self.ops[-1][1] + # return self.left + + +class Comprehension(NodeNG): + """Class representing an :class:`ast.comprehension` node. + + A :class:`Comprehension` indicates the loop inside any type of + comprehension including generator expressions. + + >>> node = astroid.extract_node('[x for x in some_values]') + >>> list(node.get_children()) + [<Name.x l.1 at 0x7f23b2e352b0>, <Comprehension l.1 at 0x7f23b2e35320>] + >>> list(node.get_children())[1].as_string() + 'for x in some_values' + """ + + _astroid_fields = ("target", "iter", "ifs") + _other_fields = ("is_async",) + + optional_assign = True + """Whether this node optionally assigns a variable.""" + + def __init__(self, parent: Optional[NodeNG] = None) -> None: + """ + :param parent: The parent node in the syntax tree. + """ + self.target: Optional[NodeNG] = None + """What is assigned to by the comprehension.""" + + self.iter: Optional[NodeNG] = None + """What is iterated over by the comprehension.""" + + self.ifs: typing.List[NodeNG] = [] + """The contents of any if statements that filter the comprehension.""" + + self.is_async: Optional[bool] = None + """Whether this is an asynchronous comprehension or not.""" + + super().__init__(parent=parent) + + # pylint: disable=redefined-builtin; same name as builtin ast module. + def postinit( + self, + target: Optional[NodeNG] = None, + iter: Optional[NodeNG] = None, + ifs: Optional[typing.List[NodeNG]] = None, + is_async: Optional[bool] = None, + ) -> None: + """Do some setup after initialisation. + + :param target: What is assigned to by the comprehension. + + :param iter: What is iterated over by the comprehension. + + :param ifs: The contents of any if statements that filter + the comprehension. + + :param is_async: Whether this is an asynchronous comprehension or not. + """ + self.target = target + self.iter = iter + if ifs is not None: + self.ifs = ifs + self.is_async = is_async + + def assign_type(self): + """The type of assignment that this node performs. + + :returns: The assignment type. + :rtype: NodeNG + """ + return self + + def _get_filtered_stmts(self, lookup_node, node, stmts, mystmt): + """method used in filter_stmts""" + if self is mystmt: + if isinstance(lookup_node, (Const, Name)): + return [lookup_node], True + + elif self.statement() is mystmt: + # original node's statement is the assignment, only keeps + # current node (gen exp, list comp) + + return [node], True + + return stmts, False + + def get_children(self): + yield self.target + yield self.iter + + yield from self.ifs + + +class Const(mixins.NoChildrenMixin, NodeNG, bases.Instance): + """Class representing any constant including num, str, bool, None, bytes. + + >>> node = astroid.extract_node('(5, "This is a string.", True, None, b"bytes")') + >>> node + <Tuple.tuple l.1 at 0x7f23b2e358d0> + >>> list(node.get_children()) + [<Const.int l.1 at 0x7f23b2e35940>, + <Const.str l.1 at 0x7f23b2e35978>, + <Const.bool l.1 at 0x7f23b2e359b0>, + <Const.NoneType l.1 at 0x7f23b2e359e8>, + <Const.bytes l.1 at 0x7f23b2e35a20>] + """ + + _other_fields = ("value",) + + def __init__( + self, + value: typing.Any, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + kind: Optional[str] = None, + ) -> None: + """ + :param value: The value that the constant represents. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + + :param kind: The string prefix. "u" for u-prefixed strings and ``None`` otherwise. Python 3.8+ only. + """ + self.value: typing.Any = value + """The value that the constant represents.""" + + self.kind: Optional[str] = kind # can be None + """"The string prefix. "u" for u-prefixed strings and ``None`` otherwise. Python 3.8+ only.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def __getattr__(self, name): + # This is needed because of Proxy's __getattr__ method. + # Calling object.__new__ on this class without calling + # __init__ would result in an infinite loop otherwise + # since __getattr__ is called when an attribute doesn't + # exist and self._proxied indirectly calls self.value + # and Proxy __getattr__ calls self.value + if name == "value": + raise AttributeError + return super().__getattr__(name) + + def getitem(self, index, context=None): + """Get an item from this node if subscriptable. + + :param index: The node to use as a subscript index. + :type index: Const or Slice + + :raises AstroidTypeError: When the given index cannot be used as a + subscript index, or if this node is not subscriptable. + """ + if isinstance(index, Const): + index_value = index.value + elif isinstance(index, Slice): + index_value = _infer_slice(index, context=context) + + else: + raise AstroidTypeError( + f"Could not use type {type(index)} as subscript index" + ) + + try: + if isinstance(self.value, (str, bytes)): + return Const(self.value[index_value]) + except IndexError as exc: + raise AstroidIndexError( + message="Index {index!r} out of range", + node=self, + index=index, + context=context, + ) from exc + except TypeError as exc: + raise AstroidTypeError( + message="Type error {error!r}", node=self, index=index, context=context + ) from exc + + raise AstroidTypeError(f"{self!r} (value={self.value})") + + def has_dynamic_getattr(self): + """Check if the node has a custom __getattr__ or __getattribute__. + + :returns: True if the class has a custom + __getattr__ or __getattribute__, False otherwise. + For a :class:`Const` this is always ``False``. + :rtype: bool + """ + return False + + def itered(self): + """An iterator over the elements this node contains. + + :returns: The contents of this node. + :rtype: iterable(Const) + + :raises TypeError: If this node does not represent something that is iterable. + """ + if isinstance(self.value, str): + return [const_factory(elem) for elem in self.value] + raise TypeError(f"Cannot iterate over type {type(self.value)!r}") + + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + return self._proxied.qname() + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + :rtype: bool + """ + return bool(self.value) + + +class Continue(mixins.NoChildrenMixin, Statement): + """Class representing an :class:`ast.Continue` node. + + >>> node = astroid.extract_node('continue') + >>> node + <Continue l.1 at 0x7f23b2e35588> + """ + + +class Decorators(NodeNG): + """A node representing a list of decorators. + + A :class:`Decorators` is the decorators that are applied to + a method or function. + + >>> node = astroid.extract_node(''' + @property + def my_property(self): + return 3 + ''') + >>> node + <FunctionDef.my_property l.2 at 0x7f23b2e35d30> + >>> list(node.get_children())[0] + <Decorators l.1 at 0x7f23b2e35d68> + """ + + _astroid_fields = ("nodes",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.nodes: typing.List[NodeNG] + """The decorators that this node contains. + + :type: list(Name or Call) or None + """ + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, nodes: typing.List[NodeNG]) -> None: + """Do some setup after initialisation. + + :param nodes: The decorators that this node contains. + :type nodes: list(Name or Call) + """ + self.nodes = nodes + + def scope(self): + """The first parent node defining a new scope. + + :returns: The first parent scope node. + :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr + """ + # skip the function node to go directly to the upper level scope + return self.parent.parent.scope() + + def get_children(self): + yield from self.nodes + + +class DelAttr(mixins.ParentAssignTypeMixin, NodeNG): + """Variation of :class:`ast.Delete` representing deletion of an attribute. + + >>> node = astroid.extract_node('del self.attr') + >>> node + <Delete l.1 at 0x7f23b2e35f60> + >>> list(node.get_children())[0] + <DelAttr.attr l.1 at 0x7f23b2e411d0> + """ + + _astroid_fields = ("expr",) + _other_fields = ("attrname",) + + def __init__( + self, + attrname: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param attrname: The name of the attribute that is being deleted. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.expr: Optional[NodeNG] = None + """The name that this node represents. + + :type: Name or None + """ + + self.attrname: Optional[str] = attrname + """The name of the attribute that is being deleted.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, expr: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param expr: The name that this node represents. + :type expr: Name or None + """ + self.expr = expr + + def get_children(self): + yield self.expr + + +class Delete(mixins.AssignTypeMixin, Statement): + """Class representing an :class:`ast.Delete` node. + + A :class:`Delete` is a ``del`` statement this is deleting something. + + >>> node = astroid.extract_node('del self.attr') + >>> node + <Delete l.1 at 0x7f23b2e35f60> + """ + + _astroid_fields = ("targets",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.targets: typing.List[NodeNG] = [] + """What is being deleted.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, targets: Optional[typing.List[NodeNG]] = None) -> None: + """Do some setup after initialisation. + + :param targets: What is being deleted. + """ + if targets is not None: + self.targets = targets + + def get_children(self): + yield from self.targets + + +class Dict(NodeNG, bases.Instance): + """Class representing an :class:`ast.Dict` node. + + A :class:`Dict` is a dictionary that is created with ``{}`` syntax. + + >>> node = astroid.extract_node('{1: "1"}') + >>> node + <Dict.dict l.1 at 0x7f23b2e35cc0> + """ + + _astroid_fields = ("items",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.items: typing.List[typing.Tuple[NodeNG, NodeNG]] = [] + """The key-value pairs contained in the dictionary.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, items: typing.List[typing.Tuple[NodeNG, NodeNG]]) -> None: + """Do some setup after initialisation. + + :param items: The key-value pairs contained in the dictionary. + """ + self.items = items + + @classmethod + def from_elements(cls, items=None): + """Create a :class:`Dict` of constants from a live dictionary. + + :param items: The items to store in the node. + :type items: dict + + :returns: The created dictionary node. + :rtype: Dict + """ + node = cls() + if items is None: + node.items = [] + else: + node.items = [ + (const_factory(k), const_factory(v) if _is_const(v) else v) + for k, v in items.items() + # The keys need to be constants + if _is_const(k) + ] + return node + + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + return "%s.dict" % BUILTINS + + def get_children(self): + """Get the key and value nodes below this node. + + Children are returned in the order that they are defined in the source + code, key first then the value. + + :returns: The children. + :rtype: iterable(NodeNG) + """ + for key, value in self.items: + yield key + yield value + + def last_child(self): + """An optimized version of list(get_children())[-1] + + :returns: The last child, or None if no children exist. + :rtype: NodeNG or None + """ + if self.items: + return self.items[-1][1] + return None + + def itered(self): + """An iterator over the keys this node contains. + + :returns: The keys of this node. + :rtype: iterable(NodeNG) + """ + return [key for (key, _) in self.items] + + def getitem(self, index, context=None): + """Get an item from this node. + + :param index: The node to use as a subscript index. + :type index: Const or Slice + + :raises AstroidTypeError: When the given index cannot be used as a + subscript index, or if this node is not subscriptable. + :raises AstroidIndexError: If the given index does not exist in the + dictionary. + """ + for key, value in self.items: + # TODO(cpopa): no support for overriding yet, {1:2, **{1: 3}}. + if isinstance(key, DictUnpack): + try: + return value.getitem(index, context) + except (AstroidTypeError, AstroidIndexError): + continue + for inferredkey in key.infer(context): + if inferredkey is util.Uninferable: + continue + if isinstance(inferredkey, Const) and isinstance(index, Const): + if inferredkey.value == index.value: + return value + + raise AstroidIndexError(index) + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + :rtype: bool + """ + return bool(self.items) + + +class Expr(Statement): + """Class representing an :class:`ast.Expr` node. + + An :class:`Expr` is any expression that does not have its value used or + stored. + + >>> node = astroid.extract_node('method()') + >>> node + <Call l.1 at 0x7f23b2e352b0> + >>> node.parent + <Expr l.1 at 0x7f23b2e35278> + """ + + _astroid_fields = ("value",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.value: Optional[NodeNG] = None + """What the expression does.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, value: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param value: What the expression does. + """ + self.value = value + + def get_children(self): + yield self.value + + def _get_yield_nodes_skip_lambdas(self): + if not self.value.is_lambda: + yield from self.value._get_yield_nodes_skip_lambdas() + + +class Ellipsis(mixins.NoChildrenMixin, NodeNG): # pylint: disable=redefined-builtin + """Class representing an :class:`ast.Ellipsis` node. + + An :class:`Ellipsis` is the ``...`` syntax. + + Deprecated since v2.6.0 - Use :class:`Const` instead. + Will be removed with the release v2.7.0 + """ + + +class EmptyNode(mixins.NoChildrenMixin, NodeNG): + """Holds an arbitrary object in the :attr:`LocalsDictNodeNG.locals`.""" + + object = None + + +class ExceptHandler(mixins.MultiLineBlockMixin, mixins.AssignTypeMixin, Statement): + """Class representing an :class:`ast.ExceptHandler`. node. + + An :class:`ExceptHandler` is an ``except`` block on a try-except. + + >>> node = astroid.extract_node(''' + try: + do_something() + except Exception as error: + print("Error!") + ''') + >>> node + <TryExcept l.2 at 0x7f23b2e9d908> + >>> >>> node.handlers + [<ExceptHandler l.4 at 0x7f23b2e9e860>] + """ + + _astroid_fields = ("type", "name", "body") + _multi_line_block_fields = ("body",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.type: Optional[NodeNG] = None # can be None + """The types that the block handles. + + :type: Tuple or NodeNG or None + """ + + self.name: Optional[AssignName] = None # can be None + """The name that the caught exception is assigned to.""" + + self.body: typing.List[NodeNG] = [] + """The contents of the block.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def get_children(self): + if self.type is not None: + yield self.type + + if self.name is not None: + yield self.name + + yield from self.body + + # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. + def postinit( + self, + type: Optional[NodeNG] = None, + name: Optional[AssignName] = None, + body: Optional[typing.List[NodeNG]] = None, + ) -> None: + """Do some setup after initialisation. + + :param type: The types that the block handles. + :type type: Tuple or NodeNG or None + + :param name: The name that the caught exception is assigned to. + + :param body:The contents of the block. + """ + self.type = type + self.name = name + if body is not None: + self.body = body + + @decorators.cachedproperty + def blockstart_tolineno(self): + """The line on which the beginning of this block ends. + + :type: int + """ + if self.name: + return self.name.tolineno + if self.type: + return self.type.tolineno + return self.lineno + + def catch(self, exceptions: Optional[typing.List[str]]) -> bool: + """Check if this node handles any of the given + + :param exceptions: The names of the exceptions to check for. + """ + if self.type is None or exceptions is None: + return True + for node in self.type._get_name_nodes(): + if node.name in exceptions: + return True + return False + + +class ExtSlice(NodeNG): + """Class representing an :class:`ast.ExtSlice` node. + + An :class:`ExtSlice` is a complex slice expression. + + Deprecated since v2.6.0 - Now part of the :class:`Subscript` node. + Will be removed with the release of v2.7.0 + """ + + +class For( + mixins.MultiLineBlockMixin, + mixins.BlockRangeMixIn, + mixins.AssignTypeMixin, + Statement, +): + """Class representing an :class:`ast.For` node. + + >>> node = astroid.extract_node('for thing in things: print(thing)') + >>> node + <For l.1 at 0x7f23b2e8cf28> + """ + + _astroid_fields = ("target", "iter", "body", "orelse") + _other_other_fields = ("type_annotation",) + _multi_line_block_fields = ("body", "orelse") + + optional_assign = True + """Whether this node optionally assigns a variable. + + This is always ``True`` for :class:`For` nodes. + """ + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.target: Optional[NodeNG] = None + """What the loop assigns to.""" + + self.iter: Optional[NodeNG] = None + """What the loop iterates over.""" + + self.body: typing.List[NodeNG] = [] + """The contents of the body of the loop.""" + + self.orelse: typing.List[NodeNG] = [] + """The contents of the ``else`` block of the loop.""" + + self.type_annotation: Optional[NodeNG] = None # can be None + """If present, this will contain the type annotation passed by a type comment""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. + def postinit( + self, + target: Optional[NodeNG] = None, + iter: Optional[NodeNG] = None, + body: Optional[typing.List[NodeNG]] = None, + orelse: Optional[typing.List[NodeNG]] = None, + type_annotation: Optional[NodeNG] = None, + ) -> None: + """Do some setup after initialisation. + + :param target: What the loop assigns to. + + :param iter: What the loop iterates over. + + :param body: The contents of the body of the loop. + + :param orelse: The contents of the ``else`` block of the loop. + """ + self.target = target + self.iter = iter + if body is not None: + self.body = body + if orelse is not None: + self.orelse = orelse + self.type_annotation = type_annotation + + @decorators.cachedproperty + def blockstart_tolineno(self): + """The line on which the beginning of this block ends. + + :type: int + """ + return self.iter.tolineno + + def get_children(self): + yield self.target + yield self.iter + + yield from self.body + yield from self.orelse + + +class AsyncFor(For): + """Class representing an :class:`ast.AsyncFor` node. + + An :class:`AsyncFor` is an asynchronous :class:`For` built with + the ``async`` keyword. + + >>> node = astroid.extract_node(''' + async def func(things): + async for thing in things: + print(thing) + ''') + >>> node + <AsyncFunctionDef.func l.2 at 0x7f23b2e416d8> + >>> node.body[0] + <AsyncFor l.3 at 0x7f23b2e417b8> + """ + + +class Await(NodeNG): + """Class representing an :class:`ast.Await` node. + + An :class:`Await` is the ``await`` keyword. + + >>> node = astroid.extract_node(''' + async def func(things): + await other_func() + ''') + >>> node + <AsyncFunctionDef.func l.2 at 0x7f23b2e41748> + >>> node.body[0] + <Expr l.3 at 0x7f23b2e419e8> + >>> list(node.body[0].get_children())[0] + <Await l.3 at 0x7f23b2e41a20> + """ + + _astroid_fields = ("value",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.value: Optional[NodeNG] = None + """What to wait for.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, value: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param value: What to wait for. + """ + self.value = value + + def get_children(self): + yield self.value + + +class ImportFrom(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement): + """Class representing an :class:`ast.ImportFrom` node. + + >>> node = astroid.extract_node('from my_package import my_module') + >>> node + <ImportFrom l.1 at 0x7f23b2e415c0> + """ + + _other_fields = ("modname", "names", "level") + + def __init__( + self, + fromname: Optional[str], + names: typing.List[typing.Tuple[str, Optional[str]]], + level: Optional[int] = 0, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param fromname: The module that is being imported from. + + :param names: What is being imported from the module. + + :param level: The level of relative import. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.modname: Optional[str] = fromname # can be None + """The module that is being imported from. + + This is ``None`` for relative imports. + """ + + self.names: typing.List[typing.Tuple[str, Optional[str]]] = names + """What is being imported from the module. + + Each entry is a :class:`tuple` of the name being imported, + and the alias that the name is assigned to (if any). + """ + + # TODO When is 'level' None? + self.level: Optional[int] = level # can be None + """The level of relative import. + + Essentially this is the number of dots in the import. + This is always 0 for absolute imports. + """ + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + +class Attribute(NodeNG): + """Class representing an :class:`ast.Attribute` node.""" + + _astroid_fields = ("expr",) + _other_fields = ("attrname",) + + def __init__( + self, + attrname: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param attrname: The name of the attribute. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.expr: Optional[NodeNG] = None + """The name that this node represents. + + :type: Name or None + """ + + self.attrname: Optional[str] = attrname + """The name of the attribute.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, expr: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param expr: The name that this node represents. + :type expr: Name or None + """ + self.expr = expr + + def get_children(self): + yield self.expr + + +class Global(mixins.NoChildrenMixin, Statement): + """Class representing an :class:`ast.Global` node. + + >>> node = astroid.extract_node('global a_global') + >>> node + <Global l.1 at 0x7f23b2e9de10> + """ + + _other_fields = ("names",) + + def __init__( + self, + names: typing.List[str], + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param names: The names being declared as global. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.names: typing.List[str] = names + """The names being declared as global.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def _infer_name(self, frame, name): + return name + + +class If(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): + """Class representing an :class:`ast.If` node. + + >>> node = astroid.extract_node('if condition: print(True)') + >>> node + <If l.1 at 0x7f23b2e9dd30> + """ + + _astroid_fields = ("test", "body", "orelse") + _multi_line_block_fields = ("body", "orelse") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.test: Optional[NodeNG] = None + """The condition that the statement tests.""" + + self.body: typing.List[NodeNG] = [] + """The contents of the block.""" + + self.orelse: typing.List[NodeNG] = [] + """The contents of the ``else`` block.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + test: Optional[NodeNG] = None, + body: Optional[typing.List[NodeNG]] = None, + orelse: Optional[typing.List[NodeNG]] = None, + ) -> None: + """Do some setup after initialisation. + + :param test: The condition that the statement tests. + + :param body: The contents of the block. + + :param orelse: The contents of the ``else`` block. + """ + self.test = test + if body is not None: + self.body = body + if orelse is not None: + self.orelse = orelse + + @decorators.cachedproperty + def blockstart_tolineno(self): + """The line on which the beginning of this block ends. + + :type: int + """ + return self.test.tolineno + + def block_range(self, lineno): + """Get a range from the given line number to where this node ends. + + :param lineno: The line number to start the range at. + :type lineno: int + + :returns: The range of line numbers that this node belongs to, + starting at the given line number. + :rtype: tuple(int, int) + """ + if lineno == self.body[0].fromlineno: + return lineno, lineno + if lineno <= self.body[-1].tolineno: + return lineno, self.body[-1].tolineno + return self._elsed_block_range(lineno, self.orelse, self.body[0].fromlineno - 1) + + def get_children(self): + yield self.test + + yield from self.body + yield from self.orelse + + def has_elif_block(self): + return len(self.orelse) == 1 and isinstance(self.orelse[0], If) + + def _get_yield_nodes_skip_lambdas(self): + """An If node can contain a Yield node in the test""" + yield from self.test._get_yield_nodes_skip_lambdas() + yield from super()._get_yield_nodes_skip_lambdas() + + def is_sys_guard(self) -> bool: + """Return True if IF stmt is a sys.version_info guard. + + >>> node = astroid.extract_node(''' + import sys + if sys.version_info > (3, 8): + from typing import Literal + else: + from typing_extensions import Literal + ''') + >>> node.is_sys_guard() + True + """ + if isinstance(self.test, Compare): + value = self.test.left + if isinstance(value, Subscript): + value = value.value + if isinstance(value, Attribute) and value.as_string() == "sys.version_info": + return True + + return False + + def is_typing_guard(self) -> bool: + """Return True if IF stmt is a typing guard. + + >>> node = astroid.extract_node(''' + from typing import TYPE_CHECKING + if TYPE_CHECKING: + from xyz import a + ''') + >>> node.is_typing_guard() + True + """ + return isinstance( + self.test, (Name, Attribute) + ) and self.test.as_string().endswith("TYPE_CHECKING") + + +class IfExp(NodeNG): + """Class representing an :class:`ast.IfExp` node. + + >>> node = astroid.extract_node('value if condition else other') + >>> node + <IfExp l.1 at 0x7f23b2e9dbe0> + """ + + _astroid_fields = ("test", "body", "orelse") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.test: Optional[NodeNG] = None + """The condition that the statement tests.""" + + self.body: Optional[NodeNG] = None + """The contents of the block.""" + + self.orelse: Optional[NodeNG] = None + """The contents of the ``else`` block.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + test: Optional[NodeNG] = None, + body: Optional[NodeNG] = None, + orelse: Optional[NodeNG] = None, + ) -> None: + """Do some setup after initialisation. + + :param test: The condition that the statement tests. + + :param body: The contents of the block. + + :param orelse: The contents of the ``else`` block. + """ + self.test = test + self.body = body + self.orelse = orelse + + def get_children(self): + yield self.test + yield self.body + yield self.orelse + + def op_left_associative(self): + # `1 if True else 2 if False else 3` is parsed as + # `1 if True else (2 if False else 3)` + return False + + +class Import(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement): + """Class representing an :class:`ast.Import` node. + + >>> node = astroid.extract_node('import astroid') + >>> node + <Import l.1 at 0x7f23b2e4e5c0> + """ + + _other_fields = ("names",) + + def __init__( + self, + names: Optional[typing.List[typing.Tuple[str, Optional[str]]]] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param names: The names being imported. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.names: typing.List[typing.Tuple[str, Optional[str]]] = names or [] + """The names being imported. + + Each entry is a :class:`tuple` of the name being imported, + and the alias that the name is assigned to (if any). + """ + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + +class Index(NodeNG): + """Class representing an :class:`ast.Index` node. + + An :class:`Index` is a simple subscript. + + Deprecated since v2.6.0 - Now part of the :class:`Subscript` node. + Will be removed with the release of v2.7.0 + """ + + +class Keyword(NodeNG): + """Class representing an :class:`ast.keyword` node. + + >>> node = astroid.extract_node('function(a_kwarg=True)') + >>> node + <Call l.1 at 0x7f23b2e9e320> + >>> node.keywords + [<Keyword l.1 at 0x7f23b2e9e9b0>] + """ + + _astroid_fields = ("value",) + _other_fields = ("arg",) + + def __init__( + self, + arg: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param arg: The argument being assigned to. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.arg: Optional[str] = arg # can be None + """The argument being assigned to.""" + + self.value: Optional[NodeNG] = None + """The value being assigned to the keyword argument.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, value: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param value: The value being assigned to the ketword argument. + """ + self.value = value + + def get_children(self): + yield self.value + + +class List(_BaseContainer): + """Class representing an :class:`ast.List` node. + + >>> node = astroid.extract_node('[1, 2, 3]') + >>> node + <List.list l.1 at 0x7f23b2e9e128> + """ + + _other_fields = ("ctx",) + + def __init__( + self, + ctx: Optional[Context] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param ctx: Whether the list is assigned to or loaded from. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.ctx: Optional[Context] = ctx + """Whether the list is assigned to or loaded from.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + return "%s.list" % BUILTINS + + def getitem(self, index, context=None): + """Get an item from this node. + + :param index: The node to use as a subscript index. + :type index: Const or Slice + """ + return _container_getitem(self, self.elts, index, context=context) + + +class Nonlocal(mixins.NoChildrenMixin, Statement): + """Class representing an :class:`ast.Nonlocal` node. + + >>> node = astroid.extract_node(''' + def function(): + nonlocal var + ''') + >>> node + <FunctionDef.function l.2 at 0x7f23b2e9e208> + >>> node.body[0] + <Nonlocal l.3 at 0x7f23b2e9e908> + """ + + _other_fields = ("names",) + + def __init__( + self, + names: typing.List[str], + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param names: The names being declared as not local. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.names: typing.List[str] = names + """The names being declared as not local.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def _infer_name(self, frame, name): + return name + + +class Pass(mixins.NoChildrenMixin, Statement): + """Class representing an :class:`ast.Pass` node. + + >>> node = astroid.extract_node('pass') + >>> node + <Pass l.1 at 0x7f23b2e9e748> + """ + + +class Raise(Statement): + """Class representing an :class:`ast.Raise` node. + + >>> node = astroid.extract_node('raise RuntimeError("Something bad happened!")') + >>> node + <Raise l.1 at 0x7f23b2e9e828> + """ + + _astroid_fields = ("exc", "cause") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.exc: Optional[NodeNG] = None # can be None + """What is being raised.""" + + self.cause: Optional[NodeNG] = None # can be None + """The exception being used to raise this one.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + exc: Optional[NodeNG] = None, + cause: Optional[NodeNG] = None, + ) -> None: + """Do some setup after initialisation. + + :param exc: What is being raised. + + :param cause: The exception being used to raise this one. + """ + self.exc = exc + self.cause = cause + + def raises_not_implemented(self): + """Check if this node raises a :class:`NotImplementedError`. + + :returns: True if this node raises a :class:`NotImplementedError`, + False otherwise. + :rtype: bool + """ + if not self.exc: + return False + for name in self.exc._get_name_nodes(): + if name.name == "NotImplementedError": + return True + return False + + def get_children(self): + if self.exc is not None: + yield self.exc + + if self.cause is not None: + yield self.cause + + +class Return(Statement): + """Class representing an :class:`ast.Return` node. + + >>> node = astroid.extract_node('return True') + >>> node + <Return l.1 at 0x7f23b8211908> + """ + + _astroid_fields = ("value",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.value: Optional[NodeNG] = None # can be None + """The value being returned.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, value: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param value: The value being returned. + """ + self.value = value + + def get_children(self): + if self.value is not None: + yield self.value + + def is_tuple_return(self): + return isinstance(self.value, Tuple) + + def _get_return_nodes_skip_functions(self): + yield self + + +class Set(_BaseContainer): + """Class representing an :class:`ast.Set` node. + + >>> node = astroid.extract_node('{1, 2, 3}') + >>> node + <Set.set l.1 at 0x7f23b2e71d68> + """ + + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + return "%s.set" % BUILTINS + + +class Slice(NodeNG): + """Class representing an :class:`ast.Slice` node. + + >>> node = astroid.extract_node('things[1:3]') + >>> node + <Subscript l.1 at 0x7f23b2e71f60> + >>> node.slice + <Slice l.1 at 0x7f23b2e71e80> + """ + + _astroid_fields = ("lower", "upper", "step") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.lower: Optional[NodeNG] = None # can be None + """The lower index in the slice.""" + + self.upper: Optional[NodeNG] = None # can be None + """The upper index in the slice.""" + + self.step: Optional[NodeNG] = None # can be None + """The step to take between indexes.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + lower: Optional[NodeNG] = None, + upper: Optional[NodeNG] = None, + step: Optional[NodeNG] = None, + ) -> None: + """Do some setup after initialisation. + + :param lower: The lower index in the slice. + + :param upper: The upper index in the slice. + + :param step: The step to take between index. + """ + self.lower = lower + self.upper = upper + self.step = step + + def _wrap_attribute(self, attr): + """Wrap the empty attributes of the Slice in a Const node.""" + if not attr: + const = const_factory(attr) + const.parent = self + return const + return attr + + @decorators.cachedproperty + def _proxied(self): + builtins = AstroidManager().builtins_module + return builtins.getattr("slice")[0] + + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + return "%s.slice" % BUILTINS + + def igetattr(self, attrname, context=None): + """Infer the possible values of the given attribute on the slice. + + :param attrname: The name of the attribute to infer. + :type attrname: str + + :returns: The inferred possible values. + :rtype: iterable(NodeNG) + """ + if attrname == "start": + yield self._wrap_attribute(self.lower) + elif attrname == "stop": + yield self._wrap_attribute(self.upper) + elif attrname == "step": + yield self._wrap_attribute(self.step) + else: + yield from self.getattr(attrname, context=context) + + def getattr(self, attrname, context=None): + return self._proxied.getattr(attrname, context) + + def get_children(self): + if self.lower is not None: + yield self.lower + + if self.upper is not None: + yield self.upper + + if self.step is not None: + yield self.step + + +class Starred(mixins.ParentAssignTypeMixin, NodeNG): + """Class representing an :class:`ast.Starred` node. + + >>> node = astroid.extract_node('*args') + >>> node + <Starred l.1 at 0x7f23b2e41978> + """ + + _astroid_fields = ("value",) + _other_fields = ("ctx",) + + def __init__( + self, + ctx: Optional[Context] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param ctx: Whether the list is assigned to or loaded from. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.value: Optional[NodeNG] = None + """What is being unpacked.""" + + self.ctx: Optional[Context] = ctx + """Whether the starred item is assigned to or loaded from.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, value: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param value: What is being unpacked. + """ + self.value = value + + def get_children(self): + yield self.value + + +class Subscript(NodeNG): + """Class representing an :class:`ast.Subscript` node. + + >>> node = astroid.extract_node('things[1:3]') + >>> node + <Subscript l.1 at 0x7f23b2e71f60> + """ + + _astroid_fields = ("value", "slice") + _other_fields = ("ctx",) + + def __init__( + self, + ctx: Optional[Context] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param ctx: Whether the subscripted item is assigned to or loaded from. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.value: Optional[NodeNG] = None + """What is being indexed.""" + + self.slice: Optional[NodeNG] = None + """The slice being used to lookup.""" + + self.ctx: Optional[Context] = ctx + """Whether the subscripted item is assigned to or loaded from.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + # pylint: disable=redefined-builtin; had to use the same name as builtin ast module. + def postinit( + self, value: Optional[NodeNG] = None, slice: Optional[NodeNG] = None + ) -> None: + """Do some setup after initialisation. + + :param value: What is being indexed. + + :param slice: The slice being used to lookup. + """ + self.value = value + self.slice = slice + + def get_children(self): + yield self.value + yield self.slice + + +class TryExcept(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): + """Class representing an :class:`ast.TryExcept` node. + + >>> node = astroid.extract_node(''' + try: + do_something() + except Exception as error: + print("Error!") + ''') + >>> node + <TryExcept l.2 at 0x7f23b2e9d908> + """ + + _astroid_fields = ("body", "handlers", "orelse") + _multi_line_block_fields = ("body", "handlers", "orelse") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.body: typing.List[NodeNG] = [] + """The contents of the block to catch exceptions from.""" + + self.handlers: typing.List[ExceptHandler] = [] + """The exception handlers.""" + + self.orelse: typing.List[NodeNG] = [] + """The contents of the ``else`` block.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + body: Optional[typing.List[NodeNG]] = None, + handlers: Optional[typing.List[ExceptHandler]] = None, + orelse: Optional[typing.List[NodeNG]] = None, + ) -> None: + """Do some setup after initialisation. + + :param body: The contents of the block to catch exceptions from. + + :param handlers: The exception handlers. + + :param orelse: The contents of the ``else`` block. + """ + if body is not None: + self.body = body + if handlers is not None: + self.handlers = handlers + if orelse is not None: + self.orelse = orelse + + def _infer_name(self, frame, name): + return name + + def block_range(self, lineno): + """Get a range from the given line number to where this node ends. + + :param lineno: The line number to start the range at. + :type lineno: int + + :returns: The range of line numbers that this node belongs to, + starting at the given line number. + :rtype: tuple(int, int) + """ + last = None + for exhandler in self.handlers: + if exhandler.type and lineno == exhandler.type.fromlineno: + return lineno, lineno + if exhandler.body[0].fromlineno <= lineno <= exhandler.body[-1].tolineno: + return lineno, exhandler.body[-1].tolineno + if last is None: + last = exhandler.body[0].fromlineno - 1 + return self._elsed_block_range(lineno, self.orelse, last) + + def get_children(self): + yield from self.body + + yield from self.handlers or () + yield from self.orelse or () + + +class TryFinally(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): + """Class representing an :class:`ast.TryFinally` node. + + >>> node = astroid.extract_node(''' + try: + do_something() + except Exception as error: + print("Error!") + finally: + print("Cleanup!") + ''') + >>> node + <TryFinally l.2 at 0x7f23b2e41d68> + """ + + _astroid_fields = ("body", "finalbody") + _multi_line_block_fields = ("body", "finalbody") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.body: typing.Union[typing.List[TryExcept], typing.List[NodeNG]] = [] + """The try-except that the finally is attached to.""" + + self.finalbody: typing.List[NodeNG] = [] + """The contents of the ``finally`` block.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + body: typing.Union[typing.List[TryExcept], typing.List[NodeNG], None] = None, + finalbody: Optional[typing.List[NodeNG]] = None, + ) -> None: + """Do some setup after initialisation. + + :param body: The try-except that the finally is attached to. + + :param finalbody: The contents of the ``finally`` block. + """ + if body is not None: + self.body = body + if finalbody is not None: + self.finalbody = finalbody + + def block_range(self, lineno): + """Get a range from the given line number to where this node ends. + + :param lineno: The line number to start the range at. + :type lineno: int + + :returns: The range of line numbers that this node belongs to, + starting at the given line number. + :rtype: tuple(int, int) + """ + child = self.body[0] + # py2.5 try: except: finally: + if ( + isinstance(child, TryExcept) + and child.fromlineno == self.fromlineno + and child.tolineno >= lineno > self.fromlineno + ): + return child.block_range(lineno) + return self._elsed_block_range(lineno, self.finalbody) + + def get_children(self): + yield from self.body + yield from self.finalbody + + +class Tuple(_BaseContainer): + """Class representing an :class:`ast.Tuple` node. + + >>> node = astroid.extract_node('(1, 2, 3)') + >>> node + <Tuple.tuple l.1 at 0x7f23b2e41780> + """ + + _other_fields = ("ctx",) + + def __init__( + self, + ctx: Optional[Context] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param ctx: Whether the tuple is assigned to or loaded from. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.ctx: Optional[Context] = ctx + """Whether the tuple is assigned to or loaded from.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + return "%s.tuple" % BUILTINS + + def getitem(self, index, context=None): + """Get an item from this node. + + :param index: The node to use as a subscript index. + :type index: Const or Slice + """ + return _container_getitem(self, self.elts, index, context=context) + + +class UnaryOp(NodeNG): + """Class representing an :class:`ast.UnaryOp` node. + + >>> node = astroid.extract_node('-5') + >>> node + <UnaryOp l.1 at 0x7f23b2e4e198> + """ + + _astroid_fields = ("operand",) + _other_fields = ("op",) + + def __init__( + self, + op: Optional[str] = None, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param op: The operator. + + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.op: Optional[str] = op + """The operator.""" + + self.operand: Optional[NodeNG] = None + """What the unary operator is applied to.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, operand: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param operand: What the unary operator is applied to. + """ + self.operand = operand + + # This is set by inference.py + def _infer_unaryop(self, context=None): + raise NotImplementedError + + def type_errors(self, context=None): + """Get a list of type errors which can occur during inference. + + Each TypeError is represented by a :class:`BadBinaryOperationMessage`, + which holds the original exception. + + :returns: The list of possible type errors. + :rtype: list(BadBinaryOperationMessage) + """ + try: + results = self._infer_unaryop(context=context) + return [ + result + for result in results + if isinstance(result, util.BadUnaryOperationMessage) + ] + except InferenceError: + return [] + + def get_children(self): + yield self.operand + + def op_precedence(self): + if self.op == "not": + return OP_PRECEDENCE[self.op] + + return super().op_precedence() + + +class While(mixins.MultiLineBlockMixin, mixins.BlockRangeMixIn, Statement): + """Class representing an :class:`ast.While` node. + + >>> node = astroid.extract_node(''' + while condition(): + print("True") + ''') + >>> node + <While l.2 at 0x7f23b2e4e390> + """ + + _astroid_fields = ("test", "body", "orelse") + _multi_line_block_fields = ("body", "orelse") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.test: Optional[NodeNG] = None + """The condition that the loop tests.""" + + self.body: typing.List[NodeNG] = [] + """The contents of the loop.""" + + self.orelse: typing.List[NodeNG] = [] + """The contents of the ``else`` block.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + test: Optional[NodeNG] = None, + body: Optional[typing.List[NodeNG]] = None, + orelse: Optional[typing.List[NodeNG]] = None, + ) -> None: + """Do some setup after initialisation. + + :param test: The condition that the loop tests. + + :param body: The contents of the loop. + + :param orelse: The contents of the ``else`` block. + """ + self.test = test + if body is not None: + self.body = body + if orelse is not None: + self.orelse = orelse + + @decorators.cachedproperty + def blockstart_tolineno(self): + """The line on which the beginning of this block ends. + + :type: int + """ + return self.test.tolineno + + def block_range(self, lineno): + """Get a range from the given line number to where this node ends. + + :param lineno: The line number to start the range at. + :type lineno: int + + :returns: The range of line numbers that this node belongs to, + starting at the given line number. + :rtype: tuple(int, int) + """ + return self._elsed_block_range(lineno, self.orelse) + + def get_children(self): + yield self.test + + yield from self.body + yield from self.orelse + + def _get_yield_nodes_skip_lambdas(self): + """A While node can contain a Yield node in the test""" + yield from self.test._get_yield_nodes_skip_lambdas() + yield from super()._get_yield_nodes_skip_lambdas() + + +class With( + mixins.MultiLineBlockMixin, + mixins.BlockRangeMixIn, + mixins.AssignTypeMixin, + Statement, +): + """Class representing an :class:`ast.With` node. + + >>> node = astroid.extract_node(''' + with open(file_path) as file_: + print(file_.read()) + ''') + >>> node + <With l.2 at 0x7f23b2e4e710> + """ + + _astroid_fields = ("items", "body") + _other_other_fields = ("type_annotation",) + _multi_line_block_fields = ("body",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.items: typing.List[typing.Tuple[NodeNG, Optional[NodeNG]]] = [] + """The pairs of context managers and the names they are assigned to.""" + + self.body: typing.List[NodeNG] = [] + """The contents of the ``with`` block.""" + + self.type_annotation: Optional[NodeNG] = None # can be None + """If present, this will contain the type annotation passed by a type comment""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + items: Optional[typing.List[typing.Tuple[NodeNG, Optional[NodeNG]]]] = None, + body: Optional[typing.List[NodeNG]] = None, + type_annotation: Optional[NodeNG] = None, + ) -> None: + """Do some setup after initialisation. + + :param items: The pairs of context managers and the names + they are assigned to. + + :param body: The contents of the ``with`` block. + """ + if items is not None: + self.items = items + if body is not None: + self.body = body + self.type_annotation = type_annotation + + @decorators.cachedproperty + def blockstart_tolineno(self): + """The line on which the beginning of this block ends. + + :type: int + """ + return self.items[-1][0].tolineno + + def get_children(self): + """Get the child nodes below this node. + + :returns: The children. + :rtype: iterable(NodeNG) + """ + for expr, var in self.items: + yield expr + if var: + yield var + yield from self.body + + +class AsyncWith(With): + """Asynchronous ``with`` built with the ``async`` keyword.""" + + +class Yield(NodeNG): + """Class representing an :class:`ast.Yield` node. + + >>> node = astroid.extract_node('yield True') + >>> node + <Yield l.1 at 0x7f23b2e4e5f8> + """ + + _astroid_fields = ("value",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.value: Optional[NodeNG] = None # can be None + """The value to yield.""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, value: Optional[NodeNG] = None) -> None: + """Do some setup after initialisation. + + :param value: The value to yield. + """ + self.value = value + + def get_children(self): + if self.value is not None: + yield self.value + + def _get_yield_nodes_skip_lambdas(self): + yield self + + +class YieldFrom(Yield): # TODO value is required, not optional + """Class representing an :class:`ast.YieldFrom` node.""" + + +class DictUnpack(mixins.NoChildrenMixin, NodeNG): + """Represents the unpacking of dicts into dicts using :pep:`448`.""" + + +class FormattedValue(NodeNG): + """Class representing an :class:`ast.FormattedValue` node. + + Represents a :pep:`498` format string. + + >>> node = astroid.extract_node('f"Format {type_}"') + >>> node + <JoinedStr l.1 at 0x7f23b2e4ed30> + >>> node.values + [<Const.str l.1 at 0x7f23b2e4eda0>, <FormattedValue l.1 at 0x7f23b2e4edd8>] + """ + + _astroid_fields = ("value", "format_spec") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.value: NodeNG + """The value to be formatted into the string.""" + + self.conversion: Optional[int] = None # can be None + """The type of formatting to be applied to the value. + + .. seealso:: + :class:`ast.FormattedValue` + """ + + self.format_spec: Optional[NodeNG] = None # can be None + """The formatting to be applied to the value. + + .. seealso:: + :class:`ast.FormattedValue` + + :type: JoinedStr or None + """ + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + value: NodeNG, + conversion: Optional[int] = None, + format_spec: Optional[NodeNG] = None, + ) -> None: + """Do some setup after initialisation. + + :param value: The value to be formatted into the string. + + :param conversion: The type of formatting to be applied to the value. + + :param format_spec: The formatting to be applied to the value. + :type format_spec: JoinedStr or None + """ + self.value = value + self.conversion = conversion + self.format_spec = format_spec + + def get_children(self): + yield self.value + + if self.format_spec is not None: + yield self.format_spec + + +class JoinedStr(NodeNG): + """Represents a list of string expressions to be joined. + + >>> node = astroid.extract_node('f"Format {type_}"') + >>> node + <JoinedStr l.1 at 0x7f23b2e4ed30> + """ + + _astroid_fields = ("values",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.values: typing.List[NodeNG] = [] + """The string expressions to be joined. + + :type: list(FormattedValue or Const) + """ + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, values: Optional[typing.List[NodeNG]] = None) -> None: + """Do some setup after initialisation. + + :param value: The string expressions to be joined. + + :type: list(FormattedValue or Const) + """ + if values is not None: + self.values = values + + def get_children(self): + yield from self.values + + +class NamedExpr(mixins.AssignTypeMixin, NodeNG): + """Represents the assignment from the assignment expression + + >>> module = astroid.parse('if a := 1: pass') + >>> module.body[0].test + <NamedExpr l.1 at 0x7f23b2e4ed30> + """ + + _astroid_fields = ("target", "value") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + """ + :param lineno: The line that this node appears on in the source code. + + :param col_offset: The column that this node appears on in the + source code. + + :param parent: The parent node in the syntax tree. + """ + self.target: NodeNG + """The assignment target + + :type: Name + """ + + self.value: NodeNG + """The value that gets assigned in the expression""" + + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, target: NodeNG, value: NodeNG) -> None: + self.target = target + self.value = value + + +class Unknown(mixins.AssignTypeMixin, NodeNG): + """This node represents a node in a constructed AST where + introspection is not possible. At the moment, it's only used in + the args attribute of FunctionDef nodes where function signature + introspection failed. + """ + + name = "Unknown" + + def qname(self): + return "Unknown" + + def infer(self, context=None, **kwargs): + """Inference on an Unknown node immediately terminates.""" + yield util.Uninferable + + +class EvaluatedObject(NodeNG): + """Contains an object that has already been inferred + + This class is useful to pre-evaluate a particular node, + with the resulting class acting as the non-evaluated node. + """ + + name = "EvaluatedObject" + _astroid_fields = ("original",) + _other_fields = ("value",) + + def __init__( + self, original: NodeNG, value: typing.Union[NodeNG, util.Uninferable] + ) -> None: + self.original: NodeNG = original + """The original node that has already been evaluated""" + + self.value: typing.Union[NodeNG, util.Uninferable] = value + """The inferred value""" + + super().__init__( + lineno=self.original.lineno, + col_offset=self.original.col_offset, + parent=self.original.parent, + ) + + def infer(self, context=None, **kwargs): + yield self.value + + +# Pattern matching ####################################################### + + +class Match(Statement): + """Class representing a :class:`ast.Match` node. + + >>> node = astroid.extract_node(''' + match x: + case 200: + ... + case _: + ... + ''') + >>> node + <Match l.2 at 0x10c24e170> + """ + + _astroid_fields = ("subject", "cases") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + self.subject: NodeNG + self.cases: typing.List["MatchCase"] + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + *, + subject: NodeNG, + cases: typing.List["MatchCase"], + ) -> None: + self.subject = subject + self.cases = cases + + +class Pattern(NodeNG): + """Base class for all Pattern nodes.""" + + +class MatchCase(mixins.MultiLineBlockMixin, NodeNG): + """Class representing a :class:`ast.match_case` node. + + >>> node = astroid.extract_node(''' + match x: + case 200: + ... + ''') + >>> node.cases[0] + <MatchCase l.3 at 0x10c24e590> + """ + + _astroid_fields = ("pattern", "guard", "body") + _multi_line_block_fields = ("body",) + + def __init__(self, *, parent: Optional[NodeNG] = None) -> None: + self.pattern: Pattern + self.guard: Optional[NodeNG] + self.body: typing.List[NodeNG] + super().__init__(parent=parent) + + def postinit( + self, + *, + pattern: Pattern, + guard: Optional[NodeNG], + body: typing.List[NodeNG], + ) -> None: + self.pattern = pattern + self.guard = guard + self.body = body + + +class MatchValue(Pattern): + """Class representing a :class:`ast.MatchValue` node. + + >>> node = astroid.extract_node(''' + match x: + case 200: + ... + ''') + >>> node.cases[0].pattern + <MatchValue l.3 at 0x10c24e200> + """ + + _astroid_fields = ("value",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + self.value: NodeNG + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, *, value: NodeNG) -> None: + self.value = value + + +class MatchSingleton(Pattern): + """Class representing a :class:`ast.MatchSingleton` node. + + >>> node = astroid.extract_node(''' + match x: + case True: + ... + case False: + ... + case None: + ... + ''') + >>> node.cases[0].pattern + <MatchSingleton l.3 at 0x10c2282e0> + >>> node.cases[1].pattern + <MatchSingleton l.5 at 0x10c228af0> + >>> node.cases[2].pattern + <MatchSingleton l.7 at 0x10c229f90> + """ + + _other_fields = ("value",) + + def __init__( + self, + *, + value: Literal[True, False, None], + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + self.value: Literal[True, False, None] = value + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + +class MatchSequence(Pattern): + """Class representing a :class:`ast.MatchSequence` node. + + >>> node = astroid.extract_node(''' + match x: + case [1, 2]: + ... + case (1, 2, *_): + ... + ''') + >>> node.cases[0].pattern + <MatchSequence l.3 at 0x10ca80d00> + >>> node.cases[1].pattern + <MatchSequence l.5 at 0x10ca80b20> + """ + + _astroid_fields = ("patterns",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + self.patterns: typing.List[Pattern] + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, *, patterns: typing.List[Pattern]) -> None: + self.patterns = patterns + + +class MatchMapping(mixins.AssignTypeMixin, Pattern): + """Class representing a :class:`ast.MatchMapping` node. + + >>> node = astroid.extract_node(''' + match x: + case {1: "Hello", 2: "World", 3: _, **rest}: + ... + ''') + >>> node.cases[0].pattern + <MatchMapping l.3 at 0x10c8a8850> + """ + + _astroid_fields = ("keys", "patterns", "rest") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + self.keys: typing.List[NodeNG] + self.patterns: typing.List[Pattern] + self.rest: Optional[AssignName] + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + *, + keys: typing.List[NodeNG], + patterns: typing.List[Pattern], + rest: Optional[AssignName], + ) -> None: + self.keys = keys + self.patterns = patterns + self.rest = rest + + assigned_stmts: Callable[ + [ + "MatchMapping", + AssignName, + Optional[contextmod.InferenceContext], + Literal[None], + ], + Generator[NodeNG, None, None], + ] + + +class MatchClass(Pattern): + """Class representing a :class:`ast.MatchClass` node. + + >>> node = astroid.extract_node(''' + match x: + case Point2D(0, 0): + ... + case Point3D(x=0, y=0, z=0): + ... + ''') + >>> node.cases[0].pattern + <MatchClass l.3 at 0x10ca83940> + >>> node.cases[1].pattern + <MatchClass l.5 at 0x10ca80880> + """ + + _astroid_fields = ("cls", "patterns", "kwd_patterns") + _other_fields = ("kwd_attrs",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + self.cls: NodeNG + self.patterns: typing.List[Pattern] + self.kwd_attrs: typing.List[str] + self.kwd_patterns: typing.List[Pattern] + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + *, + cls: NodeNG, + patterns: typing.List[Pattern], + kwd_attrs: typing.List[str], + kwd_patterns: typing.List[Pattern], + ) -> None: + self.cls = cls + self.patterns = patterns + self.kwd_attrs = kwd_attrs + self.kwd_patterns = kwd_patterns + + +class MatchStar(mixins.AssignTypeMixin, Pattern): + """Class representing a :class:`ast.MatchStar` node. + + >>> node = astroid.extract_node(''' + match x: + case [1, *_]: + ... + ''') + >>> node.cases[0].pattern.patterns[1] + <MatchStar l.3 at 0x10ca809a0> + """ + + _astroid_fields = ("name",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + self.name: Optional[AssignName] + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, *, name: Optional[AssignName]) -> None: + self.name = name + + assigned_stmts: Callable[ + [ + "MatchStar", + AssignName, + Optional[contextmod.InferenceContext], + Literal[None], + ], + Generator[NodeNG, None, None], + ] + + +class MatchAs(mixins.AssignTypeMixin, Pattern): + """Class representing a :class:`ast.MatchAs` node. + + >>> node = astroid.extract_node(''' + match x: + case [1, a]: + ... + case {'key': b}: + ... + case Point2D(0, 0) as c: + ... + case d: + ... + ''') + >>> node.cases[0].pattern.patterns[1] + <MatchAs l.3 at 0x10d0b2da0> + >>> node.cases[1].pattern.patterns[0] + <MatchAs l.5 at 0x10d0b2920> + >>> node.cases[2].pattern + <MatchAs l.7 at 0x10d0b06a0> + >>> node.cases[3].pattern + <MatchAs l.9 at 0x10d09b880> + """ + + _astroid_fields = ("pattern", "name") + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + self.pattern: Optional[Pattern] + self.name: Optional[AssignName] + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit( + self, + *, + pattern: Optional[Pattern], + name: Optional[AssignName], + ) -> None: + self.pattern = pattern + self.name = name + + assigned_stmts: Callable[ + [ + "MatchAs", + AssignName, + Optional[contextmod.InferenceContext], + Literal[None], + ], + Generator[NodeNG, None, None], + ] + + +class MatchOr(Pattern): + """Class representing a :class:`ast.MatchOr` node. + + >>> node = astroid.extract_node(''' + match x: + case 400 | 401 | 402: + ... + ''') + >>> node.cases[0].pattern + <MatchOr l.3 at 0x10d0b0b50> + """ + + _astroid_fields = ("patterns",) + + def __init__( + self, + lineno: Optional[int] = None, + col_offset: Optional[int] = None, + parent: Optional[NodeNG] = None, + ) -> None: + self.patterns: typing.List[Pattern] + super().__init__(lineno=lineno, col_offset=col_offset, parent=parent) + + def postinit(self, *, patterns: typing.List[Pattern]) -> None: + self.patterns = patterns + + +# constants ############################################################## + +CONST_CLS = { + list: List, + tuple: Tuple, + dict: Dict, + set: Set, + type(None): Const, + type(NotImplemented): Const, + type(...): Const, +} + + +def _update_const_classes(): + """update constant classes, so the keys of CONST_CLS can be reused""" + klasses = (bool, int, float, complex, str, bytes) + for kls in klasses: + CONST_CLS[kls] = Const + + +_update_const_classes() + + +def _two_step_initialization(cls, value): + instance = cls() + instance.postinit(value) + return instance + + +def _dict_initialization(cls, value): + if isinstance(value, dict): + value = tuple(value.items()) + return _two_step_initialization(cls, value) + + +_CONST_CLS_CONSTRUCTORS = { + List: _two_step_initialization, + Tuple: _two_step_initialization, + Dict: _dict_initialization, + Set: _two_step_initialization, + Const: lambda cls, value: cls(value), +} + + +def const_factory(value): + """return an astroid node for a python value""" + # XXX we should probably be stricter here and only consider stuff in + # CONST_CLS or do better treatment: in case where value is not in CONST_CLS, + # we should rather recall the builder on this value than returning an empty + # node (another option being that const_factory shouldn't be called with something + # not in CONST_CLS) + assert not isinstance(value, NodeNG) + + # Hack for ignoring elements of a sequence + # or a mapping, in order to avoid transforming + # each element to an AST. This is fixed in 2.0 + # and this approach is a temporary hack. + if isinstance(value, (list, set, tuple, dict)): + elts = [] + else: + elts = value + + try: + initializer_cls = CONST_CLS[value.__class__] + initializer = _CONST_CLS_CONSTRUCTORS[initializer_cls] + return initializer(initializer_cls, elts) + except (KeyError, AttributeError): + node = EmptyNode() + node.object = value + return node + + +def is_from_decorator(node): + """Return True if the given node is the child of a decorator""" + parent = node.parent + while parent is not None: + if isinstance(parent, Decorators): + return True + parent = parent.parent + return False diff --git a/astroid/nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes.py new file mode 100644 index 00000000..84fbd09b --- /dev/null +++ b/astroid/nodes/scoped_nodes.py @@ -0,0 +1,3034 @@ +# Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> +# Copyright (c) 2010 Daniel Harding <dharding@gmail.com> +# Copyright (c) 2011, 2013-2015 Google, Inc. +# Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> +# Copyright (c) 2013 Phil Schaf <flying-sheep@web.de> +# Copyright (c) 2014 Eevee (Alex Munroe) <amunroe@yelp.com> +# Copyright (c) 2015-2016 Florian Bruhin <me@the-compiler.org> +# Copyright (c) 2015-2016 Ceridwen <ceridwenv@gmail.com> +# Copyright (c) 2015 Rene Zhang <rz99@cornell.edu> +# Copyright (c) 2015 Philip Lorenz <philip@bithub.de> +# Copyright (c) 2016-2017 Derek Gustafson <degustaf@gmail.com> +# Copyright (c) 2017-2018 Bryce Guinta <bryce.paul.guinta@gmail.com> +# Copyright (c) 2017-2018 Ashley Whetter <ashley@awhetter.co.uk> +# Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com> +# Copyright (c) 2017 David Euresti <david@dropbox.com> +# Copyright (c) 2018-2019 Nick Drozd <nicholasdrozd@gmail.com> +# Copyright (c) 2018 Ville Skyttä <ville.skytta@iki.fi> +# Copyright (c) 2018 Anthony Sottile <asottile@umich.edu> +# Copyright (c) 2018 HoverHell <hoverhell@gmail.com> +# Copyright (c) 2019 Hugo van Kemenade <hugovk@users.noreply.github.com> +# Copyright (c) 2019 Peter de Blanc <peter@standard.ai> +# Copyright (c) 2020-2021 hippo91 <guillaume.peillex@gmail.com> +# Copyright (c) 2020 Peter Kolbus <peter.kolbus@gmail.com> +# Copyright (c) 2020 Tim Martin <tim@asymptotic.co.uk> +# Copyright (c) 2020 Ram Rachum <ram@rachum.com> +# Copyright (c) 2021 doranid <ddandd@gmail.com> +# Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com> +# Copyright (c) 2021 David Liu <david@cs.toronto.edu> +# Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com> +# Copyright (c) 2021 Andrew Haigh <hello@nelf.in> +# Copyright (c) 2021 pre-commit-ci[bot] <bot@noreply.github.com> + +# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html +# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE + + +""" +This module contains the classes for "scoped" node, i.e. which are opening a +new local scope in the language definition : Module, ClassDef, FunctionDef (and +Lambda, GeneratorExp, DictComp and SetComp to some extent). +""" +import builtins +import io +import itertools +import typing +from typing import List, Optional + +from astroid import bases +from astroid import context as contextmod +from astroid import decorators as decorators_mod +from astroid import mixins, util +from astroid.const import BUILTINS, PY39_PLUS +from astroid.exceptions import ( + AstroidBuildingError, + AstroidTypeError, + AttributeInferenceError, + DuplicateBasesError, + InconsistentMroError, + InferenceError, + MroError, + TooManyLevelsError, +) +from astroid.interpreter.dunder_lookup import lookup +from astroid.interpreter.objectmodel import ClassModel, FunctionModel, ModuleModel +from astroid.manager import AstroidManager +from astroid.nodes import node_classes + +ITER_METHODS = ("__iter__", "__getitem__") +EXCEPTION_BASE_CLASSES = frozenset({"Exception", "BaseException"}) +objects = util.lazy_import("objects") +BUILTIN_DESCRIPTORS = frozenset( + {"classmethod", "staticmethod", "builtins.classmethod", "builtins.staticmethod"} +) + + +def _c3_merge(sequences, cls, context): + """Merges MROs in *sequences* to a single MRO using the C3 algorithm. + + Adapted from http://www.python.org/download/releases/2.3/mro/. + + """ + result = [] + while True: + sequences = [s for s in sequences if s] # purge empty sequences + if not sequences: + return result + for s1 in sequences: # find merge candidates among seq heads + candidate = s1[0] + for s2 in sequences: + if candidate in s2[1:]: + candidate = None + break # reject the current head, it appears later + else: + break + if not candidate: + # Show all the remaining bases, which were considered as + # candidates for the next mro sequence. + raise InconsistentMroError( + message="Cannot create a consistent method resolution order " + "for MROs {mros} of class {cls!r}.", + mros=sequences, + cls=cls, + context=context, + ) + + result.append(candidate) + # remove the chosen candidate + for seq in sequences: + if seq[0] == candidate: + del seq[0] + return None + + +def clean_typing_generic_mro(sequences: List[List["ClassDef"]]) -> None: + """A class can inherit from typing.Generic directly, as base, + and as base of bases. The merged MRO must however only contain the last entry. + To prepare for _c3_merge, remove some typing.Generic entries from + sequences if multiple are present. + + This method will check if Generic is in inferred_bases and also + part of bases_mro. If true, remove it from inferred_bases + as well as its entry the bases_mro. + + Format sequences: [[self]] + bases_mro + [inferred_bases] + """ + bases_mro = sequences[1:-1] + inferred_bases = sequences[-1] + # Check if Generic is part of inferred_bases + for i, base in enumerate(inferred_bases): + if base.qname() == "typing.Generic": + position_in_inferred_bases = i + break + else: + return + # Check if also part of bases_mro + # Ignore entry for typing.Generic + for i, seq in enumerate(bases_mro): + if i == position_in_inferred_bases: + continue + if any(base.qname() == "typing.Generic" for base in seq): + break + else: + return + # Found multiple Generics in mro, remove entry from inferred_bases + # and the corresponding one from bases_mro + inferred_bases.pop(position_in_inferred_bases) + bases_mro.pop(position_in_inferred_bases) + + +def clean_duplicates_mro(sequences, cls, context): + for sequence in sequences: + names = [ + (node.lineno, node.qname()) if node.name else None for node in sequence + ] + last_index = dict(map(reversed, enumerate(names))) + if names and names[0] is not None and last_index[names[0]] != 0: + raise DuplicateBasesError( + message="Duplicates found in MROs {mros} for {cls!r}.", + mros=sequences, + cls=cls, + context=context, + ) + yield [ + node + for i, (node, name) in enumerate(zip(sequence, names)) + if name is None or last_index[name] == i + ] + + +def function_to_method(n, klass): + if isinstance(n, FunctionDef): + if n.type == "classmethod": + return bases.BoundMethod(n, klass) + if n.type == "property": + return n + if n.type != "staticmethod": + return bases.UnboundMethod(n) + return n + + +def builtin_lookup(name): + """lookup a name into the builtin module + return the list of matching statements and the astroid for the builtin + module + """ + builtin_astroid = AstroidManager().ast_from_module(builtins) + if name == "__dict__": + return builtin_astroid, () + try: + stmts = builtin_astroid.locals[name] + except KeyError: + stmts = () + return builtin_astroid, stmts + + +# TODO move this Mixin to mixins.py; problem: 'FunctionDef' in _scope_lookup +class LocalsDictNodeNG(node_classes.LookupMixIn, node_classes.NodeNG): + """this class provides locals handling common to Module, FunctionDef + and ClassDef nodes, including a dict like interface for direct access + to locals information + """ + + # attributes below are set by the builder module or by raw factories + + locals = {} + """A map of the name of a local variable to the node defining the local. + + :type: dict(str, NodeNG) + """ + + def qname(self): + """Get the 'qualified' name of the node. + + For example: module.name, module.class.name ... + + :returns: The qualified name. + :rtype: str + """ + # pylint: disable=no-member; github.com/pycqa/astroid/issues/278 + if self.parent is None: + return self.name + return f"{self.parent.frame().qname()}.{self.name}" + + def frame(self): + """The first parent frame node. + + A frame node is a :class:`Module`, :class:`FunctionDef`, + or :class:`ClassDef`. + + :returns: The first parent frame node. + :rtype: Module or FunctionDef or ClassDef + """ + return self + + def scope(self): + """The first parent node defining a new scope. + + :returns: The first parent scope node. + :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr + """ + return self + + def _scope_lookup(self, node, name, offset=0): + """XXX method for interfacing the scope lookup""" + try: + stmts = node._filter_stmts(self.locals[name], self, offset) + except KeyError: + stmts = () + if stmts: + return self, stmts + + # Handle nested scopes: since class names do not extend to nested + # scopes (e.g., methods), we find the next enclosing non-class scope + pscope = self.parent and self.parent.scope() + while pscope is not None: + if not isinstance(pscope, ClassDef): + return pscope.scope_lookup(node, name) + pscope = pscope.parent and pscope.parent.scope() + + # self is at the top level of a module, or is enclosed only by ClassDefs + return builtin_lookup(name) + + def set_local(self, name, stmt): + """Define that the given name is declared in the given statement node. + + .. seealso:: :meth:`scope` + + :param name: The name that is being defined. + :type name: str + + :param stmt: The statement that defines the given name. + :type stmt: NodeNG + """ + # assert not stmt in self.locals.get(name, ()), (self, stmt) + self.locals.setdefault(name, []).append(stmt) + + __setitem__ = set_local + + def _append_node(self, child): + """append a child, linking it in the tree""" + # pylint: disable=no-member; depending by the class + # which uses the current class as a mixin or base class. + # It's rewritten in 2.0, so it makes no sense for now + # to spend development time on it. + self.body.append(child) + child.parent = self + + def add_local_node(self, child_node, name=None): + """Append a child that should alter the locals of this scope node. + + :param child_node: The child node that will alter locals. + :type child_node: NodeNG + + :param name: The name of the local that will be altered by + the given child node. + :type name: str or None + """ + if name != "__class__": + # add __class__ node as a child will cause infinite recursion later! + self._append_node(child_node) + self.set_local(name or child_node.name, child_node) + + def __getitem__(self, item): + """The first node the defines the given local. + + :param item: The name of the locally defined object. + :type item: str + + :raises KeyError: If the name is not defined. + """ + return self.locals[item][0] + + def __iter__(self): + """Iterate over the names of locals defined in this scoped node. + + :returns: The names of the defined locals. + :rtype: iterable(str) + """ + return iter(self.keys()) + + def keys(self): + """The names of locals defined in this scoped node. + + :returns: The names of the defined locals. + :rtype: list(str) + """ + return list(self.locals.keys()) + + def values(self): + """The nodes that define the locals in this scoped node. + + :returns: The nodes that define locals. + :rtype: list(NodeNG) + """ + # pylint: disable=consider-using-dict-items + # It look like this class override items/keys/values, + # probably not worth the headache + return [self[key] for key in self.keys()] + + def items(self): + """Get the names of the locals and the node that defines the local. + + :returns: The names of locals and their associated node. + :rtype: list(tuple(str, NodeNG)) + """ + return list(zip(self.keys(), self.values())) + + def __contains__(self, name): + """Check if a local is defined in this scope. + + :param name: The name of the local to check for. + :type name: str + + :returns: True if this node has a local of the given name, + False otherwise. + :rtype: bool + """ + return name in self.locals + + +class Module(LocalsDictNodeNG): + """Class representing an :class:`ast.Module` node. + + >>> node = astroid.extract_node('import astroid') + >>> node + <Import l.1 at 0x7f23b2e4e5c0> + >>> node.parent + <Module l.0 at 0x7f23b2e4eda0> + """ + + _astroid_fields = ("body",) + + fromlineno = 0 + """The first line that this node appears on in the source code. + + :type: int or None + """ + lineno = 0 + """The line that this node appears on in the source code. + + :type: int or None + """ + + # attributes below are set by the builder module or by raw factories + + file = None + """The path to the file that this ast has been extracted from. + + This will be ``None`` when the representation has been built from a + built-in module. + + :type: str or None + """ + file_bytes = None + """The string/bytes that this ast was built from. + + :type: str or bytes or None + """ + file_encoding = None + """The encoding of the source file. + + This is used to get unicode out of a source file. + Python 2 only. + + :type: str or None + """ + name = None + """The name of the module. + + :type: str or None + """ + pure_python = None + """Whether the ast was built from source. + + :type: bool or None + """ + package = None + """Whether the node represents a package or a module. + + :type: bool or None + """ + globals = None + """A map of the name of a global variable to the node defining the global. + + :type: dict(str, NodeNG) + """ + + # Future imports + future_imports = None + """The imports from ``__future__``. + + :type: set(str) or None + """ + special_attributes = ModuleModel() + """The names of special attributes that this module has. + + :type: objectmodel.ModuleModel + """ + + # names of module attributes available through the global scope + scope_attrs = {"__name__", "__doc__", "__file__", "__path__", "__package__"} + """The names of module attributes available through the global scope. + + :type: str(str) + """ + + _other_fields = ( + "name", + "doc", + "file", + "path", + "package", + "pure_python", + "future_imports", + ) + _other_other_fields = ("locals", "globals") + + def __init__( + self, + name, + doc, + file=None, + path: Optional[List[str]] = None, + package=None, + parent=None, + pure_python=True, + ): + """ + :param name: The name of the module. + :type name: str + + :param doc: The module docstring. + :type doc: str + + :param file: The path to the file that this ast has been extracted from. + :type file: str or None + + :param path: + :type path: Optional[List[str]] + + :param package: Whether the node represents a package or a module. + :type package: bool or None + + :param parent: The parent node in the syntax tree. + :type parent: NodeNG or None + + :param pure_python: Whether the ast was built from source. + :type pure_python: bool or None + """ + self.name = name + self.doc = doc + self.file = file + self.path = path + self.package = package + self.parent = parent + self.pure_python = pure_python + self.locals = self.globals = {} + """A map of the name of a local variable to the node defining the local. + + :type: dict(str, NodeNG) + """ + self.body = [] + """The contents of the module. + + :type: list(NodeNG) or None + """ + self.future_imports = set() + + # pylint: enable=redefined-builtin + + def postinit(self, body=None): + """Do some setup after initialisation. + + :param body: The contents of the module. + :type body: list(NodeNG) or None + """ + self.body = body + + def _get_stream(self): + if self.file_bytes is not None: + return io.BytesIO(self.file_bytes) + if self.file is not None: + # pylint: disable=consider-using-with + stream = open(self.file, "rb") + return stream + return None + + def stream(self): + """Get a stream to the underlying file or bytes. + + :type: file or io.BytesIO or None + """ + return self._get_stream() + + def block_range(self, lineno): + """Get a range from where this node starts to where this node ends. + + :param lineno: Unused. + :type lineno: int + + :returns: The range of line numbers that this node belongs to. + :rtype: tuple(int, int) + """ + return self.fromlineno, self.tolineno + + def scope_lookup(self, node, name, offset=0): + """Lookup where the given variable is assigned. + + :param node: The node to look for assignments up to. + Any assignments after the given node are ignored. + :type node: NodeNG + + :param name: The name of the variable to find assignments for. + :type name: str + + :param offset: The line offset to filter statements up to. + :type offset: int + + :returns: This scope node and the list of assignments associated to the + given name according to the scope where it has been found (locals, + globals or builtin). + :rtype: tuple(str, list(NodeNG)) + """ + if name in self.scope_attrs and name not in self.locals: + try: + return self, self.getattr(name) + except AttributeInferenceError: + return self, () + return self._scope_lookup(node, name, offset) + + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + return "%s.module" % BUILTINS + + def display_type(self): + """A human readable type of this node. + + :returns: The type of this node. + :rtype: str + """ + return "Module" + + def getattr(self, name, context=None, ignore_locals=False): + if not name: + raise AttributeInferenceError(target=self, attribute=name, context=context) + + result = [] + name_in_locals = name in self.locals + + if name in self.special_attributes and not ignore_locals and not name_in_locals: + result = [self.special_attributes.lookup(name)] + elif not ignore_locals and name_in_locals: + result = self.locals[name] + elif self.package: + try: + result = [self.import_module(name, relative_only=True)] + except (AstroidBuildingError, SyntaxError) as exc: + raise AttributeInferenceError( + target=self, attribute=name, context=context + ) from exc + result = [n for n in result if not isinstance(n, node_classes.DelName)] + if result: + return result + raise AttributeInferenceError(target=self, attribute=name, context=context) + + def igetattr(self, name, context=None): + """Infer the possible values of the given variable. + + :param name: The name of the variable to infer. + :type name: str + + :returns: The inferred possible values. + :rtype: iterable(NodeNG) or None + """ + # set lookup name since this is necessary to infer on import nodes for + # instance + context = contextmod.copy_context(context) + context.lookupname = name + try: + return bases._infer_stmts(self.getattr(name, context), context, frame=self) + except AttributeInferenceError as error: + raise InferenceError( + str(error), target=self, attribute=name, context=context + ) from error + + def fully_defined(self): + """Check if this module has been build from a .py file. + + If so, the module contains a complete representation, + including the code. + + :returns: True if the module has been built from a .py file. + :rtype: bool + """ + return self.file is not None and self.file.endswith(".py") + + def statement(self): + """The first parent node, including self, marked as statement node. + + :returns: The first parent statement. + :rtype: NodeNG + """ + return self + + def previous_sibling(self): + """The previous sibling statement. + + :returns: The previous sibling statement node. + :rtype: NodeNG or None + """ + + def next_sibling(self): + """The next sibling statement node. + + :returns: The next sibling statement node. + :rtype: NodeNG or None + """ + + _absolute_import_activated = True + + def absolute_import_activated(self): + """Whether :pep:`328` absolute import behaviour has been enabled. + + :returns: True if :pep:`328` has been enabled, False otherwise. + :rtype: bool + """ + return self._absolute_import_activated + + def import_module(self, modname, relative_only=False, level=None): + """Get the ast for a given module as if imported from this module. + + :param modname: The name of the module to "import". + :type modname: str + + :param relative_only: Whether to only consider relative imports. + :type relative_only: bool + + :param level: The level of relative import. + :type level: int or None + + :returns: The imported module ast. + :rtype: NodeNG + """ + if relative_only and level is None: + level = 0 + absmodname = self.relative_to_absolute_name(modname, level) + + try: + return AstroidManager().ast_from_module_name(absmodname) + except AstroidBuildingError: + # we only want to import a sub module or package of this module, + # skip here + if relative_only: + raise + return AstroidManager().ast_from_module_name(modname) + + def relative_to_absolute_name(self, modname, level): + """Get the absolute module name for a relative import. + + The relative import can be implicit or explicit. + + :param modname: The module name to convert. + :type modname: str + + :param level: The level of relative import. + :type level: int + + :returns: The absolute module name. + :rtype: str + + :raises TooManyLevelsError: When the relative import refers to a + module too far above this one. + """ + # XXX this returns non sens when called on an absolute import + # like 'pylint.checkers.astroid.utils' + # XXX doesn't return absolute name if self.name isn't absolute name + if self.absolute_import_activated() and level is None: + return modname + if level: + if self.package: + level = level - 1 + if level and self.name.count(".") < level: + raise TooManyLevelsError(level=level, name=self.name) + + package_name = self.name.rsplit(".", level)[0] + elif self.package: + package_name = self.name + else: + package_name = self.name.rsplit(".", 1)[0] + + if package_name: + if not modname: + return package_name + return f"{package_name}.{modname}" + return modname + + def wildcard_import_names(self): + """The list of imported names when this module is 'wildcard imported'. + + It doesn't include the '__builtins__' name which is added by the + current CPython implementation of wildcard imports. + + :returns: The list of imported names. + :rtype: list(str) + """ + # We separate the different steps of lookup in try/excepts + # to avoid catching too many Exceptions + default = [name for name in self.keys() if not name.startswith("_")] + try: + all_values = self["__all__"] + except KeyError: + return default + + try: + explicit = next(all_values.assigned_stmts()) + except (InferenceError, StopIteration): + return default + except AttributeError: + # not an assignment node + # XXX infer? + return default + + # Try our best to detect the exported name. + inferred = [] + try: + explicit = next(explicit.infer()) + except (InferenceError, StopIteration): + return default + if not isinstance(explicit, (node_classes.Tuple, node_classes.List)): + return default + + def str_const(node): + return isinstance(node, node_classes.Const) and isinstance(node.value, str) + + for node in explicit.elts: + if str_const(node): + inferred.append(node.value) + else: + try: + inferred_node = next(node.infer()) + except (InferenceError, StopIteration): + continue + if str_const(inferred_node): + inferred.append(inferred_node.value) + return inferred + + def public_names(self): + """The list of the names that are publicly available in this module. + + :returns: The list of publc names. + :rtype: list(str) + """ + return [name for name in self.keys() if not name.startswith("_")] + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + For a :class:`Module` this is always ``True``. + :rtype: bool + """ + return True + + def get_children(self): + yield from self.body + + +class ComprehensionScope(LocalsDictNodeNG): + """Scoping for different types of comprehensions.""" + + def frame(self): + """The first parent frame node. + + A frame node is a :class:`Module`, :class:`FunctionDef`, + or :class:`ClassDef`. + + :returns: The first parent frame node. + :rtype: Module or FunctionDef or ClassDef + """ + return self.parent.frame() + + scope_lookup = LocalsDictNodeNG._scope_lookup + + +class GeneratorExp(ComprehensionScope): + """Class representing an :class:`ast.GeneratorExp` node. + + >>> node = astroid.extract_node('(thing for thing in things if thing)') + >>> node + <GeneratorExp l.1 at 0x7f23b2e4e400> + """ + + _astroid_fields = ("elt", "generators") + _other_other_fields = ("locals",) + elt = None + """The element that forms the output of the expression. + + :type: NodeNG or None + """ + generators = None + """The generators that are looped through. + + :type: list(Comprehension) or None + """ + + def __init__(self, lineno=None, col_offset=None, parent=None): + """ + :param lineno: The line that this node appears on in the source code. + :type lineno: int or None + + :param col_offset: The column that this node appears on in the + source code. + :type col_offset: int or None + + :param parent: The parent node in the syntax tree. + :type parent: NodeNG or None + """ + self.locals = {} + """A map of the name of a local variable to the node defining the local. + + :type: dict(str, NodeNG) + """ + + super().__init__(lineno, col_offset, parent) + + def postinit(self, elt=None, generators=None): + """Do some setup after initialisation. + + :param elt: The element that forms the output of the expression. + :type elt: NodeNG or None + + :param generators: The generators that are looped through. + :type generators: list(Comprehension) or None + """ + self.elt = elt + if generators is None: + self.generators = [] + else: + self.generators = generators + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + For a :class:`GeneratorExp` this is always ``True``. + :rtype: bool + """ + return True + + def get_children(self): + yield self.elt + + yield from self.generators + + +class DictComp(ComprehensionScope): + """Class representing an :class:`ast.DictComp` node. + + >>> node = astroid.extract_node('{k:v for k, v in things if k > v}') + >>> node + <DictComp l.1 at 0x7f23b2e41d68> + """ + + _astroid_fields = ("key", "value", "generators") + _other_other_fields = ("locals",) + key = None + """What produces the keys. + + :type: NodeNG or None + """ + value = None + """What produces the values. + + :type: NodeNG or None + """ + generators = None + """The generators that are looped through. + + :type: list(Comprehension) or None + """ + + def __init__(self, lineno=None, col_offset=None, parent=None): + """ + :param lineno: The line that this node appears on in the source code. + :type lineno: int or None + + :param col_offset: The column that this node appears on in the + source code. + :type col_offset: int or None + + :param parent: The parent node in the syntax tree. + :type parent: NodeNG or None + """ + self.locals = {} + """A map of the name of a local variable to the node defining the local. + + :type: dict(str, NodeNG) + """ + + super().__init__(lineno, col_offset, parent) + + def postinit(self, key=None, value=None, generators=None): + """Do some setup after initialisation. + + :param key: What produces the keys. + :type key: NodeNG or None + + :param value: What produces the values. + :type value: NodeNG or None + + :param generators: The generators that are looped through. + :type generators: list(Comprehension) or None + """ + self.key = key + self.value = value + if generators is None: + self.generators = [] + else: + self.generators = generators + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + For a :class:`DictComp` this is always :class:`Uninferable`. + :rtype: Uninferable + """ + return util.Uninferable + + def get_children(self): + yield self.key + yield self.value + + yield from self.generators + + +class SetComp(ComprehensionScope): + """Class representing an :class:`ast.SetComp` node. + + >>> node = astroid.extract_node('{thing for thing in things if thing}') + >>> node + <SetComp l.1 at 0x7f23b2e41898> + """ + + _astroid_fields = ("elt", "generators") + _other_other_fields = ("locals",) + elt = None + """The element that forms the output of the expression. + + :type: NodeNG or None + """ + generators = None + """The generators that are looped through. + + :type: list(Comprehension) or None + """ + + def __init__(self, lineno=None, col_offset=None, parent=None): + """ + :param lineno: The line that this node appears on in the source code. + :type lineno: int or None + + :param col_offset: The column that this node appears on in the + source code. + :type col_offset: int or None + + :param parent: The parent node in the syntax tree. + :type parent: NodeNG or None + """ + self.locals = {} + """A map of the name of a local variable to the node defining the local. + + :type: dict(str, NodeNG) + """ + + super().__init__(lineno, col_offset, parent) + + def postinit(self, elt=None, generators=None): + """Do some setup after initialisation. + + :param elt: The element that forms the output of the expression. + :type elt: NodeNG or None + + :param generators: The generators that are looped through. + :type generators: list(Comprehension) or None + """ + self.elt = elt + if generators is None: + self.generators = [] + else: + self.generators = generators + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + For a :class:`SetComp` this is always :class:`Uninferable`. + :rtype: Uninferable + """ + return util.Uninferable + + def get_children(self): + yield self.elt + + yield from self.generators + + +class _ListComp(node_classes.NodeNG): + """Class representing an :class:`ast.ListComp` node. + + >>> node = astroid.extract_node('[thing for thing in things if thing]') + >>> node + <ListComp l.1 at 0x7f23b2e418d0> + """ + + _astroid_fields = ("elt", "generators") + elt = None + """The element that forms the output of the expression. + + :type: NodeNG or None + """ + generators = None + """The generators that are looped through. + + :type: list(Comprehension) or None + """ + + def postinit(self, elt=None, generators=None): + """Do some setup after initialisation. + + :param elt: The element that forms the output of the expression. + :type elt: NodeNG or None + + :param generators: The generators that are looped through. + :type generators: list(Comprehension) or None + """ + self.elt = elt + self.generators = generators + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + For a :class:`ListComp` this is always :class:`Uninferable`. + :rtype: Uninferable + """ + return util.Uninferable + + def get_children(self): + yield self.elt + + yield from self.generators + + +class ListComp(_ListComp, ComprehensionScope): + """Class representing an :class:`ast.ListComp` node. + + >>> node = astroid.extract_node('[thing for thing in things if thing]') + >>> node + <ListComp l.1 at 0x7f23b2e418d0> + """ + + _other_other_fields = ("locals",) + + def __init__(self, lineno=None, col_offset=None, parent=None): + self.locals = {} + """A map of the name of a local variable to the node defining it. + + :type: dict(str, NodeNG) + """ + + super().__init__(lineno, col_offset, parent) + + +def _infer_decorator_callchain(node): + """Detect decorator call chaining and see if the end result is a + static or a classmethod. + """ + if not isinstance(node, FunctionDef): + return None + if not node.parent: + return None + try: + result = next(node.infer_call_result(node.parent), None) + except InferenceError: + return None + if isinstance(result, bases.Instance): + result = result._proxied + if isinstance(result, ClassDef): + if result.is_subtype_of("%s.classmethod" % BUILTINS): + return "classmethod" + if result.is_subtype_of("%s.staticmethod" % BUILTINS): + return "staticmethod" + if isinstance(result, FunctionDef): + if not result.decorators: + return None + # Determine if this function is decorated with one of the builtin descriptors we want. + for decorator in result.decorators.nodes: + if isinstance(decorator, node_classes.Name): + if decorator.name in BUILTIN_DESCRIPTORS: + return decorator.name + if ( + isinstance(decorator, node_classes.Attribute) + and isinstance(decorator.expr, node_classes.Name) + and decorator.expr.name == BUILTINS + and decorator.attrname in BUILTIN_DESCRIPTORS + ): + return decorator.attrname + return None + + +class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG): + """Class representing an :class:`ast.Lambda` node. + + >>> node = astroid.extract_node('lambda arg: arg + 1') + >>> node + <Lambda.<lambda> l.1 at 0x7f23b2e41518> + """ + + _astroid_fields = ("args", "body") + _other_other_fields = ("locals",) + name = "<lambda>" + is_lambda = True + + def implicit_parameters(self): + return 0 + + # function's type, 'function' | 'method' | 'staticmethod' | 'classmethod' + @property + def type(self): + """Whether this is a method or function. + + :returns: 'method' if this is a method, 'function' otherwise. + :rtype: str + """ + # pylint: disable=no-member + if self.args.arguments and self.args.arguments[0].name == "self": + if isinstance(self.parent.scope(), ClassDef): + return "method" + return "function" + + def __init__(self, lineno=None, col_offset=None, parent=None): + """ + :param lineno: The line that this node appears on in the source code. + :type lineno: int or None + + :param col_offset: The column that this node appears on in the + source code. + :type col_offset: int or None + + :param parent: The parent node in the syntax tree. + :type parent: NodeNG or None + """ + self.locals = {} + """A map of the name of a local variable to the node defining it. + + :type: dict(str, NodeNG) + """ + + self.args = [] + """The arguments that the function takes. + + :type: Arguments or list + """ + + self.body = [] + """The contents of the function body. + + :type: list(NodeNG) + """ + + super().__init__(lineno, col_offset, parent) + + def postinit(self, args, body): + """Do some setup after initialisation. + + :param args: The arguments that the function takes. + :type args: Arguments + + :param body: The contents of the function body. + :type body: list(NodeNG) + """ + self.args = args + self.body = body + + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + if "method" in self.type: + return "%s.instancemethod" % BUILTINS + return "%s.function" % BUILTINS + + def display_type(self): + """A human readable type of this node. + + :returns: The type of this node. + :rtype: str + """ + if "method" in self.type: + return "Method" + return "Function" + + def callable(self): + """Whether this node defines something that is callable. + + :returns: True if this defines something that is callable, + False otherwise. + For a :class:`Lambda` this is always ``True``. + :rtype: bool + """ + return True + + def argnames(self): + """Get the names of each of the arguments. + + :returns: The names of the arguments. + :rtype: list(str) + """ + # pylint: disable=no-member; github.com/pycqa/astroid/issues/291 + # args is in fact redefined later on by postinit. Can't be changed + # to None due to a strong interaction between Lambda and FunctionDef. + + if self.args.arguments: # maybe None with builtin functions + names = _rec_get_names(self.args.arguments) + else: + names = [] + if self.args.vararg: + names.append(self.args.vararg) + if self.args.kwarg: + names.append(self.args.kwarg) + return names + + def infer_call_result(self, caller, context=None): + """Infer what the function returns when called. + + :param caller: Unused + :type caller: object + """ + # pylint: disable=no-member; github.com/pycqa/astroid/issues/291 + # args is in fact redefined later on by postinit. Can't be changed + # to None due to a strong interaction between Lambda and FunctionDef. + return self.body.infer(context) + + def scope_lookup(self, node, name, offset=0): + """Lookup where the given names is assigned. + + :param node: The node to look for assignments up to. + Any assignments after the given node are ignored. + :type node: NodeNG + + :param name: The name to find assignments for. + :type name: str + + :param offset: The line offset to filter statements up to. + :type offset: int + + :returns: This scope node and the list of assignments associated to the + given name according to the scope where it has been found (locals, + globals or builtin). + :rtype: tuple(str, list(NodeNG)) + """ + # pylint: disable=no-member; github.com/pycqa/astroid/issues/291 + # args is in fact redefined later on by postinit. Can't be changed + # to None due to a strong interaction between Lambda and FunctionDef. + + if node in self.args.defaults or node in self.args.kw_defaults: + frame = self.parent.frame() + # line offset to avoid that def func(f=func) resolve the default + # value to the defined function + offset = -1 + else: + # check this is not used in function decorators + frame = self + return frame._scope_lookup(node, name, offset) + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + For a :class:`Lambda` this is always ``True``. + :rtype: bool + """ + return True + + def get_children(self): + yield self.args + yield self.body + + +class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda): + """Class representing an :class:`ast.FunctionDef`. + + >>> node = astroid.extract_node(''' + ... def my_func(arg): + ... return arg + 1 + ... ''') + >>> node + <FunctionDef.my_func l.2 at 0x7f23b2e71e10> + """ + + _astroid_fields = ("decorators", "args", "returns", "body") + _multi_line_block_fields = ("body",) + returns = None + decorators = None + """The decorators that are applied to this method or function. + + :type: Decorators or None + """ + special_attributes = FunctionModel() + """The names of special attributes that this function has. + + :type: objectmodel.FunctionModel + """ + is_function = True + """Whether this node indicates a function. + + For a :class:`FunctionDef` this is always ``True``. + + :type: bool + """ + type_annotation = None + """If present, this will contain the type annotation passed by a type comment + + :type: NodeNG or None + """ + type_comment_args = None + """ + If present, this will contain the type annotation for arguments + passed by a type comment + """ + type_comment_returns = None + """If present, this will contain the return type annotation, passed by a type comment""" + # attributes below are set by the builder module or by raw factories + _other_fields = ("name", "doc") + _other_other_fields = ( + "locals", + "_type", + "type_comment_returns", + "type_comment_args", + ) + _type = None + + def __init__(self, name=None, doc=None, lineno=None, col_offset=None, parent=None): + """ + :param name: The name of the function. + :type name: str or None + + :param doc: The function's docstring. + :type doc: str or None + + :param lineno: The line that this node appears on in the source code. + :type lineno: int or None + + :param col_offset: The column that this node appears on in the + source code. + :type col_offset: int or None + + :param parent: The parent node in the syntax tree. + :type parent: NodeNG or None + """ + self.name = name + """The name of the function. + + :type name: str or None + """ + + self.doc = doc + """The function's docstring. + + :type doc: str or None + """ + + self.instance_attrs = {} + super().__init__(lineno, col_offset, parent) + if parent: + frame = parent.frame() + frame.set_local(name, self) + + # pylint: disable=arguments-differ; different than Lambdas + def postinit( + self, + args, + body, + decorators=None, + returns=None, + type_comment_returns=None, + type_comment_args=None, + ): + """Do some setup after initialisation. + + :param args: The arguments that the function takes. + :type args: Arguments or list + + :param body: The contents of the function body. + :type body: list(NodeNG) + + :param decorators: The decorators that are applied to this + method or function. + :type decorators: Decorators or None + :params type_comment_returns: + The return type annotation passed via a type comment. + :params type_comment_args: + The args type annotation passed via a type comment. + """ + self.args = args + self.body = body + self.decorators = decorators + self.returns = returns + self.type_comment_returns = type_comment_returns + self.type_comment_args = type_comment_args + + @decorators_mod.cachedproperty + def extra_decorators(self): + """The extra decorators that this function can have. + + Additional decorators are considered when they are used as + assignments, as in ``method = staticmethod(method)``. + The property will return all the callables that are used for + decoration. + + :type: list(NodeNG) + """ + frame = self.parent.frame() + if not isinstance(frame, ClassDef): + return [] + + decorators = [] + for assign in frame._get_assign_nodes(): + if isinstance(assign.value, node_classes.Call) and isinstance( + assign.value.func, node_classes.Name + ): + for assign_node in assign.targets: + if not isinstance(assign_node, node_classes.AssignName): + # Support only `name = callable(name)` + continue + + if assign_node.name != self.name: + # Interested only in the assignment nodes that + # decorates the current method. + continue + try: + meth = frame[self.name] + except KeyError: + continue + else: + # Must be a function and in the same frame as the + # original method. + if ( + isinstance(meth, FunctionDef) + and assign_node.frame() == frame + ): + decorators.append(assign.value) + return decorators + + @decorators_mod.cachedproperty + def type( + self, + ): # pylint: disable=invalid-overridden-method,too-many-return-statements + """The function type for this node. + + Possible values are: method, function, staticmethod, classmethod. + + :type: str + """ + for decorator in self.extra_decorators: + if decorator.func.name in BUILTIN_DESCRIPTORS: + return decorator.func.name + + frame = self.parent.frame() + type_name = "function" + if isinstance(frame, ClassDef): + if self.name == "__new__": + return "classmethod" + if self.name == "__init_subclass__": + return "classmethod" + + type_name = "method" + + if not self.decorators: + return type_name + + for node in self.decorators.nodes: + if isinstance(node, node_classes.Name): + if node.name in BUILTIN_DESCRIPTORS: + return node.name + if ( + isinstance(node, node_classes.Attribute) + and isinstance(node.expr, node_classes.Name) + and node.expr.name == BUILTINS + and node.attrname in BUILTIN_DESCRIPTORS + ): + return node.attrname + + if isinstance(node, node_classes.Call): + # Handle the following case: + # @some_decorator(arg1, arg2) + # def func(...) + # + try: + current = next(node.func.infer()) + except (InferenceError, StopIteration): + continue + _type = _infer_decorator_callchain(current) + if _type is not None: + return _type + + try: + for inferred in node.infer(): + # Check to see if this returns a static or a class method. + _type = _infer_decorator_callchain(inferred) + if _type is not None: + return _type + + if not isinstance(inferred, ClassDef): + continue + for ancestor in inferred.ancestors(): + if not isinstance(ancestor, ClassDef): + continue + if ancestor.is_subtype_of("%s.classmethod" % BUILTINS): + return "classmethod" + if ancestor.is_subtype_of("%s.staticmethod" % BUILTINS): + return "staticmethod" + except InferenceError: + pass + return type_name + + @decorators_mod.cachedproperty + def fromlineno(self): + """The first line that this node appears on in the source code. + + :type: int or None + """ + # lineno is the line number of the first decorator, we want the def + # statement lineno + lineno = self.lineno + if self.decorators is not None: + lineno += sum( + node.tolineno - node.lineno + 1 for node in self.decorators.nodes + ) + + return lineno + + @decorators_mod.cachedproperty + def blockstart_tolineno(self): + """The line on which the beginning of this block ends. + + :type: int + """ + return self.args.tolineno + + def block_range(self, lineno): + """Get a range from the given line number to where this node ends. + + :param lineno: Unused. + :type lineno: int + + :returns: The range of line numbers that this node belongs to, + :rtype: tuple(int, int) + """ + return self.fromlineno, self.tolineno + + def getattr(self, name, context=None): + """this method doesn't look in the instance_attrs dictionary since it's + done by an Instance proxy at inference time. + """ + if not name: + raise AttributeInferenceError(target=self, attribute=name, context=context) + + found_attrs = [] + if name in self.instance_attrs: + found_attrs = self.instance_attrs[name] + if name in self.special_attributes: + found_attrs.append(self.special_attributes.lookup(name)) + if found_attrs: + return found_attrs + raise AttributeInferenceError(target=self, attribute=name) + + def igetattr(self, name, context=None): + """Inferred getattr, which returns an iterator of inferred statements.""" + try: + return bases._infer_stmts(self.getattr(name, context), context, frame=self) + except AttributeInferenceError as error: + raise InferenceError( + str(error), target=self, attribute=name, context=context + ) from error + + def is_method(self): + """Check if this function node represents a method. + + :returns: True if this is a method, False otherwise. + :rtype: bool + """ + # check we are defined in a ClassDef, because this is usually expected + # (e.g. pylint...) when is_method() return True + return self.type != "function" and isinstance(self.parent.frame(), ClassDef) + + @decorators_mod.cached + def decoratornames(self, context=None): + """Get the qualified names of each of the decorators on this function. + + :param context: + An inference context that can be passed to inference functions + :returns: The names of the decorators. + :rtype: set(str) + """ + result = set() + decoratornodes = [] + if self.decorators is not None: + decoratornodes += self.decorators.nodes + decoratornodes += self.extra_decorators + for decnode in decoratornodes: + try: + for infnode in decnode.infer(context=context): + result.add(infnode.qname()) + except InferenceError: + continue + return result + + def is_bound(self): + """Check if the function is bound to an instance or class. + + :returns: True if the function is bound to an instance or class, + False otherwise. + :rtype: bool + """ + return self.type == "classmethod" + + def is_abstract(self, pass_is_abstract=True, any_raise_is_abstract=False): + """Check if the method is abstract. + + A method is considered abstract if any of the following is true: + * The only statement is 'raise NotImplementedError' + * The only statement is 'raise <SomeException>' and any_raise_is_abstract is True + * The only statement is 'pass' and pass_is_abstract is True + * The method is annotated with abc.astractproperty/abc.abstractmethod + + :returns: True if the method is abstract, False otherwise. + :rtype: bool + """ + if self.decorators: + for node in self.decorators.nodes: + try: + inferred = next(node.infer()) + except (InferenceError, StopIteration): + continue + if inferred and inferred.qname() in ( + "abc.abstractproperty", + "abc.abstractmethod", + ): + return True + + for child_node in self.body: + if isinstance(child_node, node_classes.Raise): + if any_raise_is_abstract: + return True + if child_node.raises_not_implemented(): + return True + return pass_is_abstract and isinstance(child_node, node_classes.Pass) + # empty function is the same as function with a single "pass" statement + if pass_is_abstract: + return True + + def is_generator(self): + """Check if this is a generator function. + + :returns: True is this is a generator function, False otherwise. + :rtype: bool + """ + return bool(next(self._get_yield_nodes_skip_lambdas(), False)) + + def infer_yield_result(self, context=None): + """Infer what the function yields when called + + :returns: What the function yields + :rtype: iterable(NodeNG or Uninferable) or None + """ + for yield_ in self.nodes_of_class(node_classes.Yield): + if yield_.value is None: + const = node_classes.Const(None) + const.parent = yield_ + const.lineno = yield_.lineno + yield const + elif yield_.scope() == self: + yield from yield_.value.infer(context=context) + + def infer_call_result(self, caller=None, context=None): + """Infer what the function returns when called. + + :returns: What the function returns. + :rtype: iterable(NodeNG or Uninferable) or None + """ + if self.is_generator(): + if isinstance(self, AsyncFunctionDef): + generator_cls = bases.AsyncGenerator + else: + generator_cls = bases.Generator + result = generator_cls(self, generator_initial_context=context) + yield result + return + # This is really a gigantic hack to work around metaclass generators + # that return transient class-generating functions. Pylint's AST structure + # cannot handle a base class object that is only used for calling __new__, + # but does not contribute to the inheritance structure itself. We inject + # a fake class into the hierarchy here for several well-known metaclass + # generators, and filter it out later. + if ( + self.name == "with_metaclass" + and len(self.args.args) == 1 + and self.args.vararg is not None + ): + metaclass = next(caller.args[0].infer(context), None) + if isinstance(metaclass, ClassDef): + try: + class_bases = [next(arg.infer(context)) for arg in caller.args[1:]] + except StopIteration as e: + raise InferenceError(node=caller.args[1:], context=context) from e + new_class = ClassDef(name="temporary_class") + new_class.hide = True + new_class.parent = self + new_class.postinit( + bases=[base for base in class_bases if base != util.Uninferable], + body=[], + decorators=[], + metaclass=metaclass, + ) + yield new_class + return + returns = self._get_return_nodes_skip_functions() + + first_return = next(returns, None) + if not first_return: + if self.body: + if self.is_abstract(pass_is_abstract=True, any_raise_is_abstract=True): + yield util.Uninferable + else: + yield node_classes.Const(None) + return + + raise InferenceError("The function does not have any return statements") + + for returnnode in itertools.chain((first_return,), returns): + if returnnode.value is None: + yield node_classes.Const(None) + else: + try: + yield from returnnode.value.infer(context) + except InferenceError: + yield util.Uninferable + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + For a :class:`FunctionDef` this is always ``True``. + :rtype: bool + """ + return True + + def get_children(self): + if self.decorators is not None: + yield self.decorators + + yield self.args + + if self.returns is not None: + yield self.returns + + yield from self.body + + def scope_lookup(self, node, name, offset=0): + """Lookup where the given name is assigned.""" + if name == "__class__": + # __class__ is an implicit closure reference created by the compiler + # if any methods in a class body refer to either __class__ or super. + # In our case, we want to be able to look it up in the current scope + # when `__class__` is being used. + frame = self.parent.frame() + if isinstance(frame, ClassDef): + return self, [frame] + return super().scope_lookup(node, name, offset) + + +class AsyncFunctionDef(FunctionDef): + """Class representing an :class:`ast.FunctionDef` node. + + A :class:`AsyncFunctionDef` is an asynchronous function + created with the `async` keyword. + + >>> node = astroid.extract_node(''' + async def func(things): + async for thing in things: + print(thing) + ''') + >>> node + <AsyncFunctionDef.func l.2 at 0x7f23b2e416d8> + >>> node.body[0] + <AsyncFor l.3 at 0x7f23b2e417b8> + """ + + +def _rec_get_names(args, names=None): + """return a list of all argument names""" + if names is None: + names = [] + for arg in args: + if isinstance(arg, node_classes.Tuple): + _rec_get_names(arg.elts, names) + else: + names.append(arg.name) + return names + + +def _is_metaclass(klass, seen=None): + """Return if the given class can be + used as a metaclass. + """ + if klass.name == "type": + return True + if seen is None: + seen = set() + for base in klass.bases: + try: + for baseobj in base.infer(): + baseobj_name = baseobj.qname() + if baseobj_name in seen: + continue + + seen.add(baseobj_name) + if isinstance(baseobj, bases.Instance): + # not abstract + return False + if baseobj is util.Uninferable: + continue + if baseobj is klass: + continue + if not isinstance(baseobj, ClassDef): + continue + if baseobj._type == "metaclass": + return True + if _is_metaclass(baseobj, seen): + return True + except InferenceError: + continue + return False + + +def _class_type(klass, ancestors=None): + """return a ClassDef node type to differ metaclass and exception + from 'regular' classes + """ + # XXX we have to store ancestors in case we have an ancestor loop + if klass._type is not None: + return klass._type + if _is_metaclass(klass): + klass._type = "metaclass" + elif klass.name.endswith("Exception"): + klass._type = "exception" + else: + if ancestors is None: + ancestors = set() + klass_name = klass.qname() + if klass_name in ancestors: + # XXX we are in loop ancestors, and have found no type + klass._type = "class" + return "class" + ancestors.add(klass_name) + for base in klass.ancestors(recurs=False): + name = _class_type(base, ancestors) + if name != "class": + if name == "metaclass" and not _is_metaclass(klass): + # don't propagate it if the current class + # can't be a metaclass + continue + klass._type = base.type + break + if klass._type is None: + klass._type = "class" + return klass._type + + +def get_wrapping_class(node): + """Get the class that wraps the given node. + + We consider that a class wraps a node if the class + is a parent for the said node. + + :returns: The class that wraps the given node + :rtype: ClassDef or None + """ + + klass = node.frame() + while klass is not None and not isinstance(klass, ClassDef): + if klass.parent is None: + klass = None + else: + klass = klass.parent.frame() + return klass + + +class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement): + """Class representing an :class:`ast.ClassDef` node. + + >>> node = astroid.extract_node(''' + class Thing: + def my_meth(self, arg): + return arg + self.offset + ''') + >>> node + <ClassDef.Thing l.2 at 0x7f23b2e9e748> + """ + + # some of the attributes below are set by the builder module or + # by a raw factories + + # a dictionary of class instances attributes + _astroid_fields = ("decorators", "bases", "keywords", "body") # name + + decorators = None + """The decorators that are applied to this class. + + :type: Decorators or None + """ + special_attributes = ClassModel() + """The names of special attributes that this class has. + + :type: objectmodel.ClassModel + """ + + _type = None + _metaclass_hack = False + hide = False + type = property( + _class_type, + doc=( + "The class type for this node.\n\n" + "Possible values are: class, metaclass, exception.\n\n" + ":type: str" + ), + ) + _other_fields = ("name", "doc") + _other_other_fields = ("locals", "_newstyle") + _newstyle = None + + def __init__(self, name=None, doc=None, lineno=None, col_offset=None, parent=None): + """ + :param name: The name of the class. + :type name: str or None + + :param doc: The function's docstring. + :type doc: str or None + + :param lineno: The line that this node appears on in the source code. + :type lineno: int or None + + :param col_offset: The column that this node appears on in the + source code. + :type col_offset: int or None + + :param parent: The parent node in the syntax tree. + :type parent: NodeNG or None + """ + self.instance_attrs = {} + self.locals = {} + """A map of the name of a local variable to the node defining it. + + :type: dict(str, NodeNG) + """ + + self.keywords = [] + """The keywords given to the class definition. + + This is usually for :pep:`3115` style metaclass declaration. + + :type: list(Keyword) or None + """ + + self.bases = [] + """What the class inherits from. + + :type: list(NodeNG) + """ + + self.body = [] + """The contents of the class body. + + :type: list(NodeNG) + """ + + self.name = name + """The name of the class. + + :type name: str or None + """ + + self.doc = doc + """The class' docstring. + + :type doc: str or None + """ + + super().__init__(lineno, col_offset, parent) + if parent is not None: + parent.frame().set_local(name, self) + + for local_name, node in self.implicit_locals(): + self.add_local_node(node, local_name) + + def implicit_parameters(self): + return 1 + + def implicit_locals(self): + """Get implicitly defined class definition locals. + + :returns: the the name and Const pair for each local + :rtype: tuple(tuple(str, node_classes.Const), ...) + """ + locals_ = (("__module__", self.special_attributes.attr___module__),) + # __qualname__ is defined in PEP3155 + locals_ += (("__qualname__", self.special_attributes.attr___qualname__),) + return locals_ + + # pylint: disable=redefined-outer-name + def postinit( + self, bases, body, decorators, newstyle=None, metaclass=None, keywords=None + ): + """Do some setup after initialisation. + + :param bases: What the class inherits from. + :type bases: list(NodeNG) + + :param body: The contents of the class body. + :type body: list(NodeNG) + + :param decorators: The decorators that are applied to this class. + :type decorators: Decorators or None + + :param newstyle: Whether this is a new style class or not. + :type newstyle: bool or None + + :param metaclass: The metaclass of this class. + :type metaclass: NodeNG or None + + :param keywords: The keywords given to the class definition. + :type keywords: list(Keyword) or None + """ + self.keywords = keywords + self.bases = bases + self.body = body + self.decorators = decorators + if newstyle is not None: + self._newstyle = newstyle + if metaclass is not None: + self._metaclass = metaclass + + def _newstyle_impl(self, context=None): + if context is None: + context = contextmod.InferenceContext() + if self._newstyle is not None: + return self._newstyle + for base in self.ancestors(recurs=False, context=context): + if base._newstyle_impl(context): + self._newstyle = True + break + klass = self.declared_metaclass() + # could be any callable, we'd need to infer the result of klass(name, + # bases, dict). punt if it's not a class node. + if klass is not None and isinstance(klass, ClassDef): + self._newstyle = klass._newstyle_impl(context) + if self._newstyle is None: + self._newstyle = False + return self._newstyle + + _newstyle = None + newstyle = property( + _newstyle_impl, + doc=("Whether this is a new style class or not\n\n" ":type: bool or None"), + ) + + @decorators_mod.cachedproperty + def blockstart_tolineno(self): + """The line on which the beginning of this block ends. + + :type: int + """ + if self.bases: + return self.bases[-1].tolineno + + return self.fromlineno + + def block_range(self, lineno): + """Get a range from the given line number to where this node ends. + + :param lineno: Unused. + :type lineno: int + + :returns: The range of line numbers that this node belongs to, + :rtype: tuple(int, int) + """ + return self.fromlineno, self.tolineno + + def pytype(self): + """Get the name of the type that this node represents. + + :returns: The name of the type. + :rtype: str + """ + if self.newstyle: + return "%s.type" % BUILTINS + return "%s.classobj" % BUILTINS + + def display_type(self): + """A human readable type of this node. + + :returns: The type of this node. + :rtype: str + """ + return "Class" + + def callable(self): + """Whether this node defines something that is callable. + + :returns: True if this defines something that is callable, + False otherwise. + For a :class:`ClassDef` this is always ``True``. + :rtype: bool + """ + return True + + def is_subtype_of(self, type_name, context=None): + """Whether this class is a subtype of the given type. + + :param type_name: The name of the type of check against. + :type type_name: str + + :returns: True if this class is a subtype of the given type, + False otherwise. + :rtype: bool + """ + if self.qname() == type_name: + return True + for anc in self.ancestors(context=context): + if anc.qname() == type_name: + return True + return False + + def _infer_type_call(self, caller, context): + try: + name_node = next(caller.args[0].infer(context)) + except StopIteration as e: + raise InferenceError(node=caller.args[0], context=context) from e + if isinstance(name_node, node_classes.Const) and isinstance( + name_node.value, str + ): + name = name_node.value + else: + return util.Uninferable + + result = ClassDef(name, None) + + # Get the bases of the class. + try: + class_bases = next(caller.args[1].infer(context)) + except StopIteration as e: + raise InferenceError(node=caller.args[1], context=context) from e + if isinstance(class_bases, (node_classes.Tuple, node_classes.List)): + bases = [] + for base in class_bases.itered(): + inferred = next(base.infer(context=context), None) + if inferred: + bases.append( + node_classes.EvaluatedObject(original=base, value=inferred) + ) + result.bases = bases + else: + # There is currently no AST node that can represent an 'unknown' + # node (Uninferable is not an AST node), therefore we simply return Uninferable here + # although we know at least the name of the class. + return util.Uninferable + + # Get the members of the class + try: + members = next(caller.args[2].infer(context)) + except (InferenceError, StopIteration): + members = None + + if members and isinstance(members, node_classes.Dict): + for attr, value in members.items: + if isinstance(attr, node_classes.Const) and isinstance(attr.value, str): + result.locals[attr.value] = [value] + + result.parent = caller.parent + return result + + def infer_call_result(self, caller, context=None): + """infer what a class is returning when called""" + if self.is_subtype_of(f"{BUILTINS}.type", context) and len(caller.args) == 3: + result = self._infer_type_call(caller, context) + yield result + return + + dunder_call = None + try: + metaclass = self.metaclass(context=context) + if metaclass is not None: + dunder_call = next(metaclass.igetattr("__call__", context)) + except (AttributeInferenceError, StopIteration): + pass + + if dunder_call and dunder_call.qname() != "builtins.type.__call__": + # Call type.__call__ if not set metaclass + # (since type is the default metaclass) + context = contextmod.bind_context_to_node(context, self) + yield from dunder_call.infer_call_result(caller, context) + else: + yield self.instantiate_class() + + def scope_lookup(self, node, name, offset=0): + """Lookup where the given name is assigned. + + :param node: The node to look for assignments up to. + Any assignments after the given node are ignored. + :type node: NodeNG + + :param name: The name to find assignments for. + :type name: str + + :param offset: The line offset to filter statements up to. + :type offset: int + + :returns: This scope node and the list of assignments associated to the + given name according to the scope where it has been found (locals, + globals or builtin). + :rtype: tuple(str, list(NodeNG)) + """ + # If the name looks like a builtin name, just try to look + # into the upper scope of this class. We might have a + # decorator that it's poorly named after a builtin object + # inside this class. + lookup_upper_frame = ( + isinstance(node.parent, node_classes.Decorators) + and name in AstroidManager().builtins_module + ) + if ( + any(node == base or base.parent_of(node) for base in self.bases) + or lookup_upper_frame + ): + # Handle the case where we have either a name + # in the bases of a class, which exists before + # the actual definition or the case where we have + # a Getattr node, with that name. + # + # name = ... + # class A(name): + # def name(self): ... + # + # import name + # class A(name.Name): + # def name(self): ... + + frame = self.parent.frame() + # line offset to avoid that class A(A) resolve the ancestor to + # the defined class + offset = -1 + else: + frame = self + return frame._scope_lookup(node, name, offset) + + @property + def basenames(self): + """The names of the parent classes + + Names are given in the order they appear in the class definition. + + :type: list(str) + """ + return [bnode.as_string() for bnode in self.bases] + + def ancestors(self, recurs=True, context=None): + """Iterate over the base classes in prefixed depth first order. + + :param recurs: Whether to recurse or return direct ancestors only. + :type recurs: bool + + :returns: The base classes + :rtype: iterable(NodeNG) + """ + # FIXME: should be possible to choose the resolution order + # FIXME: inference make infinite loops possible here + yielded = {self} + if context is None: + context = contextmod.InferenceContext() + if not self.bases and self.qname() != "builtins.object": + yield builtin_lookup("object")[1][0] + return + + for stmt in self.bases: + with context.restore_path(): + try: + for baseobj in stmt.infer(context): + if not isinstance(baseobj, ClassDef): + if isinstance(baseobj, bases.Instance): + baseobj = baseobj._proxied + else: + continue + if not baseobj.hide: + if baseobj in yielded: + continue + yielded.add(baseobj) + yield baseobj + if not recurs: + continue + for grandpa in baseobj.ancestors(recurs=True, context=context): + if grandpa is self: + # This class is the ancestor of itself. + break + if grandpa in yielded: + continue + yielded.add(grandpa) + yield grandpa + except InferenceError: + continue + + def local_attr_ancestors(self, name, context=None): + """Iterate over the parents that define the given name. + + :param name: The name to find definitions for. + :type name: str + + :returns: The parents that define the given name. + :rtype: iterable(NodeNG) + """ + # Look up in the mro if we can. This will result in the + # attribute being looked up just as Python does it. + try: + ancestors = self.mro(context)[1:] + except MroError: + # Fallback to use ancestors, we can't determine + # a sane MRO. + ancestors = self.ancestors(context=context) + for astroid in ancestors: + if name in astroid: + yield astroid + + def instance_attr_ancestors(self, name, context=None): + """Iterate over the parents that define the given name as an attribute. + + :param name: The name to find definitions for. + :type name: str + + :returns: The parents that define the given name as + an instance attribute. + :rtype: iterable(NodeNG) + """ + for astroid in self.ancestors(context=context): + if name in astroid.instance_attrs: + yield astroid + + def has_base(self, node): + """Whether this class directly inherits from the given node. + + :param node: The node to check for. + :type node: NodeNG + + :returns: True if this class directly inherits from the given node. + :rtype: bool + """ + return node in self.bases + + def local_attr(self, name, context=None): + """Get the list of assign nodes associated to the given name. + + Assignments are looked for in both this class and in parents. + + :returns: The list of assignments to the given name. + :rtype: list(NodeNG) + + :raises AttributeInferenceError: If no attribute with this name + can be found in this class or parent classes. + """ + result = [] + if name in self.locals: + result = self.locals[name] + else: + class_node = next(self.local_attr_ancestors(name, context), None) + if class_node: + result = class_node.locals[name] + result = [n for n in result if not isinstance(n, node_classes.DelAttr)] + if result: + return result + raise AttributeInferenceError(target=self, attribute=name, context=context) + + def instance_attr(self, name, context=None): + """Get the list of nodes associated to the given attribute name. + + Assignments are looked for in both this class and in parents. + + :returns: The list of assignments to the given name. + :rtype: list(NodeNG) + + :raises AttributeInferenceError: If no attribute with this name + can be found in this class or parent classes. + """ + # Return a copy, so we don't modify self.instance_attrs, + # which could lead to infinite loop. + values = list(self.instance_attrs.get(name, [])) + # get all values from parents + for class_node in self.instance_attr_ancestors(name, context): + values += class_node.instance_attrs[name] + values = [n for n in values if not isinstance(n, node_classes.DelAttr)] + if values: + return values + raise AttributeInferenceError(target=self, attribute=name, context=context) + + def instantiate_class(self): + """Get an :class:`Instance` of the :class:`ClassDef` node. + + :returns: An :class:`Instance` of the :class:`ClassDef` node, + or self if this is not possible. + :rtype: Instance or ClassDef + """ + try: + if any(cls.name in EXCEPTION_BASE_CLASSES for cls in self.mro()): + # Subclasses of exceptions can be exception instances + return objects.ExceptionInstance(self) + except MroError: + pass + return bases.Instance(self) + + def getattr(self, name, context=None, class_context=True): + """Get an attribute from this class, using Python's attribute semantic. + + This method doesn't look in the :attr:`instance_attrs` dictionary + since it is done by an :class:`Instance` proxy at inference time. + It may return an :class:`Uninferable` object if + the attribute has not been + found, but a ``__getattr__`` or ``__getattribute__`` method is defined. + If ``class_context`` is given, then it is considered that the + attribute is accessed from a class context, + e.g. ClassDef.attribute, otherwise it might have been accessed + from an instance as well. If ``class_context`` is used in that + case, then a lookup in the implicit metaclass and the explicit + metaclass will be done. + + :param name: The attribute to look for. + :type name: str + + :param class_context: Whether the attribute can be accessed statically. + :type class_context: bool + + :returns: The attribute. + :rtype: list(NodeNG) + + :raises AttributeInferenceError: If the attribute cannot be inferred. + """ + if not name: + raise AttributeInferenceError(target=self, attribute=name, context=context) + + values = self.locals.get(name, []) + if name in self.special_attributes and class_context and not values: + result = [self.special_attributes.lookup(name)] + if name == "__bases__": + # Need special treatment, since they are mutable + # and we need to return all the values. + result += values + return result + + # don't modify the list in self.locals! + values = list(values) + for classnode in self.ancestors(recurs=True, context=context): + values += classnode.locals.get(name, []) + + if class_context: + values += self._metaclass_lookup_attribute(name, context) + + if not values: + raise AttributeInferenceError(target=self, attribute=name, context=context) + + # Look for AnnAssigns, which are not attributes in the purest sense. + for value in values: + if isinstance(value, node_classes.AssignName): + stmt = value.statement() + if isinstance(stmt, node_classes.AnnAssign) and stmt.value is None: + raise AttributeInferenceError( + target=self, attribute=name, context=context + ) + return values + + def _metaclass_lookup_attribute(self, name, context): + """Search the given name in the implicit and the explicit metaclass.""" + attrs = set() + implicit_meta = self.implicit_metaclass() + context = contextmod.copy_context(context) + metaclass = self.metaclass(context=context) + for cls in (implicit_meta, metaclass): + if cls and cls != self and isinstance(cls, ClassDef): + cls_attributes = self._get_attribute_from_metaclass(cls, name, context) + attrs.update(set(cls_attributes)) + return attrs + + def _get_attribute_from_metaclass(self, cls, name, context): + try: + attrs = cls.getattr(name, context=context, class_context=True) + except AttributeInferenceError: + return + + for attr in bases._infer_stmts(attrs, context, frame=cls): + if not isinstance(attr, FunctionDef): + yield attr + continue + + if isinstance(attr, objects.Property): + yield attr + continue + if attr.type == "classmethod": + # If the method is a classmethod, then it will + # be bound to the metaclass, not to the class + # from where the attribute is retrieved. + # get_wrapping_class could return None, so just + # default to the current class. + frame = get_wrapping_class(attr) or self + yield bases.BoundMethod(attr, frame) + elif attr.type == "staticmethod": + yield attr + else: + yield bases.BoundMethod(attr, self) + + def igetattr(self, name, context=None, class_context=True): + """Infer the possible values of the given variable. + + :param name: The name of the variable to infer. + :type name: str + + :returns: The inferred possible values. + :rtype: iterable(NodeNG or Uninferable) + """ + # set lookup name since this is necessary to infer on import nodes for + # instance + context = contextmod.copy_context(context) + context.lookupname = name + + metaclass = self.metaclass(context=context) + try: + attributes = self.getattr(name, context, class_context=class_context) + # If we have more than one attribute, make sure that those starting from + # the second one are from the same scope. This is to account for modifications + # to the attribute happening *after* the attribute's definition (e.g. AugAssigns on lists) + if len(attributes) > 1: + first_attr, attributes = attributes[0], attributes[1:] + first_scope = first_attr.scope() + attributes = [first_attr] + [ + attr + for attr in attributes + if attr.parent and attr.parent.scope() == first_scope + ] + + for inferred in bases._infer_stmts(attributes, context, frame=self): + # yield Uninferable object instead of descriptors when necessary + if not isinstance(inferred, node_classes.Const) and isinstance( + inferred, bases.Instance + ): + try: + inferred._proxied.getattr("__get__", context) + except AttributeInferenceError: + yield inferred + else: + yield util.Uninferable + elif isinstance(inferred, objects.Property): + function = inferred.function + if not class_context: + # Through an instance so we can solve the property + yield from function.infer_call_result( + caller=self, context=context + ) + # If we're in a class context, we need to determine if the property + # was defined in the metaclass (a derived class must be a subclass of + # the metaclass of all its bases), in which case we can resolve the + # property. If not, i.e. the property is defined in some base class + # instead, then we return the property object + elif metaclass and function.parent.scope() is metaclass: + # Resolve a property as long as it is not accessed through + # the class itself. + yield from function.infer_call_result( + caller=self, context=context + ) + else: + yield inferred + else: + yield function_to_method(inferred, self) + except AttributeInferenceError as error: + if not name.startswith("__") and self.has_dynamic_getattr(context): + # class handle some dynamic attributes, return a Uninferable object + yield util.Uninferable + else: + raise InferenceError( + str(error), target=self, attribute=name, context=context + ) from error + + def has_dynamic_getattr(self, context=None): + """Check if the class has a custom __getattr__ or __getattribute__. + + If any such method is found and it is not from + builtins, nor from an extension module, then the function + will return True. + + :returns: True if the class has a custom + __getattr__ or __getattribute__, False otherwise. + :rtype: bool + """ + + def _valid_getattr(node): + root = node.root() + return root.name != BUILTINS and getattr(root, "pure_python", None) + + try: + return _valid_getattr(self.getattr("__getattr__", context)[0]) + except AttributeInferenceError: + # if self.newstyle: XXX cause an infinite recursion error + try: + getattribute = self.getattr("__getattribute__", context)[0] + return _valid_getattr(getattribute) + except AttributeInferenceError: + pass + return False + + def getitem(self, index, context=None): + """Return the inference of a subscript. + + This is basically looking up the method in the metaclass and calling it. + + :returns: The inferred value of a subscript to this class. + :rtype: NodeNG + + :raises AstroidTypeError: If this class does not define a + ``__getitem__`` method. + """ + try: + methods = lookup(self, "__getitem__") + except AttributeInferenceError as exc: + if isinstance(self, ClassDef): + # subscripting a class definition may be + # achieved thanks to __class_getitem__ method + # which is a classmethod defined in the class + # that supports subscript and not in the metaclass + try: + methods = self.getattr("__class_getitem__") + # Here it is assumed that the __class_getitem__ node is + # a FunctionDef. One possible improvement would be to deal + # with more generic inference. + except AttributeInferenceError: + raise AstroidTypeError(node=self, context=context) from exc + else: + raise AstroidTypeError(node=self, context=context) from exc + + method = methods[0] + + # Create a new callcontext for providing index as an argument. + new_context = contextmod.bind_context_to_node(context, self) + new_context.callcontext = contextmod.CallContext(args=[index]) + + try: + return next(method.infer_call_result(self, new_context), util.Uninferable) + except AttributeError: + # Starting with python3.9, builtin types list, dict etc... + # are subscriptable thanks to __class_getitem___ classmethod. + # However in such case the method is bound to an EmptyNode and + # EmptyNode doesn't have infer_call_result method yielding to + # AttributeError + if ( + isinstance(method, node_classes.EmptyNode) + and self.name in ("list", "dict", "set", "tuple", "frozenset") + and PY39_PLUS + ): + return self + raise + except InferenceError: + return util.Uninferable + + def methods(self): + """Iterate over all of the method defined in this class and its parents. + + :returns: The methods defined on the class. + :rtype: iterable(FunctionDef) + """ + done = {} + for astroid in itertools.chain(iter((self,)), self.ancestors()): + for meth in astroid.mymethods(): + if meth.name in done: + continue + done[meth.name] = None + yield meth + + def mymethods(self): + """Iterate over all of the method defined in this class only. + + :returns: The methods defined on the class. + :rtype: iterable(FunctionDef) + """ + for member in self.values(): + if isinstance(member, FunctionDef): + yield member + + def implicit_metaclass(self): + """Get the implicit metaclass of the current class. + + For newstyle classes, this will return an instance of builtins.type. + For oldstyle classes, it will simply return None, since there's + no implicit metaclass there. + + :returns: The metaclass. + :rtype: builtins.type or None + """ + if self.newstyle: + return builtin_lookup("type")[1][0] + return None + + _metaclass = None + + def declared_metaclass(self, context=None): + """Return the explicit declared metaclass for the current class. + + An explicit declared metaclass is defined + either by passing the ``metaclass`` keyword argument + in the class definition line (Python 3) or (Python 2) by + having a ``__metaclass__`` class attribute, or if there are + no explicit bases but there is a global ``__metaclass__`` variable. + + :returns: The metaclass of this class, + or None if one could not be found. + :rtype: NodeNG or None + """ + for base in self.bases: + try: + for baseobj in base.infer(context=context): + if isinstance(baseobj, ClassDef) and baseobj.hide: + self._metaclass = baseobj._metaclass + self._metaclass_hack = True + break + except InferenceError: + pass + + if self._metaclass: + # Expects this from Py3k TreeRebuilder + try: + return next( + node + for node in self._metaclass.infer(context=context) + if node is not util.Uninferable + ) + except (InferenceError, StopIteration): + return None + + return None + + def _find_metaclass(self, seen=None, context=None): + if seen is None: + seen = set() + seen.add(self) + + klass = self.declared_metaclass(context=context) + if klass is None: + for parent in self.ancestors(context=context): + if parent not in seen: + klass = parent._find_metaclass(seen) + if klass is not None: + break + return klass + + def metaclass(self, context=None): + """Get the metaclass of this class. + + If this class does not define explicitly a metaclass, + then the first defined metaclass in ancestors will be used + instead. + + :returns: The metaclass of this class. + :rtype: NodeNG or None + """ + return self._find_metaclass(context=context) + + def has_metaclass_hack(self): + return self._metaclass_hack + + def _islots(self): + """Return an iterator with the inferred slots.""" + if "__slots__" not in self.locals: + return None + for slots in self.igetattr("__slots__"): + # check if __slots__ is a valid type + for meth in ITER_METHODS: + try: + slots.getattr(meth) + break + except AttributeInferenceError: + continue + else: + continue + + if isinstance(slots, node_classes.Const): + # a string. Ignore the following checks, + # but yield the node, only if it has a value + if slots.value: + yield slots + continue + if not hasattr(slots, "itered"): + # we can't obtain the values, maybe a .deque? + continue + + if isinstance(slots, node_classes.Dict): + values = [item[0] for item in slots.items] + else: + values = slots.itered() + if values is util.Uninferable: + continue + if not values: + # Stop the iteration, because the class + # has an empty list of slots. + return values + + for elt in values: + try: + for inferred in elt.infer(): + if inferred is util.Uninferable: + continue + if not isinstance( + inferred, node_classes.Const + ) or not isinstance(inferred.value, str): + continue + if not inferred.value: + continue + yield inferred + except InferenceError: + continue + + return None + + def _slots(self): + if not self.newstyle: + raise NotImplementedError( + "The concept of slots is undefined for old-style classes." + ) + + slots = self._islots() + try: + first = next(slots) + except StopIteration as exc: + # The class doesn't have a __slots__ definition or empty slots. + if exc.args and exc.args[0] not in ("", None): + return exc.args[0] + return None + return [first] + list(slots) + + # Cached, because inferring them all the time is expensive + @decorators_mod.cached + def slots(self): + """Get all the slots for this node. + + :returns: The names of slots for this class. + If the class doesn't define any slot, through the ``__slots__`` + variable, then this function will return a None. + Also, it will return None in the case the slots were not inferred. + :rtype: list(str) or None + """ + + def grouped_slots( + mro: List["ClassDef"], + ) -> typing.Iterator[Optional[node_classes.NodeNG]]: + # Not interested in object, since it can't have slots. + for cls in mro[:-1]: + try: + cls_slots = cls._slots() + except NotImplementedError: + continue + if cls_slots is not None: + yield from cls_slots + else: + yield None + + if not self.newstyle: + raise NotImplementedError( + "The concept of slots is undefined for old-style classes." + ) + + try: + mro = self.mro() + except MroError as e: + raise NotImplementedError( + "Cannot get slots while parsing mro fails." + ) from e + + slots = list(grouped_slots(mro)) + if not all(slot is not None for slot in slots): + return None + + return sorted(set(slots), key=lambda item: item.value) + + def _inferred_bases(self, context=None): + # Similar with .ancestors, but the difference is when one base is inferred, + # only the first object is wanted. That's because + # we aren't interested in superclasses, as in the following + # example: + # + # class SomeSuperClass(object): pass + # class SomeClass(SomeSuperClass): pass + # class Test(SomeClass): pass + # + # Inferring SomeClass from the Test's bases will give + # us both SomeClass and SomeSuperClass, but we are interested + # only in SomeClass. + + if context is None: + context = contextmod.InferenceContext() + if not self.bases and self.qname() != "builtins.object": + yield builtin_lookup("object")[1][0] + return + + for stmt in self.bases: + try: + baseobj = next(stmt.infer(context=context.clone())) + except (InferenceError, StopIteration): + continue + if isinstance(baseobj, bases.Instance): + baseobj = baseobj._proxied + if not isinstance(baseobj, ClassDef): + continue + if not baseobj.hide: + yield baseobj + else: + yield from baseobj.bases + + def _compute_mro(self, context=None): + inferred_bases = list(self._inferred_bases(context=context)) + bases_mro = [] + for base in inferred_bases: + if base is self: + continue + + try: + mro = base._compute_mro(context=context) + bases_mro.append(mro) + except NotImplementedError: + # Some classes have in their ancestors both newstyle and + # old style classes. For these we can't retrieve the .mro, + # although in Python it's possible, since the class we are + # currently working is in fact new style. + # So, we fallback to ancestors here. + ancestors = list(base.ancestors(context=context)) + bases_mro.append(ancestors) + + unmerged_mro = [[self]] + bases_mro + [inferred_bases] + unmerged_mro = list(clean_duplicates_mro(unmerged_mro, self, context)) + clean_typing_generic_mro(unmerged_mro) + return _c3_merge(unmerged_mro, self, context) + + def mro(self, context=None) -> List["ClassDef"]: + """Get the method resolution order, using C3 linearization. + + :returns: The list of ancestors, sorted by the mro. + :rtype: list(NodeNG) + :raises DuplicateBasesError: Duplicate bases in the same class base + :raises InconsistentMroError: A class' MRO is inconsistent + """ + return self._compute_mro(context=context) + + def bool_value(self, context=None): + """Determine the boolean value of this node. + + :returns: The boolean value of this node. + For a :class:`ClassDef` this is always ``True``. + :rtype: bool + """ + return True + + def get_children(self): + if self.decorators is not None: + yield self.decorators + + yield from self.bases + if self.keywords is not None: + yield from self.keywords + yield from self.body + + @decorators_mod.cached + def _get_assign_nodes(self): + children_assign_nodes = ( + child_node._get_assign_nodes() for child_node in self.body + ) + return list(itertools.chain.from_iterable(children_assign_nodes)) diff --git a/astroid/rebuilder.py b/astroid/rebuilder.py index 1911f504..aaceeac4 100644 --- a/astroid/rebuilder.py +++ b/astroid/rebuilder.py @@ -49,7 +49,7 @@ from astroid import node_classes, nodes from astroid._ast import ParserModule, get_parser_module, parse_function_type_comment from astroid.const import PY37_PLUS, PY38_PLUS, PY39_PLUS, Context from astroid.manager import AstroidManager -from astroid.node_classes import NodeNG +from astroid.nodes import NodeNG if sys.version_info >= (3, 8): from typing import Final diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py index 5c57920f..8d335902 100644 --- a/astroid/scoped_nodes.py +++ b/astroid/scoped_nodes.py @@ -1,3033 +1,29 @@ -# Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> -# Copyright (c) 2010 Daniel Harding <dharding@gmail.com> -# Copyright (c) 2011, 2013-2015 Google, Inc. -# Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com> -# Copyright (c) 2013 Phil Schaf <flying-sheep@web.de> -# Copyright (c) 2014 Eevee (Alex Munroe) <amunroe@yelp.com> -# Copyright (c) 2015-2016 Florian Bruhin <me@the-compiler.org> -# Copyright (c) 2015-2016 Ceridwen <ceridwenv@gmail.com> -# Copyright (c) 2015 Rene Zhang <rz99@cornell.edu> -# Copyright (c) 2015 Philip Lorenz <philip@bithub.de> -# Copyright (c) 2016-2017 Derek Gustafson <degustaf@gmail.com> -# Copyright (c) 2017-2018 Bryce Guinta <bryce.paul.guinta@gmail.com> -# Copyright (c) 2017-2018 Ashley Whetter <ashley@awhetter.co.uk> -# Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com> -# Copyright (c) 2017 David Euresti <david@dropbox.com> -# Copyright (c) 2018-2019 Nick Drozd <nicholasdrozd@gmail.com> -# Copyright (c) 2018 Ville Skyttä <ville.skytta@iki.fi> -# Copyright (c) 2018 Anthony Sottile <asottile@umich.edu> -# Copyright (c) 2018 HoverHell <hoverhell@gmail.com> -# Copyright (c) 2019 Hugo van Kemenade <hugovk@users.noreply.github.com> -# Copyright (c) 2019 Peter de Blanc <peter@standard.ai> -# Copyright (c) 2020-2021 hippo91 <guillaume.peillex@gmail.com> -# Copyright (c) 2020 Peter Kolbus <peter.kolbus@gmail.com> -# Copyright (c) 2020 Tim Martin <tim@asymptotic.co.uk> -# Copyright (c) 2020 Ram Rachum <ram@rachum.com> -# Copyright (c) 2021 doranid <ddandd@gmail.com> -# Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com> -# Copyright (c) 2021 David Liu <david@cs.toronto.edu> -# Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com> -# Copyright (c) 2021 Andrew Haigh <hello@nelf.in> -# Copyright (c) 2021 pre-commit-ci[bot] <bot@noreply.github.com> - -# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html -# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE - - -""" -This module contains the classes for "scoped" node, i.e. which are opening a -new local scope in the language definition : Module, ClassDef, FunctionDef (and -Lambda, GeneratorExp, DictComp and SetComp to some extent). -""" -import builtins -import io -import itertools -import typing -from typing import List, Optional - -from astroid import bases -from astroid import context as contextmod -from astroid import decorators as decorators_mod -from astroid import mixins, node_classes, util -from astroid.const import BUILTINS, PY39_PLUS -from astroid.exceptions import ( - AstroidBuildingError, - AstroidTypeError, - AttributeInferenceError, - DuplicateBasesError, - InconsistentMroError, - InferenceError, - MroError, - TooManyLevelsError, +# pylint: disable=unused-import + +import warnings + +from astroid.nodes.scoped_nodes import ( + AsyncFunctionDef, + ClassDef, + ComprehensionScope, + DictComp, + FunctionDef, + GeneratorExp, + Lambda, + ListComp, + LocalsDictNodeNG, + Module, + SetComp, + _is_metaclass, + builtin_lookup, + function_to_method, + get_wrapping_class, ) -from astroid.interpreter.dunder_lookup import lookup -from astroid.interpreter.objectmodel import ClassModel, FunctionModel, ModuleModel -from astroid.manager import AstroidManager -ITER_METHODS = ("__iter__", "__getitem__") -EXCEPTION_BASE_CLASSES = frozenset({"Exception", "BaseException"}) -objects = util.lazy_import("objects") -BUILTIN_DESCRIPTORS = frozenset( - {"classmethod", "staticmethod", "builtins.classmethod", "builtins.staticmethod"} +# We cannot create a __all__ here because it would create a circular import +# Please remove astroid/scoped_nodes.py|astroid/node_classes.py in autoflake +# exclude when removing this file. +warnings.warn( + "The 'astroid.scoped_nodes' module is deprecated and will be replaced by 'astroid.nodes' in astroid 3.0.0", + DeprecationWarning, ) - - -def _c3_merge(sequences, cls, context): - """Merges MROs in *sequences* to a single MRO using the C3 algorithm. - - Adapted from http://www.python.org/download/releases/2.3/mro/. - - """ - result = [] - while True: - sequences = [s for s in sequences if s] # purge empty sequences - if not sequences: - return result - for s1 in sequences: # find merge candidates among seq heads - candidate = s1[0] - for s2 in sequences: - if candidate in s2[1:]: - candidate = None - break # reject the current head, it appears later - else: - break - if not candidate: - # Show all the remaining bases, which were considered as - # candidates for the next mro sequence. - raise InconsistentMroError( - message="Cannot create a consistent method resolution order " - "for MROs {mros} of class {cls!r}.", - mros=sequences, - cls=cls, - context=context, - ) - - result.append(candidate) - # remove the chosen candidate - for seq in sequences: - if seq[0] == candidate: - del seq[0] - return None - - -def clean_typing_generic_mro(sequences: List[List["ClassDef"]]) -> None: - """A class can inherit from typing.Generic directly, as base, - and as base of bases. The merged MRO must however only contain the last entry. - To prepare for _c3_merge, remove some typing.Generic entries from - sequences if multiple are present. - - This method will check if Generic is in inferred_bases and also - part of bases_mro. If true, remove it from inferred_bases - as well as its entry the bases_mro. - - Format sequences: [[self]] + bases_mro + [inferred_bases] - """ - bases_mro = sequences[1:-1] - inferred_bases = sequences[-1] - # Check if Generic is part of inferred_bases - for i, base in enumerate(inferred_bases): - if base.qname() == "typing.Generic": - position_in_inferred_bases = i - break - else: - return - # Check if also part of bases_mro - # Ignore entry for typing.Generic - for i, seq in enumerate(bases_mro): - if i == position_in_inferred_bases: - continue - if any(base.qname() == "typing.Generic" for base in seq): - break - else: - return - # Found multiple Generics in mro, remove entry from inferred_bases - # and the corresponding one from bases_mro - inferred_bases.pop(position_in_inferred_bases) - bases_mro.pop(position_in_inferred_bases) - - -def clean_duplicates_mro(sequences, cls, context): - for sequence in sequences: - names = [ - (node.lineno, node.qname()) if node.name else None for node in sequence - ] - last_index = dict(map(reversed, enumerate(names))) - if names and names[0] is not None and last_index[names[0]] != 0: - raise DuplicateBasesError( - message="Duplicates found in MROs {mros} for {cls!r}.", - mros=sequences, - cls=cls, - context=context, - ) - yield [ - node - for i, (node, name) in enumerate(zip(sequence, names)) - if name is None or last_index[name] == i - ] - - -def function_to_method(n, klass): - if isinstance(n, FunctionDef): - if n.type == "classmethod": - return bases.BoundMethod(n, klass) - if n.type == "property": - return n - if n.type != "staticmethod": - return bases.UnboundMethod(n) - return n - - -def builtin_lookup(name): - """lookup a name into the builtin module - return the list of matching statements and the astroid for the builtin - module - """ - builtin_astroid = AstroidManager().ast_from_module(builtins) - if name == "__dict__": - return builtin_astroid, () - try: - stmts = builtin_astroid.locals[name] - except KeyError: - stmts = () - return builtin_astroid, stmts - - -# TODO move this Mixin to mixins.py; problem: 'FunctionDef' in _scope_lookup -class LocalsDictNodeNG(node_classes.LookupMixIn, node_classes.NodeNG): - """this class provides locals handling common to Module, FunctionDef - and ClassDef nodes, including a dict like interface for direct access - to locals information - """ - - # attributes below are set by the builder module or by raw factories - - locals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - - def qname(self): - """Get the 'qualified' name of the node. - - For example: module.name, module.class.name ... - - :returns: The qualified name. - :rtype: str - """ - # pylint: disable=no-member; github.com/pycqa/astroid/issues/278 - if self.parent is None: - return self.name - return f"{self.parent.frame().qname()}.{self.name}" - - def frame(self): - """The first parent frame node. - - A frame node is a :class:`Module`, :class:`FunctionDef`, - or :class:`ClassDef`. - - :returns: The first parent frame node. - :rtype: Module or FunctionDef or ClassDef - """ - return self - - def scope(self): - """The first parent node defining a new scope. - - :returns: The first parent scope node. - :rtype: Module or FunctionDef or ClassDef or Lambda or GenExpr - """ - return self - - def _scope_lookup(self, node, name, offset=0): - """XXX method for interfacing the scope lookup""" - try: - stmts = node._filter_stmts(self.locals[name], self, offset) - except KeyError: - stmts = () - if stmts: - return self, stmts - - # Handle nested scopes: since class names do not extend to nested - # scopes (e.g., methods), we find the next enclosing non-class scope - pscope = self.parent and self.parent.scope() - while pscope is not None: - if not isinstance(pscope, ClassDef): - return pscope.scope_lookup(node, name) - pscope = pscope.parent and pscope.parent.scope() - - # self is at the top level of a module, or is enclosed only by ClassDefs - return builtin_lookup(name) - - def set_local(self, name, stmt): - """Define that the given name is declared in the given statement node. - - .. seealso:: :meth:`scope` - - :param name: The name that is being defined. - :type name: str - - :param stmt: The statement that defines the given name. - :type stmt: NodeNG - """ - # assert not stmt in self.locals.get(name, ()), (self, stmt) - self.locals.setdefault(name, []).append(stmt) - - __setitem__ = set_local - - def _append_node(self, child): - """append a child, linking it in the tree""" - # pylint: disable=no-member; depending by the class - # which uses the current class as a mixin or base class. - # It's rewritten in 2.0, so it makes no sense for now - # to spend development time on it. - self.body.append(child) - child.parent = self - - def add_local_node(self, child_node, name=None): - """Append a child that should alter the locals of this scope node. - - :param child_node: The child node that will alter locals. - :type child_node: NodeNG - - :param name: The name of the local that will be altered by - the given child node. - :type name: str or None - """ - if name != "__class__": - # add __class__ node as a child will cause infinite recursion later! - self._append_node(child_node) - self.set_local(name or child_node.name, child_node) - - def __getitem__(self, item): - """The first node the defines the given local. - - :param item: The name of the locally defined object. - :type item: str - - :raises KeyError: If the name is not defined. - """ - return self.locals[item][0] - - def __iter__(self): - """Iterate over the names of locals defined in this scoped node. - - :returns: The names of the defined locals. - :rtype: iterable(str) - """ - return iter(self.keys()) - - def keys(self): - """The names of locals defined in this scoped node. - - :returns: The names of the defined locals. - :rtype: list(str) - """ - return list(self.locals.keys()) - - def values(self): - """The nodes that define the locals in this scoped node. - - :returns: The nodes that define locals. - :rtype: list(NodeNG) - """ - # pylint: disable=consider-using-dict-items - # It look like this class override items/keys/values, - # probably not worth the headache - return [self[key] for key in self.keys()] - - def items(self): - """Get the names of the locals and the node that defines the local. - - :returns: The names of locals and their associated node. - :rtype: list(tuple(str, NodeNG)) - """ - return list(zip(self.keys(), self.values())) - - def __contains__(self, name): - """Check if a local is defined in this scope. - - :param name: The name of the local to check for. - :type name: str - - :returns: True if this node has a local of the given name, - False otherwise. - :rtype: bool - """ - return name in self.locals - - -class Module(LocalsDictNodeNG): - """Class representing an :class:`ast.Module` node. - - >>> node = astroid.extract_node('import astroid') - >>> node - <Import l.1 at 0x7f23b2e4e5c0> - >>> node.parent - <Module l.0 at 0x7f23b2e4eda0> - """ - - _astroid_fields = ("body",) - - fromlineno = 0 - """The first line that this node appears on in the source code. - - :type: int or None - """ - lineno = 0 - """The line that this node appears on in the source code. - - :type: int or None - """ - - # attributes below are set by the builder module or by raw factories - - file = None - """The path to the file that this ast has been extracted from. - - This will be ``None`` when the representation has been built from a - built-in module. - - :type: str or None - """ - file_bytes = None - """The string/bytes that this ast was built from. - - :type: str or bytes or None - """ - file_encoding = None - """The encoding of the source file. - - This is used to get unicode out of a source file. - Python 2 only. - - :type: str or None - """ - name = None - """The name of the module. - - :type: str or None - """ - pure_python = None - """Whether the ast was built from source. - - :type: bool or None - """ - package = None - """Whether the node represents a package or a module. - - :type: bool or None - """ - globals = None - """A map of the name of a global variable to the node defining the global. - - :type: dict(str, NodeNG) - """ - - # Future imports - future_imports = None - """The imports from ``__future__``. - - :type: set(str) or None - """ - special_attributes = ModuleModel() - """The names of special attributes that this module has. - - :type: objectmodel.ModuleModel - """ - - # names of module attributes available through the global scope - scope_attrs = {"__name__", "__doc__", "__file__", "__path__", "__package__"} - """The names of module attributes available through the global scope. - - :type: str(str) - """ - - _other_fields = ( - "name", - "doc", - "file", - "path", - "package", - "pure_python", - "future_imports", - ) - _other_other_fields = ("locals", "globals") - - def __init__( - self, - name, - doc, - file=None, - path: Optional[List[str]] = None, - package=None, - parent=None, - pure_python=True, - ): - """ - :param name: The name of the module. - :type name: str - - :param doc: The module docstring. - :type doc: str - - :param file: The path to the file that this ast has been extracted from. - :type file: str or None - - :param path: - :type path: Optional[List[str]] - - :param package: Whether the node represents a package or a module. - :type package: bool or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - - :param pure_python: Whether the ast was built from source. - :type pure_python: bool or None - """ - self.name = name - self.doc = doc - self.file = file - self.path = path - self.package = package - self.parent = parent - self.pure_python = pure_python - self.locals = self.globals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - self.body = [] - """The contents of the module. - - :type: list(NodeNG) or None - """ - self.future_imports = set() - - # pylint: enable=redefined-builtin - - def postinit(self, body=None): - """Do some setup after initialisation. - - :param body: The contents of the module. - :type body: list(NodeNG) or None - """ - self.body = body - - def _get_stream(self): - if self.file_bytes is not None: - return io.BytesIO(self.file_bytes) - if self.file is not None: - # pylint: disable=consider-using-with - stream = open(self.file, "rb") - return stream - return None - - def stream(self): - """Get a stream to the underlying file or bytes. - - :type: file or io.BytesIO or None - """ - return self._get_stream() - - def block_range(self, lineno): - """Get a range from where this node starts to where this node ends. - - :param lineno: Unused. - :type lineno: int - - :returns: The range of line numbers that this node belongs to. - :rtype: tuple(int, int) - """ - return self.fromlineno, self.tolineno - - def scope_lookup(self, node, name, offset=0): - """Lookup where the given variable is assigned. - - :param node: The node to look for assignments up to. - Any assignments after the given node are ignored. - :type node: NodeNG - - :param name: The name of the variable to find assignments for. - :type name: str - - :param offset: The line offset to filter statements up to. - :type offset: int - - :returns: This scope node and the list of assignments associated to the - given name according to the scope where it has been found (locals, - globals or builtin). - :rtype: tuple(str, list(NodeNG)) - """ - if name in self.scope_attrs and name not in self.locals: - try: - return self, self.getattr(name) - except AttributeInferenceError: - return self, () - return self._scope_lookup(node, name, offset) - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - return "%s.module" % BUILTINS - - def display_type(self): - """A human readable type of this node. - - :returns: The type of this node. - :rtype: str - """ - return "Module" - - def getattr(self, name, context=None, ignore_locals=False): - if not name: - raise AttributeInferenceError(target=self, attribute=name, context=context) - - result = [] - name_in_locals = name in self.locals - - if name in self.special_attributes and not ignore_locals and not name_in_locals: - result = [self.special_attributes.lookup(name)] - elif not ignore_locals and name_in_locals: - result = self.locals[name] - elif self.package: - try: - result = [self.import_module(name, relative_only=True)] - except (AstroidBuildingError, SyntaxError) as exc: - raise AttributeInferenceError( - target=self, attribute=name, context=context - ) from exc - result = [n for n in result if not isinstance(n, node_classes.DelName)] - if result: - return result - raise AttributeInferenceError(target=self, attribute=name, context=context) - - def igetattr(self, name, context=None): - """Infer the possible values of the given variable. - - :param name: The name of the variable to infer. - :type name: str - - :returns: The inferred possible values. - :rtype: iterable(NodeNG) or None - """ - # set lookup name since this is necessary to infer on import nodes for - # instance - context = contextmod.copy_context(context) - context.lookupname = name - try: - return bases._infer_stmts(self.getattr(name, context), context, frame=self) - except AttributeInferenceError as error: - raise InferenceError( - str(error), target=self, attribute=name, context=context - ) from error - - def fully_defined(self): - """Check if this module has been build from a .py file. - - If so, the module contains a complete representation, - including the code. - - :returns: True if the module has been built from a .py file. - :rtype: bool - """ - return self.file is not None and self.file.endswith(".py") - - def statement(self): - """The first parent node, including self, marked as statement node. - - :returns: The first parent statement. - :rtype: NodeNG - """ - return self - - def previous_sibling(self): - """The previous sibling statement. - - :returns: The previous sibling statement node. - :rtype: NodeNG or None - """ - - def next_sibling(self): - """The next sibling statement node. - - :returns: The next sibling statement node. - :rtype: NodeNG or None - """ - - _absolute_import_activated = True - - def absolute_import_activated(self): - """Whether :pep:`328` absolute import behaviour has been enabled. - - :returns: True if :pep:`328` has been enabled, False otherwise. - :rtype: bool - """ - return self._absolute_import_activated - - def import_module(self, modname, relative_only=False, level=None): - """Get the ast for a given module as if imported from this module. - - :param modname: The name of the module to "import". - :type modname: str - - :param relative_only: Whether to only consider relative imports. - :type relative_only: bool - - :param level: The level of relative import. - :type level: int or None - - :returns: The imported module ast. - :rtype: NodeNG - """ - if relative_only and level is None: - level = 0 - absmodname = self.relative_to_absolute_name(modname, level) - - try: - return AstroidManager().ast_from_module_name(absmodname) - except AstroidBuildingError: - # we only want to import a sub module or package of this module, - # skip here - if relative_only: - raise - return AstroidManager().ast_from_module_name(modname) - - def relative_to_absolute_name(self, modname, level): - """Get the absolute module name for a relative import. - - The relative import can be implicit or explicit. - - :param modname: The module name to convert. - :type modname: str - - :param level: The level of relative import. - :type level: int - - :returns: The absolute module name. - :rtype: str - - :raises TooManyLevelsError: When the relative import refers to a - module too far above this one. - """ - # XXX this returns non sens when called on an absolute import - # like 'pylint.checkers.astroid.utils' - # XXX doesn't return absolute name if self.name isn't absolute name - if self.absolute_import_activated() and level is None: - return modname - if level: - if self.package: - level = level - 1 - if level and self.name.count(".") < level: - raise TooManyLevelsError(level=level, name=self.name) - - package_name = self.name.rsplit(".", level)[0] - elif self.package: - package_name = self.name - else: - package_name = self.name.rsplit(".", 1)[0] - - if package_name: - if not modname: - return package_name - return f"{package_name}.{modname}" - return modname - - def wildcard_import_names(self): - """The list of imported names when this module is 'wildcard imported'. - - It doesn't include the '__builtins__' name which is added by the - current CPython implementation of wildcard imports. - - :returns: The list of imported names. - :rtype: list(str) - """ - # We separate the different steps of lookup in try/excepts - # to avoid catching too many Exceptions - default = [name for name in self.keys() if not name.startswith("_")] - try: - all_values = self["__all__"] - except KeyError: - return default - - try: - explicit = next(all_values.assigned_stmts()) - except (InferenceError, StopIteration): - return default - except AttributeError: - # not an assignment node - # XXX infer? - return default - - # Try our best to detect the exported name. - inferred = [] - try: - explicit = next(explicit.infer()) - except (InferenceError, StopIteration): - return default - if not isinstance(explicit, (node_classes.Tuple, node_classes.List)): - return default - - def str_const(node): - return isinstance(node, node_classes.Const) and isinstance(node.value, str) - - for node in explicit.elts: - if str_const(node): - inferred.append(node.value) - else: - try: - inferred_node = next(node.infer()) - except (InferenceError, StopIteration): - continue - if str_const(inferred_node): - inferred.append(inferred_node.value) - return inferred - - def public_names(self): - """The list of the names that are publicly available in this module. - - :returns: The list of publc names. - :rtype: list(str) - """ - return [name for name in self.keys() if not name.startswith("_")] - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`Module` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - yield from self.body - - -class ComprehensionScope(LocalsDictNodeNG): - """Scoping for different types of comprehensions.""" - - def frame(self): - """The first parent frame node. - - A frame node is a :class:`Module`, :class:`FunctionDef`, - or :class:`ClassDef`. - - :returns: The first parent frame node. - :rtype: Module or FunctionDef or ClassDef - """ - return self.parent.frame() - - scope_lookup = LocalsDictNodeNG._scope_lookup - - -class GeneratorExp(ComprehensionScope): - """Class representing an :class:`ast.GeneratorExp` node. - - >>> node = astroid.extract_node('(thing for thing in things if thing)') - >>> node - <GeneratorExp l.1 at 0x7f23b2e4e400> - """ - - _astroid_fields = ("elt", "generators") - _other_other_fields = ("locals",) - elt = None - """The element that forms the output of the expression. - - :type: NodeNG or None - """ - generators = None - """The generators that are looped through. - - :type: list(Comprehension) or None - """ - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.locals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, elt=None, generators=None): - """Do some setup after initialisation. - - :param elt: The element that forms the output of the expression. - :type elt: NodeNG or None - - :param generators: The generators that are looped through. - :type generators: list(Comprehension) or None - """ - self.elt = elt - if generators is None: - self.generators = [] - else: - self.generators = generators - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`GeneratorExp` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - yield self.elt - - yield from self.generators - - -class DictComp(ComprehensionScope): - """Class representing an :class:`ast.DictComp` node. - - >>> node = astroid.extract_node('{k:v for k, v in things if k > v}') - >>> node - <DictComp l.1 at 0x7f23b2e41d68> - """ - - _astroid_fields = ("key", "value", "generators") - _other_other_fields = ("locals",) - key = None - """What produces the keys. - - :type: NodeNG or None - """ - value = None - """What produces the values. - - :type: NodeNG or None - """ - generators = None - """The generators that are looped through. - - :type: list(Comprehension) or None - """ - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.locals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, key=None, value=None, generators=None): - """Do some setup after initialisation. - - :param key: What produces the keys. - :type key: NodeNG or None - - :param value: What produces the values. - :type value: NodeNG or None - - :param generators: The generators that are looped through. - :type generators: list(Comprehension) or None - """ - self.key = key - self.value = value - if generators is None: - self.generators = [] - else: - self.generators = generators - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`DictComp` this is always :class:`Uninferable`. - :rtype: Uninferable - """ - return util.Uninferable - - def get_children(self): - yield self.key - yield self.value - - yield from self.generators - - -class SetComp(ComprehensionScope): - """Class representing an :class:`ast.SetComp` node. - - >>> node = astroid.extract_node('{thing for thing in things if thing}') - >>> node - <SetComp l.1 at 0x7f23b2e41898> - """ - - _astroid_fields = ("elt", "generators") - _other_other_fields = ("locals",) - elt = None - """The element that forms the output of the expression. - - :type: NodeNG or None - """ - generators = None - """The generators that are looped through. - - :type: list(Comprehension) or None - """ - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.locals = {} - """A map of the name of a local variable to the node defining the local. - - :type: dict(str, NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, elt=None, generators=None): - """Do some setup after initialisation. - - :param elt: The element that forms the output of the expression. - :type elt: NodeNG or None - - :param generators: The generators that are looped through. - :type generators: list(Comprehension) or None - """ - self.elt = elt - if generators is None: - self.generators = [] - else: - self.generators = generators - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`SetComp` this is always :class:`Uninferable`. - :rtype: Uninferable - """ - return util.Uninferable - - def get_children(self): - yield self.elt - - yield from self.generators - - -class _ListComp(node_classes.NodeNG): - """Class representing an :class:`ast.ListComp` node. - - >>> node = astroid.extract_node('[thing for thing in things if thing]') - >>> node - <ListComp l.1 at 0x7f23b2e418d0> - """ - - _astroid_fields = ("elt", "generators") - elt = None - """The element that forms the output of the expression. - - :type: NodeNG or None - """ - generators = None - """The generators that are looped through. - - :type: list(Comprehension) or None - """ - - def postinit(self, elt=None, generators=None): - """Do some setup after initialisation. - - :param elt: The element that forms the output of the expression. - :type elt: NodeNG or None - - :param generators: The generators that are looped through. - :type generators: list(Comprehension) or None - """ - self.elt = elt - self.generators = generators - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`ListComp` this is always :class:`Uninferable`. - :rtype: Uninferable - """ - return util.Uninferable - - def get_children(self): - yield self.elt - - yield from self.generators - - -class ListComp(_ListComp, ComprehensionScope): - """Class representing an :class:`ast.ListComp` node. - - >>> node = astroid.extract_node('[thing for thing in things if thing]') - >>> node - <ListComp l.1 at 0x7f23b2e418d0> - """ - - _other_other_fields = ("locals",) - - def __init__(self, lineno=None, col_offset=None, parent=None): - self.locals = {} - """A map of the name of a local variable to the node defining it. - - :type: dict(str, NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - -def _infer_decorator_callchain(node): - """Detect decorator call chaining and see if the end result is a - static or a classmethod. - """ - if not isinstance(node, FunctionDef): - return None - if not node.parent: - return None - try: - result = next(node.infer_call_result(node.parent), None) - except InferenceError: - return None - if isinstance(result, bases.Instance): - result = result._proxied - if isinstance(result, ClassDef): - if result.is_subtype_of("%s.classmethod" % BUILTINS): - return "classmethod" - if result.is_subtype_of("%s.staticmethod" % BUILTINS): - return "staticmethod" - if isinstance(result, FunctionDef): - if not result.decorators: - return None - # Determine if this function is decorated with one of the builtin descriptors we want. - for decorator in result.decorators.nodes: - if isinstance(decorator, node_classes.Name): - if decorator.name in BUILTIN_DESCRIPTORS: - return decorator.name - if ( - isinstance(decorator, node_classes.Attribute) - and isinstance(decorator.expr, node_classes.Name) - and decorator.expr.name == BUILTINS - and decorator.attrname in BUILTIN_DESCRIPTORS - ): - return decorator.attrname - return None - - -class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG): - """Class representing an :class:`ast.Lambda` node. - - >>> node = astroid.extract_node('lambda arg: arg + 1') - >>> node - <Lambda.<lambda> l.1 at 0x7f23b2e41518> - """ - - _astroid_fields = ("args", "body") - _other_other_fields = ("locals",) - name = "<lambda>" - is_lambda = True - - def implicit_parameters(self): - return 0 - - # function's type, 'function' | 'method' | 'staticmethod' | 'classmethod' - @property - def type(self): - """Whether this is a method or function. - - :returns: 'method' if this is a method, 'function' otherwise. - :rtype: str - """ - # pylint: disable=no-member - if self.args.arguments and self.args.arguments[0].name == "self": - if isinstance(self.parent.scope(), ClassDef): - return "method" - return "function" - - def __init__(self, lineno=None, col_offset=None, parent=None): - """ - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.locals = {} - """A map of the name of a local variable to the node defining it. - - :type: dict(str, NodeNG) - """ - - self.args = [] - """The arguments that the function takes. - - :type: Arguments or list - """ - - self.body = [] - """The contents of the function body. - - :type: list(NodeNG) - """ - - super().__init__(lineno, col_offset, parent) - - def postinit(self, args, body): - """Do some setup after initialisation. - - :param args: The arguments that the function takes. - :type args: Arguments - - :param body: The contents of the function body. - :type body: list(NodeNG) - """ - self.args = args - self.body = body - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - if "method" in self.type: - return "%s.instancemethod" % BUILTINS - return "%s.function" % BUILTINS - - def display_type(self): - """A human readable type of this node. - - :returns: The type of this node. - :rtype: str - """ - if "method" in self.type: - return "Method" - return "Function" - - def callable(self): - """Whether this node defines something that is callable. - - :returns: True if this defines something that is callable, - False otherwise. - For a :class:`Lambda` this is always ``True``. - :rtype: bool - """ - return True - - def argnames(self): - """Get the names of each of the arguments. - - :returns: The names of the arguments. - :rtype: list(str) - """ - # pylint: disable=no-member; github.com/pycqa/astroid/issues/291 - # args is in fact redefined later on by postinit. Can't be changed - # to None due to a strong interaction between Lambda and FunctionDef. - - if self.args.arguments: # maybe None with builtin functions - names = _rec_get_names(self.args.arguments) - else: - names = [] - if self.args.vararg: - names.append(self.args.vararg) - if self.args.kwarg: - names.append(self.args.kwarg) - return names - - def infer_call_result(self, caller, context=None): - """Infer what the function returns when called. - - :param caller: Unused - :type caller: object - """ - # pylint: disable=no-member; github.com/pycqa/astroid/issues/291 - # args is in fact redefined later on by postinit. Can't be changed - # to None due to a strong interaction between Lambda and FunctionDef. - return self.body.infer(context) - - def scope_lookup(self, node, name, offset=0): - """Lookup where the given names is assigned. - - :param node: The node to look for assignments up to. - Any assignments after the given node are ignored. - :type node: NodeNG - - :param name: The name to find assignments for. - :type name: str - - :param offset: The line offset to filter statements up to. - :type offset: int - - :returns: This scope node and the list of assignments associated to the - given name according to the scope where it has been found (locals, - globals or builtin). - :rtype: tuple(str, list(NodeNG)) - """ - # pylint: disable=no-member; github.com/pycqa/astroid/issues/291 - # args is in fact redefined later on by postinit. Can't be changed - # to None due to a strong interaction between Lambda and FunctionDef. - - if node in self.args.defaults or node in self.args.kw_defaults: - frame = self.parent.frame() - # line offset to avoid that def func(f=func) resolve the default - # value to the defined function - offset = -1 - else: - # check this is not used in function decorators - frame = self - return frame._scope_lookup(node, name, offset) - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`Lambda` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - yield self.args - yield self.body - - -class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda): - """Class representing an :class:`ast.FunctionDef`. - - >>> node = astroid.extract_node(''' - ... def my_func(arg): - ... return arg + 1 - ... ''') - >>> node - <FunctionDef.my_func l.2 at 0x7f23b2e71e10> - """ - - _astroid_fields = ("decorators", "args", "returns", "body") - _multi_line_block_fields = ("body",) - returns = None - decorators = None - """The decorators that are applied to this method or function. - - :type: Decorators or None - """ - special_attributes = FunctionModel() - """The names of special attributes that this function has. - - :type: objectmodel.FunctionModel - """ - is_function = True - """Whether this node indicates a function. - - For a :class:`FunctionDef` this is always ``True``. - - :type: bool - """ - type_annotation = None - """If present, this will contain the type annotation passed by a type comment - - :type: NodeNG or None - """ - type_comment_args = None - """ - If present, this will contain the type annotation for arguments - passed by a type comment - """ - type_comment_returns = None - """If present, this will contain the return type annotation, passed by a type comment""" - # attributes below are set by the builder module or by raw factories - _other_fields = ("name", "doc") - _other_other_fields = ( - "locals", - "_type", - "type_comment_returns", - "type_comment_args", - ) - _type = None - - def __init__(self, name=None, doc=None, lineno=None, col_offset=None, parent=None): - """ - :param name: The name of the function. - :type name: str or None - - :param doc: The function's docstring. - :type doc: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.name = name - """The name of the function. - - :type name: str or None - """ - - self.doc = doc - """The function's docstring. - - :type doc: str or None - """ - - self.instance_attrs = {} - super().__init__(lineno, col_offset, parent) - if parent: - frame = parent.frame() - frame.set_local(name, self) - - # pylint: disable=arguments-differ; different than Lambdas - def postinit( - self, - args, - body, - decorators=None, - returns=None, - type_comment_returns=None, - type_comment_args=None, - ): - """Do some setup after initialisation. - - :param args: The arguments that the function takes. - :type args: Arguments or list - - :param body: The contents of the function body. - :type body: list(NodeNG) - - :param decorators: The decorators that are applied to this - method or function. - :type decorators: Decorators or None - :params type_comment_returns: - The return type annotation passed via a type comment. - :params type_comment_args: - The args type annotation passed via a type comment. - """ - self.args = args - self.body = body - self.decorators = decorators - self.returns = returns - self.type_comment_returns = type_comment_returns - self.type_comment_args = type_comment_args - - @decorators_mod.cachedproperty - def extra_decorators(self): - """The extra decorators that this function can have. - - Additional decorators are considered when they are used as - assignments, as in ``method = staticmethod(method)``. - The property will return all the callables that are used for - decoration. - - :type: list(NodeNG) - """ - frame = self.parent.frame() - if not isinstance(frame, ClassDef): - return [] - - decorators = [] - for assign in frame._get_assign_nodes(): - if isinstance(assign.value, node_classes.Call) and isinstance( - assign.value.func, node_classes.Name - ): - for assign_node in assign.targets: - if not isinstance(assign_node, node_classes.AssignName): - # Support only `name = callable(name)` - continue - - if assign_node.name != self.name: - # Interested only in the assignment nodes that - # decorates the current method. - continue - try: - meth = frame[self.name] - except KeyError: - continue - else: - # Must be a function and in the same frame as the - # original method. - if ( - isinstance(meth, FunctionDef) - and assign_node.frame() == frame - ): - decorators.append(assign.value) - return decorators - - @decorators_mod.cachedproperty - def type( - self, - ): # pylint: disable=invalid-overridden-method,too-many-return-statements - """The function type for this node. - - Possible values are: method, function, staticmethod, classmethod. - - :type: str - """ - for decorator in self.extra_decorators: - if decorator.func.name in BUILTIN_DESCRIPTORS: - return decorator.func.name - - frame = self.parent.frame() - type_name = "function" - if isinstance(frame, ClassDef): - if self.name == "__new__": - return "classmethod" - if self.name == "__init_subclass__": - return "classmethod" - - type_name = "method" - - if not self.decorators: - return type_name - - for node in self.decorators.nodes: - if isinstance(node, node_classes.Name): - if node.name in BUILTIN_DESCRIPTORS: - return node.name - if ( - isinstance(node, node_classes.Attribute) - and isinstance(node.expr, node_classes.Name) - and node.expr.name == BUILTINS - and node.attrname in BUILTIN_DESCRIPTORS - ): - return node.attrname - - if isinstance(node, node_classes.Call): - # Handle the following case: - # @some_decorator(arg1, arg2) - # def func(...) - # - try: - current = next(node.func.infer()) - except (InferenceError, StopIteration): - continue - _type = _infer_decorator_callchain(current) - if _type is not None: - return _type - - try: - for inferred in node.infer(): - # Check to see if this returns a static or a class method. - _type = _infer_decorator_callchain(inferred) - if _type is not None: - return _type - - if not isinstance(inferred, ClassDef): - continue - for ancestor in inferred.ancestors(): - if not isinstance(ancestor, ClassDef): - continue - if ancestor.is_subtype_of("%s.classmethod" % BUILTINS): - return "classmethod" - if ancestor.is_subtype_of("%s.staticmethod" % BUILTINS): - return "staticmethod" - except InferenceError: - pass - return type_name - - @decorators_mod.cachedproperty - def fromlineno(self): - """The first line that this node appears on in the source code. - - :type: int or None - """ - # lineno is the line number of the first decorator, we want the def - # statement lineno - lineno = self.lineno - if self.decorators is not None: - lineno += sum( - node.tolineno - node.lineno + 1 for node in self.decorators.nodes - ) - - return lineno - - @decorators_mod.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - return self.args.tolineno - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: Unused. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - :rtype: tuple(int, int) - """ - return self.fromlineno, self.tolineno - - def getattr(self, name, context=None): - """this method doesn't look in the instance_attrs dictionary since it's - done by an Instance proxy at inference time. - """ - if not name: - raise AttributeInferenceError(target=self, attribute=name, context=context) - - found_attrs = [] - if name in self.instance_attrs: - found_attrs = self.instance_attrs[name] - if name in self.special_attributes: - found_attrs.append(self.special_attributes.lookup(name)) - if found_attrs: - return found_attrs - raise AttributeInferenceError(target=self, attribute=name) - - def igetattr(self, name, context=None): - """Inferred getattr, which returns an iterator of inferred statements.""" - try: - return bases._infer_stmts(self.getattr(name, context), context, frame=self) - except AttributeInferenceError as error: - raise InferenceError( - str(error), target=self, attribute=name, context=context - ) from error - - def is_method(self): - """Check if this function node represents a method. - - :returns: True if this is a method, False otherwise. - :rtype: bool - """ - # check we are defined in a ClassDef, because this is usually expected - # (e.g. pylint...) when is_method() return True - return self.type != "function" and isinstance(self.parent.frame(), ClassDef) - - @decorators_mod.cached - def decoratornames(self, context=None): - """Get the qualified names of each of the decorators on this function. - - :param context: - An inference context that can be passed to inference functions - :returns: The names of the decorators. - :rtype: set(str) - """ - result = set() - decoratornodes = [] - if self.decorators is not None: - decoratornodes += self.decorators.nodes - decoratornodes += self.extra_decorators - for decnode in decoratornodes: - try: - for infnode in decnode.infer(context=context): - result.add(infnode.qname()) - except InferenceError: - continue - return result - - def is_bound(self): - """Check if the function is bound to an instance or class. - - :returns: True if the function is bound to an instance or class, - False otherwise. - :rtype: bool - """ - return self.type == "classmethod" - - def is_abstract(self, pass_is_abstract=True, any_raise_is_abstract=False): - """Check if the method is abstract. - - A method is considered abstract if any of the following is true: - * The only statement is 'raise NotImplementedError' - * The only statement is 'raise <SomeException>' and any_raise_is_abstract is True - * The only statement is 'pass' and pass_is_abstract is True - * The method is annotated with abc.astractproperty/abc.abstractmethod - - :returns: True if the method is abstract, False otherwise. - :rtype: bool - """ - if self.decorators: - for node in self.decorators.nodes: - try: - inferred = next(node.infer()) - except (InferenceError, StopIteration): - continue - if inferred and inferred.qname() in ( - "abc.abstractproperty", - "abc.abstractmethod", - ): - return True - - for child_node in self.body: - if isinstance(child_node, node_classes.Raise): - if any_raise_is_abstract: - return True - if child_node.raises_not_implemented(): - return True - return pass_is_abstract and isinstance(child_node, node_classes.Pass) - # empty function is the same as function with a single "pass" statement - if pass_is_abstract: - return True - - def is_generator(self): - """Check if this is a generator function. - - :returns: True is this is a generator function, False otherwise. - :rtype: bool - """ - return bool(next(self._get_yield_nodes_skip_lambdas(), False)) - - def infer_yield_result(self, context=None): - """Infer what the function yields when called - - :returns: What the function yields - :rtype: iterable(NodeNG or Uninferable) or None - """ - for yield_ in self.nodes_of_class(node_classes.Yield): - if yield_.value is None: - const = node_classes.Const(None) - const.parent = yield_ - const.lineno = yield_.lineno - yield const - elif yield_.scope() == self: - yield from yield_.value.infer(context=context) - - def infer_call_result(self, caller=None, context=None): - """Infer what the function returns when called. - - :returns: What the function returns. - :rtype: iterable(NodeNG or Uninferable) or None - """ - if self.is_generator(): - if isinstance(self, AsyncFunctionDef): - generator_cls = bases.AsyncGenerator - else: - generator_cls = bases.Generator - result = generator_cls(self, generator_initial_context=context) - yield result - return - # This is really a gigantic hack to work around metaclass generators - # that return transient class-generating functions. Pylint's AST structure - # cannot handle a base class object that is only used for calling __new__, - # but does not contribute to the inheritance structure itself. We inject - # a fake class into the hierarchy here for several well-known metaclass - # generators, and filter it out later. - if ( - self.name == "with_metaclass" - and len(self.args.args) == 1 - and self.args.vararg is not None - ): - metaclass = next(caller.args[0].infer(context), None) - if isinstance(metaclass, ClassDef): - try: - class_bases = [next(arg.infer(context)) for arg in caller.args[1:]] - except StopIteration as e: - raise InferenceError(node=caller.args[1:], context=context) from e - new_class = ClassDef(name="temporary_class") - new_class.hide = True - new_class.parent = self - new_class.postinit( - bases=[base for base in class_bases if base != util.Uninferable], - body=[], - decorators=[], - metaclass=metaclass, - ) - yield new_class - return - returns = self._get_return_nodes_skip_functions() - - first_return = next(returns, None) - if not first_return: - if self.body: - if self.is_abstract(pass_is_abstract=True, any_raise_is_abstract=True): - yield util.Uninferable - else: - yield node_classes.Const(None) - return - - raise InferenceError("The function does not have any return statements") - - for returnnode in itertools.chain((first_return,), returns): - if returnnode.value is None: - yield node_classes.Const(None) - else: - try: - yield from returnnode.value.infer(context) - except InferenceError: - yield util.Uninferable - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`FunctionDef` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - if self.decorators is not None: - yield self.decorators - - yield self.args - - if self.returns is not None: - yield self.returns - - yield from self.body - - def scope_lookup(self, node, name, offset=0): - """Lookup where the given name is assigned.""" - if name == "__class__": - # __class__ is an implicit closure reference created by the compiler - # if any methods in a class body refer to either __class__ or super. - # In our case, we want to be able to look it up in the current scope - # when `__class__` is being used. - frame = self.parent.frame() - if isinstance(frame, ClassDef): - return self, [frame] - return super().scope_lookup(node, name, offset) - - -class AsyncFunctionDef(FunctionDef): - """Class representing an :class:`ast.FunctionDef` node. - - A :class:`AsyncFunctionDef` is an asynchronous function - created with the `async` keyword. - - >>> node = astroid.extract_node(''' - async def func(things): - async for thing in things: - print(thing) - ''') - >>> node - <AsyncFunctionDef.func l.2 at 0x7f23b2e416d8> - >>> node.body[0] - <AsyncFor l.3 at 0x7f23b2e417b8> - """ - - -def _rec_get_names(args, names=None): - """return a list of all argument names""" - if names is None: - names = [] - for arg in args: - if isinstance(arg, node_classes.Tuple): - _rec_get_names(arg.elts, names) - else: - names.append(arg.name) - return names - - -def _is_metaclass(klass, seen=None): - """Return if the given class can be - used as a metaclass. - """ - if klass.name == "type": - return True - if seen is None: - seen = set() - for base in klass.bases: - try: - for baseobj in base.infer(): - baseobj_name = baseobj.qname() - if baseobj_name in seen: - continue - - seen.add(baseobj_name) - if isinstance(baseobj, bases.Instance): - # not abstract - return False - if baseobj is util.Uninferable: - continue - if baseobj is klass: - continue - if not isinstance(baseobj, ClassDef): - continue - if baseobj._type == "metaclass": - return True - if _is_metaclass(baseobj, seen): - return True - except InferenceError: - continue - return False - - -def _class_type(klass, ancestors=None): - """return a ClassDef node type to differ metaclass and exception - from 'regular' classes - """ - # XXX we have to store ancestors in case we have an ancestor loop - if klass._type is not None: - return klass._type - if _is_metaclass(klass): - klass._type = "metaclass" - elif klass.name.endswith("Exception"): - klass._type = "exception" - else: - if ancestors is None: - ancestors = set() - klass_name = klass.qname() - if klass_name in ancestors: - # XXX we are in loop ancestors, and have found no type - klass._type = "class" - return "class" - ancestors.add(klass_name) - for base in klass.ancestors(recurs=False): - name = _class_type(base, ancestors) - if name != "class": - if name == "metaclass" and not _is_metaclass(klass): - # don't propagate it if the current class - # can't be a metaclass - continue - klass._type = base.type - break - if klass._type is None: - klass._type = "class" - return klass._type - - -def get_wrapping_class(node): - """Get the class that wraps the given node. - - We consider that a class wraps a node if the class - is a parent for the said node. - - :returns: The class that wraps the given node - :rtype: ClassDef or None - """ - - klass = node.frame() - while klass is not None and not isinstance(klass, ClassDef): - if klass.parent is None: - klass = None - else: - klass = klass.parent.frame() - return klass - - -class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement): - """Class representing an :class:`ast.ClassDef` node. - - >>> node = astroid.extract_node(''' - class Thing: - def my_meth(self, arg): - return arg + self.offset - ''') - >>> node - <ClassDef.Thing l.2 at 0x7f23b2e9e748> - """ - - # some of the attributes below are set by the builder module or - # by a raw factories - - # a dictionary of class instances attributes - _astroid_fields = ("decorators", "bases", "keywords", "body") # name - - decorators = None - """The decorators that are applied to this class. - - :type: Decorators or None - """ - special_attributes = ClassModel() - """The names of special attributes that this class has. - - :type: objectmodel.ClassModel - """ - - _type = None - _metaclass_hack = False - hide = False - type = property( - _class_type, - doc=( - "The class type for this node.\n\n" - "Possible values are: class, metaclass, exception.\n\n" - ":type: str" - ), - ) - _other_fields = ("name", "doc") - _other_other_fields = ("locals", "_newstyle") - _newstyle = None - - def __init__(self, name=None, doc=None, lineno=None, col_offset=None, parent=None): - """ - :param name: The name of the class. - :type name: str or None - - :param doc: The function's docstring. - :type doc: str or None - - :param lineno: The line that this node appears on in the source code. - :type lineno: int or None - - :param col_offset: The column that this node appears on in the - source code. - :type col_offset: int or None - - :param parent: The parent node in the syntax tree. - :type parent: NodeNG or None - """ - self.instance_attrs = {} - self.locals = {} - """A map of the name of a local variable to the node defining it. - - :type: dict(str, NodeNG) - """ - - self.keywords = [] - """The keywords given to the class definition. - - This is usually for :pep:`3115` style metaclass declaration. - - :type: list(Keyword) or None - """ - - self.bases = [] - """What the class inherits from. - - :type: list(NodeNG) - """ - - self.body = [] - """The contents of the class body. - - :type: list(NodeNG) - """ - - self.name = name - """The name of the class. - - :type name: str or None - """ - - self.doc = doc - """The class' docstring. - - :type doc: str or None - """ - - super().__init__(lineno, col_offset, parent) - if parent is not None: - parent.frame().set_local(name, self) - - for local_name, node in self.implicit_locals(): - self.add_local_node(node, local_name) - - def implicit_parameters(self): - return 1 - - def implicit_locals(self): - """Get implicitly defined class definition locals. - - :returns: the the name and Const pair for each local - :rtype: tuple(tuple(str, node_classes.Const), ...) - """ - locals_ = (("__module__", self.special_attributes.attr___module__),) - # __qualname__ is defined in PEP3155 - locals_ += (("__qualname__", self.special_attributes.attr___qualname__),) - return locals_ - - # pylint: disable=redefined-outer-name - def postinit( - self, bases, body, decorators, newstyle=None, metaclass=None, keywords=None - ): - """Do some setup after initialisation. - - :param bases: What the class inherits from. - :type bases: list(NodeNG) - - :param body: The contents of the class body. - :type body: list(NodeNG) - - :param decorators: The decorators that are applied to this class. - :type decorators: Decorators or None - - :param newstyle: Whether this is a new style class or not. - :type newstyle: bool or None - - :param metaclass: The metaclass of this class. - :type metaclass: NodeNG or None - - :param keywords: The keywords given to the class definition. - :type keywords: list(Keyword) or None - """ - self.keywords = keywords - self.bases = bases - self.body = body - self.decorators = decorators - if newstyle is not None: - self._newstyle = newstyle - if metaclass is not None: - self._metaclass = metaclass - - def _newstyle_impl(self, context=None): - if context is None: - context = contextmod.InferenceContext() - if self._newstyle is not None: - return self._newstyle - for base in self.ancestors(recurs=False, context=context): - if base._newstyle_impl(context): - self._newstyle = True - break - klass = self.declared_metaclass() - # could be any callable, we'd need to infer the result of klass(name, - # bases, dict). punt if it's not a class node. - if klass is not None and isinstance(klass, ClassDef): - self._newstyle = klass._newstyle_impl(context) - if self._newstyle is None: - self._newstyle = False - return self._newstyle - - _newstyle = None - newstyle = property( - _newstyle_impl, - doc=("Whether this is a new style class or not\n\n" ":type: bool or None"), - ) - - @decorators_mod.cachedproperty - def blockstart_tolineno(self): - """The line on which the beginning of this block ends. - - :type: int - """ - if self.bases: - return self.bases[-1].tolineno - - return self.fromlineno - - def block_range(self, lineno): - """Get a range from the given line number to where this node ends. - - :param lineno: Unused. - :type lineno: int - - :returns: The range of line numbers that this node belongs to, - :rtype: tuple(int, int) - """ - return self.fromlineno, self.tolineno - - def pytype(self): - """Get the name of the type that this node represents. - - :returns: The name of the type. - :rtype: str - """ - if self.newstyle: - return "%s.type" % BUILTINS - return "%s.classobj" % BUILTINS - - def display_type(self): - """A human readable type of this node. - - :returns: The type of this node. - :rtype: str - """ - return "Class" - - def callable(self): - """Whether this node defines something that is callable. - - :returns: True if this defines something that is callable, - False otherwise. - For a :class:`ClassDef` this is always ``True``. - :rtype: bool - """ - return True - - def is_subtype_of(self, type_name, context=None): - """Whether this class is a subtype of the given type. - - :param type_name: The name of the type of check against. - :type type_name: str - - :returns: True if this class is a subtype of the given type, - False otherwise. - :rtype: bool - """ - if self.qname() == type_name: - return True - for anc in self.ancestors(context=context): - if anc.qname() == type_name: - return True - return False - - def _infer_type_call(self, caller, context): - try: - name_node = next(caller.args[0].infer(context)) - except StopIteration as e: - raise InferenceError(node=caller.args[0], context=context) from e - if isinstance(name_node, node_classes.Const) and isinstance( - name_node.value, str - ): - name = name_node.value - else: - return util.Uninferable - - result = ClassDef(name, None) - - # Get the bases of the class. - try: - class_bases = next(caller.args[1].infer(context)) - except StopIteration as e: - raise InferenceError(node=caller.args[1], context=context) from e - if isinstance(class_bases, (node_classes.Tuple, node_classes.List)): - bases = [] - for base in class_bases.itered(): - inferred = next(base.infer(context=context), None) - if inferred: - bases.append( - node_classes.EvaluatedObject(original=base, value=inferred) - ) - result.bases = bases - else: - # There is currently no AST node that can represent an 'unknown' - # node (Uninferable is not an AST node), therefore we simply return Uninferable here - # although we know at least the name of the class. - return util.Uninferable - - # Get the members of the class - try: - members = next(caller.args[2].infer(context)) - except (InferenceError, StopIteration): - members = None - - if members and isinstance(members, node_classes.Dict): - for attr, value in members.items: - if isinstance(attr, node_classes.Const) and isinstance(attr.value, str): - result.locals[attr.value] = [value] - - result.parent = caller.parent - return result - - def infer_call_result(self, caller, context=None): - """infer what a class is returning when called""" - if self.is_subtype_of(f"{BUILTINS}.type", context) and len(caller.args) == 3: - result = self._infer_type_call(caller, context) - yield result - return - - dunder_call = None - try: - metaclass = self.metaclass(context=context) - if metaclass is not None: - dunder_call = next(metaclass.igetattr("__call__", context)) - except (AttributeInferenceError, StopIteration): - pass - - if dunder_call and dunder_call.qname() != "builtins.type.__call__": - # Call type.__call__ if not set metaclass - # (since type is the default metaclass) - context = contextmod.bind_context_to_node(context, self) - yield from dunder_call.infer_call_result(caller, context) - else: - yield self.instantiate_class() - - def scope_lookup(self, node, name, offset=0): - """Lookup where the given name is assigned. - - :param node: The node to look for assignments up to. - Any assignments after the given node are ignored. - :type node: NodeNG - - :param name: The name to find assignments for. - :type name: str - - :param offset: The line offset to filter statements up to. - :type offset: int - - :returns: This scope node and the list of assignments associated to the - given name according to the scope where it has been found (locals, - globals or builtin). - :rtype: tuple(str, list(NodeNG)) - """ - # If the name looks like a builtin name, just try to look - # into the upper scope of this class. We might have a - # decorator that it's poorly named after a builtin object - # inside this class. - lookup_upper_frame = ( - isinstance(node.parent, node_classes.Decorators) - and name in AstroidManager().builtins_module - ) - if ( - any(node == base or base.parent_of(node) for base in self.bases) - or lookup_upper_frame - ): - # Handle the case where we have either a name - # in the bases of a class, which exists before - # the actual definition or the case where we have - # a Getattr node, with that name. - # - # name = ... - # class A(name): - # def name(self): ... - # - # import name - # class A(name.Name): - # def name(self): ... - - frame = self.parent.frame() - # line offset to avoid that class A(A) resolve the ancestor to - # the defined class - offset = -1 - else: - frame = self - return frame._scope_lookup(node, name, offset) - - @property - def basenames(self): - """The names of the parent classes - - Names are given in the order they appear in the class definition. - - :type: list(str) - """ - return [bnode.as_string() for bnode in self.bases] - - def ancestors(self, recurs=True, context=None): - """Iterate over the base classes in prefixed depth first order. - - :param recurs: Whether to recurse or return direct ancestors only. - :type recurs: bool - - :returns: The base classes - :rtype: iterable(NodeNG) - """ - # FIXME: should be possible to choose the resolution order - # FIXME: inference make infinite loops possible here - yielded = {self} - if context is None: - context = contextmod.InferenceContext() - if not self.bases and self.qname() != "builtins.object": - yield builtin_lookup("object")[1][0] - return - - for stmt in self.bases: - with context.restore_path(): - try: - for baseobj in stmt.infer(context): - if not isinstance(baseobj, ClassDef): - if isinstance(baseobj, bases.Instance): - baseobj = baseobj._proxied - else: - continue - if not baseobj.hide: - if baseobj in yielded: - continue - yielded.add(baseobj) - yield baseobj - if not recurs: - continue - for grandpa in baseobj.ancestors(recurs=True, context=context): - if grandpa is self: - # This class is the ancestor of itself. - break - if grandpa in yielded: - continue - yielded.add(grandpa) - yield grandpa - except InferenceError: - continue - - def local_attr_ancestors(self, name, context=None): - """Iterate over the parents that define the given name. - - :param name: The name to find definitions for. - :type name: str - - :returns: The parents that define the given name. - :rtype: iterable(NodeNG) - """ - # Look up in the mro if we can. This will result in the - # attribute being looked up just as Python does it. - try: - ancestors = self.mro(context)[1:] - except MroError: - # Fallback to use ancestors, we can't determine - # a sane MRO. - ancestors = self.ancestors(context=context) - for astroid in ancestors: - if name in astroid: - yield astroid - - def instance_attr_ancestors(self, name, context=None): - """Iterate over the parents that define the given name as an attribute. - - :param name: The name to find definitions for. - :type name: str - - :returns: The parents that define the given name as - an instance attribute. - :rtype: iterable(NodeNG) - """ - for astroid in self.ancestors(context=context): - if name in astroid.instance_attrs: - yield astroid - - def has_base(self, node): - """Whether this class directly inherits from the given node. - - :param node: The node to check for. - :type node: NodeNG - - :returns: True if this class directly inherits from the given node. - :rtype: bool - """ - return node in self.bases - - def local_attr(self, name, context=None): - """Get the list of assign nodes associated to the given name. - - Assignments are looked for in both this class and in parents. - - :returns: The list of assignments to the given name. - :rtype: list(NodeNG) - - :raises AttributeInferenceError: If no attribute with this name - can be found in this class or parent classes. - """ - result = [] - if name in self.locals: - result = self.locals[name] - else: - class_node = next(self.local_attr_ancestors(name, context), None) - if class_node: - result = class_node.locals[name] - result = [n for n in result if not isinstance(n, node_classes.DelAttr)] - if result: - return result - raise AttributeInferenceError(target=self, attribute=name, context=context) - - def instance_attr(self, name, context=None): - """Get the list of nodes associated to the given attribute name. - - Assignments are looked for in both this class and in parents. - - :returns: The list of assignments to the given name. - :rtype: list(NodeNG) - - :raises AttributeInferenceError: If no attribute with this name - can be found in this class or parent classes. - """ - # Return a copy, so we don't modify self.instance_attrs, - # which could lead to infinite loop. - values = list(self.instance_attrs.get(name, [])) - # get all values from parents - for class_node in self.instance_attr_ancestors(name, context): - values += class_node.instance_attrs[name] - values = [n for n in values if not isinstance(n, node_classes.DelAttr)] - if values: - return values - raise AttributeInferenceError(target=self, attribute=name, context=context) - - def instantiate_class(self): - """Get an :class:`Instance` of the :class:`ClassDef` node. - - :returns: An :class:`Instance` of the :class:`ClassDef` node, - or self if this is not possible. - :rtype: Instance or ClassDef - """ - try: - if any(cls.name in EXCEPTION_BASE_CLASSES for cls in self.mro()): - # Subclasses of exceptions can be exception instances - return objects.ExceptionInstance(self) - except MroError: - pass - return bases.Instance(self) - - def getattr(self, name, context=None, class_context=True): - """Get an attribute from this class, using Python's attribute semantic. - - This method doesn't look in the :attr:`instance_attrs` dictionary - since it is done by an :class:`Instance` proxy at inference time. - It may return an :class:`Uninferable` object if - the attribute has not been - found, but a ``__getattr__`` or ``__getattribute__`` method is defined. - If ``class_context`` is given, then it is considered that the - attribute is accessed from a class context, - e.g. ClassDef.attribute, otherwise it might have been accessed - from an instance as well. If ``class_context`` is used in that - case, then a lookup in the implicit metaclass and the explicit - metaclass will be done. - - :param name: The attribute to look for. - :type name: str - - :param class_context: Whether the attribute can be accessed statically. - :type class_context: bool - - :returns: The attribute. - :rtype: list(NodeNG) - - :raises AttributeInferenceError: If the attribute cannot be inferred. - """ - if not name: - raise AttributeInferenceError(target=self, attribute=name, context=context) - - values = self.locals.get(name, []) - if name in self.special_attributes and class_context and not values: - result = [self.special_attributes.lookup(name)] - if name == "__bases__": - # Need special treatment, since they are mutable - # and we need to return all the values. - result += values - return result - - # don't modify the list in self.locals! - values = list(values) - for classnode in self.ancestors(recurs=True, context=context): - values += classnode.locals.get(name, []) - - if class_context: - values += self._metaclass_lookup_attribute(name, context) - - if not values: - raise AttributeInferenceError(target=self, attribute=name, context=context) - - # Look for AnnAssigns, which are not attributes in the purest sense. - for value in values: - if isinstance(value, node_classes.AssignName): - stmt = value.statement() - if isinstance(stmt, node_classes.AnnAssign) and stmt.value is None: - raise AttributeInferenceError( - target=self, attribute=name, context=context - ) - return values - - def _metaclass_lookup_attribute(self, name, context): - """Search the given name in the implicit and the explicit metaclass.""" - attrs = set() - implicit_meta = self.implicit_metaclass() - context = contextmod.copy_context(context) - metaclass = self.metaclass(context=context) - for cls in (implicit_meta, metaclass): - if cls and cls != self and isinstance(cls, ClassDef): - cls_attributes = self._get_attribute_from_metaclass(cls, name, context) - attrs.update(set(cls_attributes)) - return attrs - - def _get_attribute_from_metaclass(self, cls, name, context): - try: - attrs = cls.getattr(name, context=context, class_context=True) - except AttributeInferenceError: - return - - for attr in bases._infer_stmts(attrs, context, frame=cls): - if not isinstance(attr, FunctionDef): - yield attr - continue - - if isinstance(attr, objects.Property): - yield attr - continue - if attr.type == "classmethod": - # If the method is a classmethod, then it will - # be bound to the metaclass, not to the class - # from where the attribute is retrieved. - # get_wrapping_class could return None, so just - # default to the current class. - frame = get_wrapping_class(attr) or self - yield bases.BoundMethod(attr, frame) - elif attr.type == "staticmethod": - yield attr - else: - yield bases.BoundMethod(attr, self) - - def igetattr(self, name, context=None, class_context=True): - """Infer the possible values of the given variable. - - :param name: The name of the variable to infer. - :type name: str - - :returns: The inferred possible values. - :rtype: iterable(NodeNG or Uninferable) - """ - # set lookup name since this is necessary to infer on import nodes for - # instance - context = contextmod.copy_context(context) - context.lookupname = name - - metaclass = self.metaclass(context=context) - try: - attributes = self.getattr(name, context, class_context=class_context) - # If we have more than one attribute, make sure that those starting from - # the second one are from the same scope. This is to account for modifications - # to the attribute happening *after* the attribute's definition (e.g. AugAssigns on lists) - if len(attributes) > 1: - first_attr, attributes = attributes[0], attributes[1:] - first_scope = first_attr.scope() - attributes = [first_attr] + [ - attr - for attr in attributes - if attr.parent and attr.parent.scope() == first_scope - ] - - for inferred in bases._infer_stmts(attributes, context, frame=self): - # yield Uninferable object instead of descriptors when necessary - if not isinstance(inferred, node_classes.Const) and isinstance( - inferred, bases.Instance - ): - try: - inferred._proxied.getattr("__get__", context) - except AttributeInferenceError: - yield inferred - else: - yield util.Uninferable - elif isinstance(inferred, objects.Property): - function = inferred.function - if not class_context: - # Through an instance so we can solve the property - yield from function.infer_call_result( - caller=self, context=context - ) - # If we're in a class context, we need to determine if the property - # was defined in the metaclass (a derived class must be a subclass of - # the metaclass of all its bases), in which case we can resolve the - # property. If not, i.e. the property is defined in some base class - # instead, then we return the property object - elif metaclass and function.parent.scope() is metaclass: - # Resolve a property as long as it is not accessed through - # the class itself. - yield from function.infer_call_result( - caller=self, context=context - ) - else: - yield inferred - else: - yield function_to_method(inferred, self) - except AttributeInferenceError as error: - if not name.startswith("__") and self.has_dynamic_getattr(context): - # class handle some dynamic attributes, return a Uninferable object - yield util.Uninferable - else: - raise InferenceError( - str(error), target=self, attribute=name, context=context - ) from error - - def has_dynamic_getattr(self, context=None): - """Check if the class has a custom __getattr__ or __getattribute__. - - If any such method is found and it is not from - builtins, nor from an extension module, then the function - will return True. - - :returns: True if the class has a custom - __getattr__ or __getattribute__, False otherwise. - :rtype: bool - """ - - def _valid_getattr(node): - root = node.root() - return root.name != BUILTINS and getattr(root, "pure_python", None) - - try: - return _valid_getattr(self.getattr("__getattr__", context)[0]) - except AttributeInferenceError: - # if self.newstyle: XXX cause an infinite recursion error - try: - getattribute = self.getattr("__getattribute__", context)[0] - return _valid_getattr(getattribute) - except AttributeInferenceError: - pass - return False - - def getitem(self, index, context=None): - """Return the inference of a subscript. - - This is basically looking up the method in the metaclass and calling it. - - :returns: The inferred value of a subscript to this class. - :rtype: NodeNG - - :raises AstroidTypeError: If this class does not define a - ``__getitem__`` method. - """ - try: - methods = lookup(self, "__getitem__") - except AttributeInferenceError as exc: - if isinstance(self, ClassDef): - # subscripting a class definition may be - # achieved thanks to __class_getitem__ method - # which is a classmethod defined in the class - # that supports subscript and not in the metaclass - try: - methods = self.getattr("__class_getitem__") - # Here it is assumed that the __class_getitem__ node is - # a FunctionDef. One possible improvement would be to deal - # with more generic inference. - except AttributeInferenceError: - raise AstroidTypeError(node=self, context=context) from exc - else: - raise AstroidTypeError(node=self, context=context) from exc - - method = methods[0] - - # Create a new callcontext for providing index as an argument. - new_context = contextmod.bind_context_to_node(context, self) - new_context.callcontext = contextmod.CallContext(args=[index]) - - try: - return next(method.infer_call_result(self, new_context), util.Uninferable) - except AttributeError: - # Starting with python3.9, builtin types list, dict etc... - # are subscriptable thanks to __class_getitem___ classmethod. - # However in such case the method is bound to an EmptyNode and - # EmptyNode doesn't have infer_call_result method yielding to - # AttributeError - if ( - isinstance(method, node_classes.EmptyNode) - and self.name in ("list", "dict", "set", "tuple", "frozenset") - and PY39_PLUS - ): - return self - raise - except InferenceError: - return util.Uninferable - - def methods(self): - """Iterate over all of the method defined in this class and its parents. - - :returns: The methods defined on the class. - :rtype: iterable(FunctionDef) - """ - done = {} - for astroid in itertools.chain(iter((self,)), self.ancestors()): - for meth in astroid.mymethods(): - if meth.name in done: - continue - done[meth.name] = None - yield meth - - def mymethods(self): - """Iterate over all of the method defined in this class only. - - :returns: The methods defined on the class. - :rtype: iterable(FunctionDef) - """ - for member in self.values(): - if isinstance(member, FunctionDef): - yield member - - def implicit_metaclass(self): - """Get the implicit metaclass of the current class. - - For newstyle classes, this will return an instance of builtins.type. - For oldstyle classes, it will simply return None, since there's - no implicit metaclass there. - - :returns: The metaclass. - :rtype: builtins.type or None - """ - if self.newstyle: - return builtin_lookup("type")[1][0] - return None - - _metaclass = None - - def declared_metaclass(self, context=None): - """Return the explicit declared metaclass for the current class. - - An explicit declared metaclass is defined - either by passing the ``metaclass`` keyword argument - in the class definition line (Python 3) or (Python 2) by - having a ``__metaclass__`` class attribute, or if there are - no explicit bases but there is a global ``__metaclass__`` variable. - - :returns: The metaclass of this class, - or None if one could not be found. - :rtype: NodeNG or None - """ - for base in self.bases: - try: - for baseobj in base.infer(context=context): - if isinstance(baseobj, ClassDef) and baseobj.hide: - self._metaclass = baseobj._metaclass - self._metaclass_hack = True - break - except InferenceError: - pass - - if self._metaclass: - # Expects this from Py3k TreeRebuilder - try: - return next( - node - for node in self._metaclass.infer(context=context) - if node is not util.Uninferable - ) - except (InferenceError, StopIteration): - return None - - return None - - def _find_metaclass(self, seen=None, context=None): - if seen is None: - seen = set() - seen.add(self) - - klass = self.declared_metaclass(context=context) - if klass is None: - for parent in self.ancestors(context=context): - if parent not in seen: - klass = parent._find_metaclass(seen) - if klass is not None: - break - return klass - - def metaclass(self, context=None): - """Get the metaclass of this class. - - If this class does not define explicitly a metaclass, - then the first defined metaclass in ancestors will be used - instead. - - :returns: The metaclass of this class. - :rtype: NodeNG or None - """ - return self._find_metaclass(context=context) - - def has_metaclass_hack(self): - return self._metaclass_hack - - def _islots(self): - """Return an iterator with the inferred slots.""" - if "__slots__" not in self.locals: - return None - for slots in self.igetattr("__slots__"): - # check if __slots__ is a valid type - for meth in ITER_METHODS: - try: - slots.getattr(meth) - break - except AttributeInferenceError: - continue - else: - continue - - if isinstance(slots, node_classes.Const): - # a string. Ignore the following checks, - # but yield the node, only if it has a value - if slots.value: - yield slots - continue - if not hasattr(slots, "itered"): - # we can't obtain the values, maybe a .deque? - continue - - if isinstance(slots, node_classes.Dict): - values = [item[0] for item in slots.items] - else: - values = slots.itered() - if values is util.Uninferable: - continue - if not values: - # Stop the iteration, because the class - # has an empty list of slots. - return values - - for elt in values: - try: - for inferred in elt.infer(): - if inferred is util.Uninferable: - continue - if not isinstance( - inferred, node_classes.Const - ) or not isinstance(inferred.value, str): - continue - if not inferred.value: - continue - yield inferred - except InferenceError: - continue - - return None - - def _slots(self): - if not self.newstyle: - raise NotImplementedError( - "The concept of slots is undefined for old-style classes." - ) - - slots = self._islots() - try: - first = next(slots) - except StopIteration as exc: - # The class doesn't have a __slots__ definition or empty slots. - if exc.args and exc.args[0] not in ("", None): - return exc.args[0] - return None - return [first] + list(slots) - - # Cached, because inferring them all the time is expensive - @decorators_mod.cached - def slots(self): - """Get all the slots for this node. - - :returns: The names of slots for this class. - If the class doesn't define any slot, through the ``__slots__`` - variable, then this function will return a None. - Also, it will return None in the case the slots were not inferred. - :rtype: list(str) or None - """ - - def grouped_slots( - mro: List["ClassDef"], - ) -> typing.Iterator[Optional[node_classes.NodeNG]]: - # Not interested in object, since it can't have slots. - for cls in mro[:-1]: - try: - cls_slots = cls._slots() - except NotImplementedError: - continue - if cls_slots is not None: - yield from cls_slots - else: - yield None - - if not self.newstyle: - raise NotImplementedError( - "The concept of slots is undefined for old-style classes." - ) - - try: - mro = self.mro() - except MroError as e: - raise NotImplementedError( - "Cannot get slots while parsing mro fails." - ) from e - - slots = list(grouped_slots(mro)) - if not all(slot is not None for slot in slots): - return None - - return sorted(set(slots), key=lambda item: item.value) - - def _inferred_bases(self, context=None): - # Similar with .ancestors, but the difference is when one base is inferred, - # only the first object is wanted. That's because - # we aren't interested in superclasses, as in the following - # example: - # - # class SomeSuperClass(object): pass - # class SomeClass(SomeSuperClass): pass - # class Test(SomeClass): pass - # - # Inferring SomeClass from the Test's bases will give - # us both SomeClass and SomeSuperClass, but we are interested - # only in SomeClass. - - if context is None: - context = contextmod.InferenceContext() - if not self.bases and self.qname() != "builtins.object": - yield builtin_lookup("object")[1][0] - return - - for stmt in self.bases: - try: - baseobj = next(stmt.infer(context=context.clone())) - except (InferenceError, StopIteration): - continue - if isinstance(baseobj, bases.Instance): - baseobj = baseobj._proxied - if not isinstance(baseobj, ClassDef): - continue - if not baseobj.hide: - yield baseobj - else: - yield from baseobj.bases - - def _compute_mro(self, context=None): - inferred_bases = list(self._inferred_bases(context=context)) - bases_mro = [] - for base in inferred_bases: - if base is self: - continue - - try: - mro = base._compute_mro(context=context) - bases_mro.append(mro) - except NotImplementedError: - # Some classes have in their ancestors both newstyle and - # old style classes. For these we can't retrieve the .mro, - # although in Python it's possible, since the class we are - # currently working is in fact new style. - # So, we fallback to ancestors here. - ancestors = list(base.ancestors(context=context)) - bases_mro.append(ancestors) - - unmerged_mro = [[self]] + bases_mro + [inferred_bases] - unmerged_mro = list(clean_duplicates_mro(unmerged_mro, self, context)) - clean_typing_generic_mro(unmerged_mro) - return _c3_merge(unmerged_mro, self, context) - - def mro(self, context=None) -> List["ClassDef"]: - """Get the method resolution order, using C3 linearization. - - :returns: The list of ancestors, sorted by the mro. - :rtype: list(NodeNG) - :raises DuplicateBasesError: Duplicate bases in the same class base - :raises InconsistentMroError: A class' MRO is inconsistent - """ - return self._compute_mro(context=context) - - def bool_value(self, context=None): - """Determine the boolean value of this node. - - :returns: The boolean value of this node. - For a :class:`ClassDef` this is always ``True``. - :rtype: bool - """ - return True - - def get_children(self): - if self.decorators is not None: - yield self.decorators - - yield from self.bases - if self.keywords is not None: - yield from self.keywords - yield from self.body - - @decorators_mod.cached - def _get_assign_nodes(self): - children_assign_nodes = ( - child_node._get_assign_nodes() for child_node in self.body - ) - return list(itertools.chain.from_iterable(children_assign_nodes)) diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py index 1d621181..c6926be4 100644 --- a/tests/unittest_nodes.py +++ b/tests/unittest_nodes.py @@ -477,8 +477,8 @@ class ImportNodeTest(resources.SysPathSetup, unittest.TestCase): def test_from_self_resolve(self): namenode = next(self.module.igetattr("NameNode")) self.assertTrue(isinstance(namenode, nodes.ClassDef), namenode) - self.assertEqual(namenode.root().name, "astroid.node_classes") - self.assertEqual(namenode.qname(), "astroid.node_classes.Name") + self.assertEqual(namenode.root().name, "astroid.nodes.node_classes") + self.assertEqual(namenode.qname(), "astroid.nodes.node_classes.Name") self.assertEqual(namenode.pytype(), "%s.type" % BUILTINS) abspath = next(self.module2.igetattr("abspath")) self.assertTrue(isinstance(abspath, nodes.FunctionDef), abspath) |
