1# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5"""Module for some node classes. More nodes in scoped_nodes.py"""
6
7from __future__ import annotations
8
9import abc
10import ast
11import itertools
12import operator
13import typing
14import warnings
15from collections.abc import Callable, Generator, Iterable, Iterator, Mapping
16from functools import cached_property
17from typing import TYPE_CHECKING, Any, ClassVar, Literal, Self, Union
18
19from astroid import decorators, protocols, util
20from astroid.bases import Instance, _infer_stmts
21from astroid.const import _EMPTY_OBJECT_MARKER, PY314_PLUS, Context
22from astroid.context import CallContext, InferenceContext, copy_context
23from astroid.exceptions import (
24 AstroidBuildingError,
25 AstroidError,
26 AstroidIndexError,
27 AstroidTypeError,
28 AstroidValueError,
29 AttributeInferenceError,
30 InferenceError,
31 NameInferenceError,
32 NoDefault,
33 ParentMissingError,
34 _NonDeducibleTypeHierarchy,
35)
36from astroid.interpreter import dunder_lookup
37from astroid.manager import AstroidManager
38from astroid.nodes import _base_nodes
39from astroid.nodes.const import OP_PRECEDENCE
40from astroid.nodes.node_ng import NodeNG
41from astroid.nodes.scoped_nodes import SYNTHETIC_ROOT
42from astroid.typing import (
43 ConstFactoryResult,
44 InferenceErrorInfo,
45 InferenceResult,
46 SuccessfulInferenceResult,
47)
48
49if TYPE_CHECKING:
50 from astroid import nodes
51 from astroid.nodes import LocalsDictNodeNG
52 from astroid.nodes.node_ng import FrameType
53
54
55def _is_const(value) -> bool:
56 return isinstance(value, tuple(CONST_CLS))
57
58
59_NodesT = typing.TypeVar("_NodesT", bound=NodeNG)
60_BadOpMessageT = typing.TypeVar("_BadOpMessageT", bound=util.BadOperationMessage)
61
62# pylint: disable-next=consider-alternative-union-syntax
63AssignedStmtsPossibleNode = Union["List", "Tuple", "AssignName", "AssignAttr", None]
64AssignedStmtsCall = Callable[
65 [
66 _NodesT,
67 AssignedStmtsPossibleNode,
68 InferenceContext | None,
69 list[int] | None,
70 ],
71 Any,
72]
73InferBinaryOperation = Callable[
74 [_NodesT, InferenceContext | None],
75 Generator[InferenceResult | _BadOpMessageT],
76]
77InferLHS = Callable[
78 [_NodesT, InferenceContext | None],
79 Generator[InferenceResult, None, InferenceErrorInfo | None],
80]
81InferUnaryOp = Callable[[_NodesT, str], ConstFactoryResult]
82
83
84@decorators.raise_if_nothing_inferred
85def unpack_infer(stmt, context: InferenceContext | None = None):
86 """recursively generate nodes inferred by the given statement.
87 If the inferred value is a list or a tuple, recurse on the elements
88 """
89 if isinstance(stmt, (List, Tuple)):
90 for elt in stmt.elts:
91 if elt is util.Uninferable:
92 yield elt
93 continue
94 yield from unpack_infer(elt, context)
95 return {"node": stmt, "context": context}
96 # if inferred is a final node, return it and stop
97 inferred = next(stmt.infer(context), util.Uninferable)
98 if inferred is stmt:
99 yield inferred
100 return {"node": stmt, "context": context}
101 # else, infer recursively, except Uninferable object that should be returned as is
102 for inferred in stmt.infer(context):
103 if isinstance(inferred, util.UninferableBase):
104 yield inferred
105 else:
106 yield from unpack_infer(inferred, context)
107
108 return {"node": stmt, "context": context}
109
110
111def are_exclusive(stmt1, stmt2, exceptions: list[str] | None = None) -> bool:
112 """return true if the two given statements are mutually exclusive
113
114 `exceptions` may be a list of exception names. If specified, discard If
115 branches and check one of the statement is in an exception handler catching
116 one of the given exceptions.
117
118 algorithm :
119 1) index stmt1's parents
120 2) climb among stmt2's parents until we find a common parent
121 3) if the common parent is a If or Try statement, look if nodes are
122 in exclusive branches
123 """
124 # index stmt1's parents
125 stmt1_parents = {}
126 children = {}
127 previous = stmt1
128 for node in stmt1.node_ancestors():
129 stmt1_parents[node] = 1
130 children[node] = previous
131 previous = node
132 # climb among stmt2's parents until we find a common parent
133 previous = stmt2
134 for node in stmt2.node_ancestors():
135 if node in stmt1_parents:
136 # if the common parent is a If or Try statement, look if
137 # nodes are in exclusive branches
138 if isinstance(node, If) and exceptions is None:
139 c2attr, c2node = node.locate_child(previous)
140 c1attr, c1node = node.locate_child(children[node])
141 if "test" in (c1attr, c2attr):
142 # If any node is `If.test`, then it must be inclusive with
143 # the other node (`If.body` and `If.orelse`)
144 return False
145 if c1attr != c2attr:
146 # different `If` branches (`If.body` and `If.orelse`)
147 return True
148 elif isinstance(node, Try):
149 c2attr, c2node = node.locate_child(previous)
150 c1attr, c1node = node.locate_child(children[node])
151 if c1node is not c2node:
152 first_in_body_caught_by_handlers = (
153 c2attr == "handlers"
154 and c1attr == "body"
155 and previous.catch(exceptions)
156 )
157 second_in_body_caught_by_handlers = (
158 c2attr == "body"
159 and c1attr == "handlers"
160 and children[node].catch(exceptions)
161 )
162 first_in_else_other_in_handlers = (
163 c2attr == "handlers" and c1attr == "orelse"
164 )
165 second_in_else_other_in_handlers = (
166 c2attr == "orelse" and c1attr == "handlers"
167 )
168 if any(
169 (
170 first_in_body_caught_by_handlers,
171 second_in_body_caught_by_handlers,
172 first_in_else_other_in_handlers,
173 second_in_else_other_in_handlers,
174 )
175 ):
176 return True
177 elif c2attr == "handlers" and c1attr == "handlers":
178 return previous is not children[node]
179 return False
180 previous = node
181 return False
182
183
184# getitem() helpers.
185
186_SLICE_SENTINEL = object()
187
188
189def _slice_value(index, context: InferenceContext | None = None):
190 """Get the value of the given slice index."""
191
192 if isinstance(index, Const):
193 if isinstance(index.value, (int, type(None))):
194 return index.value
195 elif index is None:
196 return None
197 else:
198 # Try to infer what the index actually is.
199 # Since we can't return all the possible values,
200 # we'll stop at the first possible value.
201 try:
202 inferred = next(index.infer(context=context))
203 except (InferenceError, StopIteration):
204 pass
205 else:
206 if isinstance(inferred, Const):
207 if isinstance(inferred.value, (int, type(None))):
208 return inferred.value
209
210 # Use a sentinel, because None can be a valid
211 # value that this function can return,
212 # as it is the case for unspecified bounds.
213 return _SLICE_SENTINEL
214
215
216def _infer_slice(node, context: InferenceContext | None = None):
217 lower = _slice_value(node.lower, context)
218 upper = _slice_value(node.upper, context)
219 step = _slice_value(node.step, context)
220 if all(elem is not _SLICE_SENTINEL for elem in (lower, upper, step)):
221 return slice(lower, upper, step)
222
223 raise AstroidTypeError(
224 message="Could not infer slice used in subscript",
225 node=node,
226 index=node.parent,
227 context=context,
228 )
229
230
231def _container_getitem(instance, elts, index, context: InferenceContext | None = None):
232 """Get a slice or an item, using the given *index*, for the given sequence."""
233 try:
234 if isinstance(index, Slice):
235 index_slice = _infer_slice(index, context=context)
236 new_cls = instance.__class__()
237 new_cls.elts = elts[index_slice]
238 new_cls.parent = instance.parent
239 return new_cls
240 if isinstance(index, Const):
241 return elts[index.value]
242 except ValueError as exc:
243 raise AstroidValueError(
244 message="Slice {index!r} cannot index container",
245 node=instance,
246 index=index,
247 context=context,
248 ) from exc
249 except IndexError as exc:
250 raise AstroidIndexError(
251 message="Index {index!s} out of range",
252 node=instance,
253 index=index,
254 context=context,
255 ) from exc
256 except TypeError as exc:
257 raise AstroidTypeError(
258 message="Type error {error!r}", node=instance, index=index, context=context
259 ) from exc
260
261 raise AstroidTypeError(f"Could not use {index} as subscript index")
262
263
264class BaseContainer(_base_nodes.ParentAssignNode, Instance, metaclass=abc.ABCMeta):
265 """Base class for Set, FrozenSet, Tuple and List."""
266
267 _astroid_fields = ("elts",)
268
269 def __init__(
270 self,
271 lineno: int | None,
272 col_offset: int | None,
273 parent: NodeNG | None,
274 *,
275 end_lineno: int | None,
276 end_col_offset: int | None,
277 ) -> None:
278 self.elts: list[SuccessfulInferenceResult] = []
279 """The elements in the node."""
280
281 super().__init__(
282 lineno=lineno,
283 col_offset=col_offset,
284 end_lineno=end_lineno,
285 end_col_offset=end_col_offset,
286 parent=parent,
287 )
288
289 def postinit(self, elts: list[SuccessfulInferenceResult]) -> None:
290 self.elts = elts
291
292 @classmethod
293 def from_elements(cls, elts: Iterable[Any]) -> Self:
294 """Create a node of this type from the given list of elements.
295
296 :param elts: The list of elements that the node should contain.
297
298 :returns: A new node containing the given elements.
299 """
300 node = cls(
301 lineno=None,
302 col_offset=None,
303 parent=None,
304 end_lineno=None,
305 end_col_offset=None,
306 )
307 node.elts = [const_factory(e) if _is_const(e) else e for e in elts]
308 return node
309
310 def itered(self) -> list[SuccessfulInferenceResult]:
311 """An iterator over the elements this node contains.
312
313 :returns: The contents of this node.
314 """
315 return self.elts
316
317 def bool_value(self, context: InferenceContext | None = None) -> bool:
318 """Determine the boolean value of this node.
319
320 :returns: The boolean value of this node.
321 """
322 return bool(self.elts)
323
324 @abc.abstractmethod
325 def pytype(self) -> str:
326 """Get the name of the type that this node represents.
327
328 :returns: The name of the type.
329 """
330
331 def get_children(self):
332 yield from self.elts
333
334 @decorators.raise_if_nothing_inferred
335 def _infer(self, context: InferenceContext | None = None) -> Iterator[Self]:
336 has_starred_named_expr = any(
337 isinstance(e, (Starred, NamedExpr)) for e in self.elts
338 )
339 if has_starred_named_expr:
340 values = self._infer_sequence_helper(context)
341 new_seq = type(self)(
342 lineno=self.lineno,
343 col_offset=self.col_offset,
344 parent=self.parent,
345 end_lineno=self.end_lineno,
346 end_col_offset=self.end_col_offset,
347 )
348 new_seq.postinit(values)
349
350 yield new_seq
351 else:
352 yield self
353
354 def _infer_sequence_helper(
355 self, context: InferenceContext | None = None
356 ) -> list[SuccessfulInferenceResult]:
357 """Infer all values based on BaseContainer.elts."""
358 values = []
359
360 for elt in self.elts:
361 if isinstance(elt, Starred):
362 starred = util.safe_infer(elt.value, context)
363 if not starred:
364 raise InferenceError(node=self, context=context)
365 if isinstance(starred, TypeVarTuple):
366 # TypeVarTuple unpacking (*Ts) represents a variadic
367 # type parameter, not an iterable to expand.
368 values.append(elt)
369 elif not hasattr(starred, "elts"):
370 raise InferenceError(node=self, context=context)
371 else:
372 # TODO: fresh context?
373 values.extend(starred._infer_sequence_helper(context))
374 elif isinstance(elt, NamedExpr):
375 value = util.safe_infer(elt.value, context)
376 if not value:
377 raise InferenceError(node=self, context=context)
378 values.append(value)
379 else:
380 values.append(elt)
381 return values
382
383
384# Name classes
385
386
387class AssignName(
388 _base_nodes.NoChildrenNode,
389 _base_nodes.LookupMixIn,
390 _base_nodes.ParentAssignNode,
391):
392 """Variation of :class:`ast.Assign` representing assignment to a name.
393
394 An :class:`AssignName` is the name of something that is assigned to.
395 This includes variables defined in a function signature or in a loop.
396
397 >>> import astroid
398 >>> node = astroid.extract_node('variable = range(10)')
399 >>> node
400 <Assign l.1 at 0x...>
401 >>> list(node.get_children())
402 [<AssignName.variable l.1 at 0x...>, <Call l.1 at 0x...>]
403 >>> list(node.get_children())[0].as_string()
404 'variable'
405 """
406
407 _other_fields = ("name",)
408
409 def __init__(
410 self,
411 name: str,
412 lineno: int,
413 col_offset: int,
414 parent: NodeNG,
415 *,
416 end_lineno: int | None,
417 end_col_offset: int | None,
418 ) -> None:
419 self.name = name
420 """The name that is assigned to."""
421
422 super().__init__(
423 lineno=lineno,
424 col_offset=col_offset,
425 end_lineno=end_lineno,
426 end_col_offset=end_col_offset,
427 parent=parent,
428 )
429
430 assigned_stmts = protocols.assend_assigned_stmts
431 """Returns the assigned statement (non inferred) according to the assignment type.
432 See astroid/protocols.py for actual implementation.
433 """
434
435 @decorators.raise_if_nothing_inferred
436 @decorators.path_wrapper
437 def _infer(
438 self, context: InferenceContext | None = None
439 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
440 """Infer an AssignName: need to inspect the RHS part of the
441 assign node.
442 """
443 if isinstance(self.parent, AugAssign):
444 return self.parent.infer(context)
445
446 stmts = list(self.assigned_stmts(context=context))
447 return _infer_stmts(stmts, context)
448
449 @decorators.raise_if_nothing_inferred
450 def infer_lhs(
451 self, context: InferenceContext | None = None
452 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
453 """Infer a Name: use name lookup rules.
454
455 Same implementation as Name._infer."""
456 # pylint: disable=import-outside-toplevel
457 from astroid.constraint import get_constraints
458 from astroid.helpers import _higher_function_scope
459
460 frame, stmts = self.lookup(self.name)
461 if not stmts:
462 # Try to see if the name is enclosed in a nested function
463 # and use the higher (first function) scope for searching.
464 parent_function = _higher_function_scope(self.scope())
465 if parent_function:
466 _, stmts = parent_function.lookup(self.name)
467
468 if not stmts:
469 raise NameInferenceError(
470 name=self.name, scope=self.scope(), context=context
471 )
472 context = copy_context(context)
473 context.lookupname = self.name
474 context.constraints[self.name] = get_constraints(self, frame)
475
476 return _infer_stmts(stmts, context, frame)
477
478
479class DelName(
480 _base_nodes.NoChildrenNode, _base_nodes.LookupMixIn, _base_nodes.ParentAssignNode
481):
482 """Variation of :class:`ast.Delete` representing deletion of a name.
483
484 A :class:`DelName` is the name of something that is deleted.
485
486 >>> import astroid
487 >>> node = astroid.extract_node("del variable #@")
488 >>> list(node.get_children())
489 [<DelName.variable l.1 at 0x...>]
490 >>> list(node.get_children())[0].as_string()
491 'variable'
492 """
493
494 _other_fields = ("name",)
495
496 def __init__(
497 self,
498 name: str,
499 lineno: int,
500 col_offset: int,
501 parent: NodeNG,
502 *,
503 end_lineno: int | None,
504 end_col_offset: int | None,
505 ) -> None:
506 self.name = name
507 """The name that is being deleted."""
508
509 super().__init__(
510 lineno=lineno,
511 col_offset=col_offset,
512 end_lineno=end_lineno,
513 end_col_offset=end_col_offset,
514 parent=parent,
515 )
516
517
518class Name(_base_nodes.LookupMixIn, _base_nodes.NoChildrenNode):
519 """Class representing an :class:`ast.Name` node.
520
521 A :class:`Name` node is something that is named, but not covered by
522 :class:`AssignName` or :class:`DelName`.
523
524 >>> import astroid
525 >>> node = astroid.extract_node('range(10)')
526 >>> node
527 <Call l.1 at 0x...>
528 >>> list(node.get_children())
529 [<Name.range l.1 at 0x...>, <Const.int l.1 at 0x...>]
530 >>> list(node.get_children())[0].as_string()
531 'range'
532 """
533
534 _other_fields = ("name",)
535
536 def __init__(
537 self,
538 name: str,
539 lineno: int,
540 col_offset: int,
541 parent: NodeNG,
542 *,
543 end_lineno: int | None,
544 end_col_offset: int | None,
545 ) -> None:
546 self.name = name
547 """The name that this node refers to."""
548
549 super().__init__(
550 lineno=lineno,
551 col_offset=col_offset,
552 end_lineno=end_lineno,
553 end_col_offset=end_col_offset,
554 parent=parent,
555 )
556
557 def _get_name_nodes(self):
558 yield self
559
560 for child_node in self.get_children():
561 yield from child_node._get_name_nodes()
562
563 @decorators.raise_if_nothing_inferred
564 @decorators.path_wrapper
565 def _infer(
566 self, context: InferenceContext | None = None
567 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
568 """Infer a Name: use name lookup rules
569
570 Same implementation as AssignName._infer_lhs."""
571 # pylint: disable=import-outside-toplevel
572 from astroid.constraint import get_constraints
573 from astroid.helpers import _higher_function_scope
574
575 frame, stmts = self.lookup(self.name)
576 if not stmts:
577 # Try to see if the name is enclosed in a nested function
578 # and use the higher (first function) scope for searching.
579 parent_function = _higher_function_scope(self.scope())
580 if parent_function:
581 _, stmts = parent_function.lookup(self.name)
582
583 if not stmts:
584 raise NameInferenceError(
585 name=self.name, scope=self.scope(), context=context
586 )
587 context = copy_context(context)
588 context.lookupname = self.name
589 context.constraints[self.name] = get_constraints(self, frame)
590
591 return _infer_stmts(stmts, context, frame)
592
593
594class Arguments(
595 _base_nodes.AssignTypeNode
596): # pylint: disable=too-many-instance-attributes
597 """Class representing an :class:`ast.arguments` node.
598
599 An :class:`Arguments` node represents that arguments in a
600 function definition.
601
602 >>> import astroid
603 >>> node = astroid.extract_node('def foo(bar): pass')
604 >>> node
605 <FunctionDef.foo l.1 at 0x...>
606 >>> node.args
607 <Arguments l.1 at 0x...>
608 """
609
610 # In the ast module, each argument is a new class, _ast.arg, which
611 # exposes an 'annotation' attribute. In astroid though, arguments are
612 # exposed as is in the Arguments node, so annotations are exposed
613 # separately:
614 # - we expose 'varargannotation' and 'kwargannotation' for the
615 # annotations of varargs and kwargs.
616 # - we expose 'annotations', a list with annotations for
617 # each normal argument. If an argument doesn't have an
618 # annotation, its value will be None.
619 _astroid_fields = (
620 "args",
621 "defaults",
622 "kwonlyargs",
623 "posonlyargs",
624 "posonlyargs_annotations",
625 "kw_defaults",
626 "annotations",
627 "varargannotation",
628 "kwargannotation",
629 "kwonlyargs_annotations",
630 "type_comment_args",
631 "type_comment_kwonlyargs",
632 "type_comment_posonlyargs",
633 )
634
635 _other_fields = ("vararg", "kwarg")
636
637 args: list[AssignName] | None
638 """The names of the required arguments.
639
640 Can be None if the associated function does not have a retrievable
641 signature and the arguments are therefore unknown.
642 This can happen with (builtin) functions implemented in C that have
643 incomplete signature information.
644 """
645
646 defaults: list[NodeNG] | None
647 """The default values for arguments that can be passed positionally."""
648
649 kwonlyargs: list[AssignName]
650 """The keyword arguments that cannot be passed positionally."""
651
652 posonlyargs: list[AssignName]
653 """The arguments that can only be passed positionally."""
654
655 kw_defaults: list[NodeNG | None] | None
656 """The default values for keyword arguments that cannot be passed positionally."""
657
658 annotations: list[NodeNG | None]
659 """The type annotations of arguments that can be passed positionally."""
660
661 posonlyargs_annotations: list[NodeNG | None]
662 """The type annotations of arguments that can only be passed positionally."""
663
664 kwonlyargs_annotations: list[NodeNG | None]
665 """The type annotations of arguments that cannot be passed positionally."""
666
667 type_comment_args: list[NodeNG | None]
668 """The type annotation, passed by a type comment, of each argument.
669
670 If an argument does not have a type comment,
671 the value for that argument will be None.
672 """
673
674 type_comment_kwonlyargs: list[NodeNG | None]
675 """The type annotation, passed by a type comment, of each keyword only argument.
676
677 If an argument does not have a type comment,
678 the value for that argument will be None.
679 """
680
681 type_comment_posonlyargs: list[NodeNG | None]
682 """The type annotation, passed by a type comment, of each positional argument.
683
684 If an argument does not have a type comment,
685 the value for that argument will be None.
686 """
687
688 varargannotation: NodeNG | None
689 """The type annotation for the variable length arguments."""
690
691 kwargannotation: NodeNG | None
692 """The type annotation for the variable length keyword arguments."""
693
694 vararg_node: AssignName | None
695 """The node for variable length arguments"""
696
697 kwarg_node: AssignName | None
698 """The node for variable keyword arguments"""
699
700 def __init__(
701 self,
702 vararg: str | None,
703 kwarg: str | None,
704 parent: NodeNG,
705 vararg_node: AssignName | None = None,
706 kwarg_node: AssignName | None = None,
707 ) -> None:
708 """Almost all attributes can be None for living objects where introspection failed."""
709 super().__init__(
710 parent=parent,
711 lineno=None,
712 col_offset=None,
713 end_lineno=None,
714 end_col_offset=None,
715 )
716
717 self.vararg = vararg
718 """The name of the variable length arguments."""
719
720 self.kwarg = kwarg
721 """The name of the variable length keyword arguments."""
722
723 self.vararg_node = vararg_node
724 self.kwarg_node = kwarg_node
725
726 # pylint: disable=too-many-arguments, too-many-positional-arguments
727 def postinit(
728 self,
729 args: list[AssignName] | None,
730 defaults: list[NodeNG] | None,
731 kwonlyargs: list[AssignName],
732 kw_defaults: list[NodeNG | None] | None,
733 annotations: list[NodeNG | None],
734 posonlyargs: list[AssignName],
735 kwonlyargs_annotations: list[NodeNG | None],
736 posonlyargs_annotations: list[NodeNG | None],
737 varargannotation: NodeNG | None = None,
738 kwargannotation: NodeNG | None = None,
739 type_comment_args: list[NodeNG | None] | None = None,
740 type_comment_kwonlyargs: list[NodeNG | None] | None = None,
741 type_comment_posonlyargs: list[NodeNG | None] | None = None,
742 ) -> None:
743 self.args = args
744 self.defaults = defaults
745 self.kwonlyargs = kwonlyargs
746 self.posonlyargs = posonlyargs
747 self.kw_defaults = kw_defaults
748 self.annotations = annotations
749 self.kwonlyargs_annotations = kwonlyargs_annotations
750 self.posonlyargs_annotations = posonlyargs_annotations
751
752 # Parameters that got added later and need a default
753 self.varargannotation = varargannotation
754 self.kwargannotation = kwargannotation
755 if type_comment_args is None:
756 type_comment_args = []
757 self.type_comment_args = type_comment_args
758 if type_comment_kwonlyargs is None:
759 type_comment_kwonlyargs = []
760 self.type_comment_kwonlyargs = type_comment_kwonlyargs
761 if type_comment_posonlyargs is None:
762 type_comment_posonlyargs = []
763 self.type_comment_posonlyargs = type_comment_posonlyargs
764
765 assigned_stmts = protocols.arguments_assigned_stmts
766 """Returns the assigned statement (non inferred) according to the assignment type.
767 See astroid/protocols.py for actual implementation.
768 """
769
770 def _infer_name(self, frame, name):
771 if self.parent is frame:
772 return name
773 return None
774
775 @cached_property
776 def fromlineno(self) -> int:
777 """The first line that this node appears on in the source code.
778
779 Can also return 0 if the line can not be determined.
780 """
781 lineno = super().fromlineno
782 return max(lineno, self.parent.fromlineno or 0)
783
784 @cached_property
785 def arguments(self):
786 """Get all the arguments for this node. This includes:
787
788 * Positional only arguments
789 * Positional arguments
790 * Keyword arguments
791 * Variable arguments (e.g. ``*args``)
792 * Variable keyword arguments (e.g. ``**kwargs``)
793 """
794 retval = list(itertools.chain((self.posonlyargs or ()), (self.args or ())))
795 if self.vararg_node:
796 retval.append(self.vararg_node)
797 retval += self.kwonlyargs or ()
798 if self.kwarg_node:
799 retval.append(self.kwarg_node)
800
801 return retval
802
803 def format_args(self, *, skippable_names: set[str] | None = None) -> str:
804 """Get the arguments formatted as string.
805
806 :returns: The formatted arguments.
807 """
808 result = []
809 positional_only_defaults = []
810 positional_or_keyword_defaults = self.defaults
811 if self.defaults:
812 args = self.args or []
813 positional_or_keyword_defaults = self.defaults[-len(args) :]
814 positional_only_defaults = self.defaults[: len(self.defaults) - len(args)]
815
816 if self.posonlyargs:
817 result.append(
818 _format_args(
819 self.posonlyargs,
820 positional_only_defaults,
821 self.posonlyargs_annotations,
822 skippable_names=skippable_names,
823 )
824 )
825 result.append("/")
826 if self.args:
827 result.append(
828 _format_args(
829 self.args,
830 positional_or_keyword_defaults,
831 getattr(self, "annotations", None),
832 skippable_names=skippable_names,
833 )
834 )
835 if self.vararg:
836 result.append(f"*{self.vararg}")
837 if self.kwonlyargs:
838 if not self.vararg:
839 result.append("*")
840 result.append(
841 _format_args(
842 self.kwonlyargs,
843 self.kw_defaults,
844 self.kwonlyargs_annotations,
845 skippable_names=skippable_names,
846 )
847 )
848 if self.kwarg:
849 result.append(f"**{self.kwarg}")
850 return ", ".join(result)
851
852 def _get_arguments_data(
853 self,
854 ) -> tuple[
855 dict[str, tuple[str | None, str | None]],
856 dict[str, tuple[str | None, str | None]],
857 ]:
858 """Get the arguments as dictionary with information about typing and defaults.
859
860 The return tuple contains a dictionary for positional and keyword arguments with their typing
861 and their default value, if any.
862 The method follows a similar order as format_args but instead of formatting into a string it
863 returns the data that is used to do so.
864 """
865 pos_only: dict[str, tuple[str | None, str | None]] = {}
866 kw_only: dict[str, tuple[str | None, str | None]] = {}
867
868 # Setup and match defaults with arguments
869 positional_only_defaults = []
870 positional_or_keyword_defaults = self.defaults
871 if self.defaults:
872 args = self.args or []
873 positional_or_keyword_defaults = self.defaults[-len(args) :]
874 positional_only_defaults = self.defaults[: len(self.defaults) - len(args)]
875
876 for index, posonly in enumerate(self.posonlyargs):
877 annotation, default = self.posonlyargs_annotations[index], None
878 if annotation is not None:
879 annotation = annotation.as_string()
880 if positional_only_defaults:
881 default = positional_only_defaults[index].as_string()
882 pos_only[posonly.name] = (annotation, default)
883
884 for index, arg in enumerate(self.args):
885 annotation, default = self.annotations[index], None
886 if annotation is not None:
887 annotation = annotation.as_string()
888 if positional_or_keyword_defaults:
889 defaults_offset = len(self.args) - len(positional_or_keyword_defaults)
890 default_index = index - defaults_offset
891 if (
892 default_index > -1
893 and positional_or_keyword_defaults[default_index] is not None
894 ):
895 default = positional_or_keyword_defaults[default_index].as_string()
896 pos_only[arg.name] = (annotation, default)
897
898 if self.vararg:
899 annotation = self.varargannotation
900 if annotation is not None:
901 annotation = annotation.as_string()
902 pos_only[self.vararg] = (annotation, None)
903
904 for index, kwarg in enumerate(self.kwonlyargs):
905 annotation = self.kwonlyargs_annotations[index]
906 if annotation is not None:
907 annotation = annotation.as_string()
908 default = self.kw_defaults[index]
909 if default is not None:
910 default = default.as_string()
911 kw_only[kwarg.name] = (annotation, default)
912
913 if self.kwarg:
914 annotation = self.kwargannotation
915 if annotation is not None:
916 annotation = annotation.as_string()
917 kw_only[self.kwarg] = (annotation, None)
918
919 return pos_only, kw_only
920
921 def default_value(self, argname: str) -> NodeNG:
922 """Get the default value for an argument.
923
924 :param argname: The name of the argument to get the default value for.
925
926 :raises NoDefault: If there is no default value defined for the
927 given argument.
928 """
929 index = _find_arg(argname, self.kwonlyargs)[0]
930 if (index is not None) and (len(self.kw_defaults) > index):
931 kw_default = self.kw_defaults[index]
932 if kw_default is not None:
933 return kw_default
934 raise NoDefault(func=self.parent, name=argname)
935
936 positional = [*(self.posonlyargs or ()), *(self.args or ())]
937 index = _find_arg(argname, positional)[0]
938 if index is not None:
939 # ``defaults`` covers the last positional arguments.
940 idx = index - (len(positional) - len(self.defaults))
941 if idx >= 0:
942 return self.defaults[idx]
943
944 raise NoDefault(func=self.parent, name=argname)
945
946 def is_argument(self, name: str) -> bool:
947 """Check if the given name is defined in the arguments.
948
949 :param name: The name to check for.
950
951 :returns: Whether the given name is defined in the arguments,
952 """
953 if name == self.vararg:
954 return True
955 if name == self.kwarg:
956 return True
957 return self.find_argname(name)[1] is not None
958
959 def find_argname(self, argname: str) -> tuple[int | None, AssignName | None]:
960 """Get the index and :class:`AssignName` node for given name.
961
962 :param argname: The name of the argument to search for.
963
964 :returns: The index and node for the argument.
965 """
966 if self.arguments:
967 index, argument = _find_arg(argname, self.arguments)
968 if argument:
969 return index, argument
970 return None, None
971
972 def get_children(self):
973 yield from self.posonlyargs or ()
974
975 for elt in self.posonlyargs_annotations:
976 if elt is not None:
977 yield elt
978
979 yield from self.args or ()
980
981 if self.defaults is not None:
982 yield from self.defaults
983 yield from self.kwonlyargs
984
985 for elt in self.kw_defaults or ():
986 if elt is not None:
987 yield elt
988
989 for elt in self.annotations:
990 if elt is not None:
991 yield elt
992
993 if self.varargannotation is not None:
994 yield self.varargannotation
995
996 if self.kwargannotation is not None:
997 yield self.kwargannotation
998
999 for elt in self.kwonlyargs_annotations:
1000 if elt is not None:
1001 yield elt
1002
1003 def get_annotations(self) -> Iterator[nodes.NodeNG]:
1004 """Iterate over all annotations nodes."""
1005 for elt in self.posonlyargs_annotations:
1006 if elt is not None:
1007 yield elt
1008 for elt in self.annotations:
1009 if elt is not None:
1010 yield elt
1011 if self.varargannotation is not None:
1012 yield self.varargannotation
1013
1014 for elt in self.kwonlyargs_annotations:
1015 if elt is not None:
1016 yield elt
1017 if self.kwargannotation is not None:
1018 yield self.kwargannotation
1019
1020 @decorators.raise_if_nothing_inferred
1021 def _infer(
1022 self, context: InferenceContext | None = None
1023 ) -> Generator[InferenceResult]:
1024 # pylint: disable-next=import-outside-toplevel
1025 from astroid.protocols import _arguments_infer_argname
1026
1027 if context is None or context.lookupname is None:
1028 raise InferenceError(node=self, context=context)
1029 return _arguments_infer_argname(self, context.lookupname, context)
1030
1031
1032def _find_arg(argname, args):
1033 for i, arg in enumerate(args):
1034 if arg.name == argname:
1035 return i, arg
1036 return None, None
1037
1038
1039def _format_args(
1040 args, defaults=None, annotations=None, skippable_names: set[str] | None = None
1041) -> str:
1042 if skippable_names is None:
1043 skippable_names = set()
1044 values = []
1045 if args is None:
1046 return ""
1047 if annotations is None:
1048 annotations = []
1049 if defaults is not None:
1050 default_offset = len(args) - len(defaults)
1051 else:
1052 default_offset = None
1053 packed = itertools.zip_longest(args, annotations)
1054 for i, (arg, annotation) in enumerate(packed):
1055 if arg.name in skippable_names:
1056 continue
1057 if isinstance(arg, Tuple):
1058 values.append(f"({_format_args(arg.elts)})")
1059 else:
1060 argname = arg.name
1061 default_sep = "="
1062 if annotation is not None:
1063 argname += ": " + annotation.as_string()
1064 default_sep = " = "
1065 values.append(argname)
1066
1067 if default_offset is not None and i >= default_offset:
1068 if defaults[i - default_offset] is not None:
1069 values[-1] += default_sep + defaults[i - default_offset].as_string()
1070 return ", ".join(values)
1071
1072
1073def _infer_attribute(
1074 node: nodes.AssignAttr | nodes.Attribute, context: InferenceContext | None = None
1075) -> Generator[InferenceResult, None, InferenceErrorInfo]:
1076 """Infer an AssignAttr/Attribute node by using getattr on the associated object."""
1077 # pylint: disable=import-outside-toplevel
1078 from astroid.constraint import get_constraints
1079 from astroid.nodes import ClassDef
1080
1081 for owner in node.expr.infer(context):
1082 if isinstance(owner, util.UninferableBase):
1083 yield owner
1084 continue
1085
1086 context = copy_context(context)
1087 old_boundnode = context.boundnode
1088 try:
1089 context.boundnode = owner
1090 if isinstance(owner, (ClassDef, Instance)):
1091 frame = owner if isinstance(owner, ClassDef) else owner._proxied
1092 context.constraints[node.attrname] = get_constraints(node, frame=frame)
1093 if node.attrname == "argv" and owner.name == "sys":
1094 # sys.argv will never be inferable during static analysis
1095 # It's value would be the args passed to the linter itself
1096 yield util.Uninferable
1097 else:
1098 yield from owner.igetattr(node.attrname, context)
1099 except (
1100 AttributeInferenceError,
1101 InferenceError,
1102 AttributeError,
1103 ):
1104 pass
1105 finally:
1106 context.boundnode = old_boundnode
1107 return InferenceErrorInfo(node=node, context=context)
1108
1109
1110class AssignAttr(_base_nodes.LookupMixIn, _base_nodes.ParentAssignNode):
1111 """Variation of :class:`ast.Assign` representing assignment to an attribute.
1112
1113 >>> import astroid
1114 >>> node = astroid.extract_node('self.attribute = range(10)')
1115 >>> node
1116 <Assign l.1 at 0x...>
1117 >>> list(node.get_children())
1118 [<AssignAttr.attribute l.1 at 0x...>, <Call l.1 at 0x...>]
1119 >>> list(node.get_children())[0].as_string()
1120 'self.attribute'
1121 """
1122
1123 expr: NodeNG
1124
1125 _astroid_fields = ("expr",)
1126 _other_fields = ("attrname",)
1127
1128 def __init__(
1129 self,
1130 attrname: str,
1131 lineno: int,
1132 col_offset: int,
1133 parent: NodeNG,
1134 *,
1135 end_lineno: int | None,
1136 end_col_offset: int | None,
1137 ) -> None:
1138 self.attrname = attrname
1139 """The name of the attribute being assigned to."""
1140
1141 super().__init__(
1142 lineno=lineno,
1143 col_offset=col_offset,
1144 end_lineno=end_lineno,
1145 end_col_offset=end_col_offset,
1146 parent=parent,
1147 )
1148
1149 def postinit(self, expr: NodeNG) -> None:
1150 self.expr = expr
1151
1152 assigned_stmts = protocols.assend_assigned_stmts
1153 """Returns the assigned statement (non inferred) according to the assignment type.
1154 See astroid/protocols.py for actual implementation.
1155 """
1156
1157 def get_children(self):
1158 yield self.expr
1159
1160 @decorators.raise_if_nothing_inferred
1161 @decorators.path_wrapper
1162 def _infer(
1163 self, context: InferenceContext | None = None
1164 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
1165 """Infer an AssignAttr: need to inspect the RHS part of the
1166 assign node.
1167 """
1168 if isinstance(self.parent, AugAssign):
1169 return self.parent.infer(context)
1170
1171 stmts = list(self.assigned_stmts(context=context))
1172 return _infer_stmts(stmts, context)
1173
1174 @decorators.raise_if_nothing_inferred
1175 @decorators.path_wrapper
1176 def infer_lhs(
1177 self, context: InferenceContext | None = None
1178 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
1179 return _infer_attribute(self, context)
1180
1181
1182class Assert(_base_nodes.Statement):
1183 """Class representing an :class:`ast.Assert` node.
1184
1185 An :class:`Assert` node represents an assert statement.
1186
1187 >>> import astroid
1188 >>> node = astroid.extract_node('assert len(things) == 10, "Not enough things"')
1189 >>> node
1190 <Assert l.1 at 0x...>
1191 """
1192
1193 _astroid_fields = ("test", "fail")
1194
1195 test: NodeNG
1196 """The test that passes or fails the assertion."""
1197
1198 fail: NodeNG | None
1199 """The message shown when the assertion fails."""
1200
1201 def postinit(self, test: NodeNG, fail: NodeNG | None) -> None:
1202 self.fail = fail
1203 self.test = test
1204
1205 def get_children(self):
1206 yield self.test
1207
1208 if self.fail is not None:
1209 yield self.fail
1210
1211
1212class Assign(_base_nodes.AssignTypeNode, _base_nodes.Statement):
1213 """Class representing an :class:`ast.Assign` node.
1214
1215 An :class:`Assign` is a statement where something is explicitly
1216 assigned to.
1217
1218 >>> import astroid
1219 >>> node = astroid.extract_node('variable = range(10)')
1220 >>> node
1221 <Assign l.1 at 0x...>
1222 """
1223
1224 targets: list[NodeNG]
1225 """What is being assigned to."""
1226
1227 value: NodeNG
1228 """The value being assigned to the variables."""
1229
1230 type_annotation: NodeNG | None
1231 """If present, this will contain the type annotation passed by a type comment"""
1232
1233 _astroid_fields = ("targets", "value")
1234 _other_other_fields = ("type_annotation",)
1235
1236 def postinit(
1237 self,
1238 targets: list[NodeNG],
1239 value: NodeNG,
1240 type_annotation: NodeNG | None,
1241 ) -> None:
1242 self.targets = targets
1243 self.value = value
1244 self.type_annotation = type_annotation
1245
1246 assigned_stmts = protocols.assign_assigned_stmts
1247 """Returns the assigned statement (non inferred) according to the assignment type.
1248 See astroid/protocols.py for actual implementation.
1249 """
1250
1251 def get_children(self):
1252 yield from self.targets
1253
1254 yield self.value
1255
1256 @cached_property
1257 def _assign_nodes_in_scope(self) -> list[nodes.Assign]:
1258 return [self, *self.value._assign_nodes_in_scope]
1259
1260 def _get_yield_nodes_skip_functions(self):
1261 yield from self.value._get_yield_nodes_skip_functions()
1262
1263 def _get_yield_nodes_skip_lambdas(self):
1264 yield from self.value._get_yield_nodes_skip_lambdas()
1265
1266
1267class AnnAssign(_base_nodes.AssignTypeNode, _base_nodes.Statement):
1268 """Class representing an :class:`ast.AnnAssign` node.
1269
1270 An :class:`AnnAssign` is an assignment with a type annotation.
1271
1272 >>> import astroid
1273 >>> node = astroid.extract_node('variable: List[int] = range(10)')
1274 >>> node
1275 <AnnAssign l.1 at 0x...>
1276 """
1277
1278 _astroid_fields = ("target", "annotation", "value")
1279 _other_fields = ("simple",)
1280
1281 target: Name | Attribute | Subscript
1282 """What is being assigned to."""
1283
1284 annotation: NodeNG
1285 """The type annotation of what is being assigned to."""
1286
1287 value: NodeNG | None
1288 """The value being assigned to the variables."""
1289
1290 simple: int
1291 """Whether :attr:`target` is a pure name or a complex statement."""
1292
1293 def postinit(
1294 self,
1295 target: Name | Attribute | Subscript,
1296 annotation: NodeNG,
1297 simple: int,
1298 value: NodeNG | None,
1299 ) -> None:
1300 self.target = target
1301 self.annotation = annotation
1302 self.value = value
1303 self.simple = simple
1304
1305 assigned_stmts = protocols.assign_annassigned_stmts
1306 """Returns the assigned statement (non inferred) according to the assignment type.
1307 See astroid/protocols.py for actual implementation.
1308 """
1309
1310 def get_children(self):
1311 yield self.target
1312 yield self.annotation
1313
1314 if self.value is not None:
1315 yield self.value
1316
1317
1318class AugAssign(
1319 _base_nodes.AssignTypeNode, _base_nodes.OperatorNode, _base_nodes.Statement
1320):
1321 """Class representing an :class:`ast.AugAssign` node.
1322
1323 An :class:`AugAssign` is an assignment paired with an operator.
1324
1325 >>> import astroid
1326 >>> node = astroid.extract_node('variable += 1')
1327 >>> node
1328 <AugAssign l.1 at 0x...>
1329 """
1330
1331 _astroid_fields = ("target", "value")
1332 _other_fields = ("op",)
1333
1334 target: Name | Attribute | Subscript
1335 """What is being assigned to."""
1336
1337 value: NodeNG
1338 """The value being assigned to the variable."""
1339
1340 def __init__(
1341 self,
1342 op: str,
1343 lineno: int,
1344 col_offset: int,
1345 parent: NodeNG,
1346 *,
1347 end_lineno: int | None,
1348 end_col_offset: int | None,
1349 ) -> None:
1350 self.op = op
1351 """The operator that is being combined with the assignment.
1352
1353 This includes the equals sign.
1354 """
1355
1356 super().__init__(
1357 lineno=lineno,
1358 col_offset=col_offset,
1359 end_lineno=end_lineno,
1360 end_col_offset=end_col_offset,
1361 parent=parent,
1362 )
1363
1364 def postinit(self, target: Name | Attribute | Subscript, value: NodeNG) -> None:
1365 self.target = target
1366 self.value = value
1367
1368 assigned_stmts = protocols.assign_assigned_stmts
1369 """Returns the assigned statement (non inferred) according to the assignment type.
1370 See astroid/protocols.py for actual implementation.
1371 """
1372
1373 def type_errors(
1374 self, context: InferenceContext | None = None
1375 ) -> list[util.BadBinaryOperationMessage]:
1376 """Get a list of type errors which can occur during inference.
1377
1378 Each TypeError is represented by a :class:`~astroid.util.BadBinaryOperationMessage`,
1379 which holds the original exception.
1380
1381 If any inferred result is uninferable, an empty list is returned.
1382 """
1383 bad = []
1384 try:
1385 for result in self._infer_augassign(context=context):
1386 if result is util.Uninferable:
1387 raise InferenceError
1388 if isinstance(result, util.BadBinaryOperationMessage):
1389 bad.append(result)
1390 except InferenceError:
1391 return []
1392 return bad
1393
1394 def get_children(self):
1395 yield self.target
1396 yield self.value
1397
1398 def _get_yield_nodes_skip_functions(self):
1399 """An AugAssign node can contain a Yield node in the value"""
1400 yield from self.value._get_yield_nodes_skip_functions()
1401 yield from super()._get_yield_nodes_skip_functions()
1402
1403 def _get_yield_nodes_skip_lambdas(self):
1404 """An AugAssign node can contain a Yield node in the value"""
1405 yield from self.value._get_yield_nodes_skip_lambdas()
1406 yield from super()._get_yield_nodes_skip_lambdas()
1407
1408 def _infer_augassign(
1409 self, context: InferenceContext | None = None
1410 ) -> Generator[InferenceResult | util.BadBinaryOperationMessage]:
1411 """Inference logic for augmented binary operations."""
1412 context = context or InferenceContext()
1413
1414 rhs_context = context.clone()
1415
1416 lhs_iter = self.target.infer_lhs(context=context)
1417 rhs_iter = self.value.infer(context=rhs_context)
1418
1419 for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
1420 if any(isinstance(value, util.UninferableBase) for value in (rhs, lhs)):
1421 # Don't know how to process this.
1422 yield util.Uninferable
1423 return
1424
1425 try:
1426 yield from self._infer_binary_operation(
1427 left=lhs,
1428 right=rhs,
1429 binary_opnode=self,
1430 context=context,
1431 flow_factory=self._get_aug_flow,
1432 )
1433 except _NonDeducibleTypeHierarchy:
1434 yield util.Uninferable
1435
1436 @decorators.raise_if_nothing_inferred
1437 @decorators.path_wrapper
1438 def _infer(
1439 self, context: InferenceContext | None = None
1440 ) -> Generator[InferenceResult]:
1441 return self._filter_operation_errors(
1442 self._infer_augassign, context, util.BadBinaryOperationMessage
1443 )
1444
1445
1446class BinOp(_base_nodes.OperatorNode):
1447 """Class representing an :class:`ast.BinOp` node.
1448
1449 A :class:`BinOp` node is an application of a binary operator.
1450
1451 >>> import astroid
1452 >>> node = astroid.extract_node('a + b')
1453 >>> node
1454 <BinOp l.1 at 0x...>
1455 """
1456
1457 _astroid_fields = ("left", "right")
1458 _other_fields = ("op",)
1459
1460 left: NodeNG
1461 """What is being applied to the operator on the left side."""
1462
1463 right: NodeNG
1464 """What is being applied to the operator on the right side."""
1465
1466 def __init__(
1467 self,
1468 op: str,
1469 lineno: int,
1470 col_offset: int,
1471 parent: NodeNG,
1472 *,
1473 end_lineno: int | None,
1474 end_col_offset: int | None,
1475 ) -> None:
1476 self.op = op
1477 """The operator."""
1478
1479 super().__init__(
1480 lineno=lineno,
1481 col_offset=col_offset,
1482 end_lineno=end_lineno,
1483 end_col_offset=end_col_offset,
1484 parent=parent,
1485 )
1486
1487 def postinit(self, left: NodeNG, right: NodeNG) -> None:
1488 self.left = left
1489 self.right = right
1490
1491 def type_errors(
1492 self, context: InferenceContext | None = None
1493 ) -> list[util.BadBinaryOperationMessage]:
1494 """Get a list of type errors which can occur during inference.
1495
1496 Each TypeError is represented by a :class:`~astroid.util.BadBinaryOperationMessage`,
1497 which holds the original exception.
1498
1499 If any inferred result is uninferable, an empty list is returned.
1500 """
1501 bad = []
1502 try:
1503 for result in self._infer_binop(context=context):
1504 if result is util.Uninferable:
1505 raise InferenceError
1506 if isinstance(result, util.BadBinaryOperationMessage):
1507 bad.append(result)
1508 except InferenceError:
1509 return []
1510 return bad
1511
1512 def get_children(self):
1513 yield self.left
1514 yield self.right
1515
1516 def op_precedence(self) -> int:
1517 return OP_PRECEDENCE[self.op]
1518
1519 def op_left_associative(self) -> bool:
1520 # 2**3**4 == 2**(3**4)
1521 return self.op != "**"
1522
1523 def _infer_binop(
1524 self, context: InferenceContext | None = None
1525 ) -> Generator[InferenceResult]:
1526 """Binary operation inference logic."""
1527 left = self.left
1528 right = self.right
1529
1530 # we use two separate contexts for evaluating lhs and rhs because
1531 # 1. evaluating lhs may leave some undesired entries in context.path
1532 # which may not let us infer right value of rhs
1533 context = context or InferenceContext()
1534 lhs_context = copy_context(context)
1535 rhs_context = copy_context(context)
1536 lhs_iter = left.infer(context=lhs_context)
1537 rhs_iter = right.infer(context=rhs_context)
1538 for lhs, rhs in itertools.product(lhs_iter, rhs_iter):
1539 if any(isinstance(value, util.UninferableBase) for value in (rhs, lhs)):
1540 # Don't know how to process this.
1541 yield util.Uninferable
1542 return
1543
1544 try:
1545 yield from self._infer_binary_operation(
1546 lhs, rhs, self, context, self._get_binop_flow
1547 )
1548 except _NonDeducibleTypeHierarchy:
1549 yield util.Uninferable
1550
1551 @decorators.yes_if_nothing_inferred
1552 @decorators.path_wrapper
1553 def _infer(
1554 self, context: InferenceContext | None = None
1555 ) -> Generator[InferenceResult]:
1556 return self._filter_operation_errors(
1557 self._infer_binop, context, util.BadBinaryOperationMessage
1558 )
1559
1560
1561class BoolOp(NodeNG):
1562 """Class representing an :class:`ast.BoolOp` node.
1563
1564 A :class:`BoolOp` is an application of a boolean operator.
1565
1566 >>> import astroid
1567 >>> node = astroid.extract_node('a and b')
1568 >>> node
1569 <BoolOp l.1 at 0x...>
1570 """
1571
1572 _astroid_fields = ("values",)
1573 _other_fields = ("op",)
1574
1575 def __init__(
1576 self,
1577 op: str,
1578 lineno: int | None = None,
1579 col_offset: int | None = None,
1580 parent: NodeNG | None = None,
1581 *,
1582 end_lineno: int | None = None,
1583 end_col_offset: int | None = None,
1584 ) -> None:
1585 """
1586 :param op: The operator.
1587
1588 :param lineno: The line that this node appears on in the source code.
1589
1590 :param col_offset: The column that this node appears on in the
1591 source code.
1592
1593 :param parent: The parent node in the syntax tree.
1594
1595 :param end_lineno: The last line this node appears on in the source code.
1596
1597 :param end_col_offset: The end column this node appears on in the
1598 source code. Note: This is after the last symbol.
1599 """
1600 self.op: str = op
1601 """The operator."""
1602
1603 self.values: list[NodeNG] = []
1604 """The values being applied to the operator."""
1605
1606 super().__init__(
1607 lineno=lineno,
1608 col_offset=col_offset,
1609 end_lineno=end_lineno,
1610 end_col_offset=end_col_offset,
1611 parent=parent,
1612 )
1613
1614 def postinit(self, values: list[NodeNG] | None = None) -> None:
1615 """Do some setup after initialisation.
1616
1617 :param values: The values being applied to the operator.
1618 """
1619 if values is not None:
1620 self.values = values
1621
1622 def get_children(self):
1623 yield from self.values
1624
1625 def op_precedence(self) -> int:
1626 return OP_PRECEDENCE[self.op]
1627
1628 @decorators.raise_if_nothing_inferred
1629 @decorators.path_wrapper
1630 def _infer(
1631 self, context: InferenceContext | None = None
1632 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
1633 """Infer a boolean operation (and / or / not).
1634
1635 The function will calculate the boolean operation
1636 for all pairs generated through inference for each component
1637 node.
1638 """
1639 values = self.values
1640 if self.op == "or":
1641 predicate = operator.truth
1642 else:
1643 predicate = operator.not_
1644
1645 try:
1646 inferred_values = [value.infer(context=context) for value in values]
1647 except InferenceError:
1648 yield util.Uninferable
1649 return None
1650
1651 for pair in itertools.product(*inferred_values):
1652 if any(isinstance(item, util.UninferableBase) for item in pair):
1653 # Can't infer the final result, just yield Uninferable.
1654 yield util.Uninferable
1655 continue
1656
1657 bool_values = [item.bool_value() for item in pair]
1658 if any(isinstance(item, util.UninferableBase) for item in bool_values):
1659 # Can't infer the final result, just yield Uninferable.
1660 yield util.Uninferable
1661 continue
1662
1663 # Since the boolean operations are short circuited operations,
1664 # this code yields the first value for which the predicate is True
1665 # and if no value respected the predicate, then the last value will
1666 # be returned (or Uninferable if there was no last value).
1667 # This is conforming to the semantics of `and` and `or`:
1668 # 1 and 0 -> 1
1669 # 0 and 1 -> 0
1670 # 1 or 0 -> 1
1671 # 0 or 1 -> 1
1672 value = util.Uninferable
1673 for value, bool_value in zip(pair, bool_values):
1674 if predicate(bool_value):
1675 yield value
1676 break
1677 else:
1678 yield value
1679
1680 return InferenceErrorInfo(node=self, context=context)
1681
1682
1683class Break(_base_nodes.NoChildrenNode, _base_nodes.Statement):
1684 """Class representing an :class:`ast.Break` node.
1685
1686 >>> import astroid
1687 >>> node = astroid.extract_node('break')
1688 >>> node
1689 <Break l.1 at 0x...>
1690 """
1691
1692
1693class Call(NodeNG):
1694 """Class representing an :class:`ast.Call` node.
1695
1696 A :class:`Call` node is a call to a function, method, etc.
1697
1698 >>> import astroid
1699 >>> node = astroid.extract_node('function()')
1700 >>> node
1701 <Call l.1 at 0x...>
1702 """
1703
1704 _astroid_fields = ("func", "args", "keywords")
1705
1706 func: NodeNG
1707 """What is being called."""
1708
1709 args: list[NodeNG]
1710 """The positional arguments being given to the call."""
1711
1712 keywords: list[Keyword]
1713 """The keyword arguments being given to the call."""
1714
1715 def postinit(
1716 self, func: NodeNG, args: list[NodeNG], keywords: list[Keyword]
1717 ) -> None:
1718 self.func = func
1719 self.args = args
1720 self.keywords = keywords
1721
1722 @property
1723 def starargs(self) -> list[Starred]:
1724 """The positional arguments that unpack something."""
1725 return [arg for arg in self.args if isinstance(arg, Starred)]
1726
1727 @property
1728 def kwargs(self) -> list[Keyword]:
1729 """The keyword arguments that unpack something."""
1730 return [keyword for keyword in self.keywords if keyword.arg is None]
1731
1732 def get_children(self):
1733 yield self.func
1734
1735 yield from self.args
1736
1737 yield from self.keywords
1738
1739 @decorators.raise_if_nothing_inferred
1740 @decorators.path_wrapper
1741 def _infer(
1742 self, context: InferenceContext | None = None
1743 ) -> Generator[InferenceResult, None, InferenceErrorInfo]:
1744 """Infer a Call node by trying to guess what the function returns."""
1745 callcontext = copy_context(context)
1746 callcontext.boundnode = None
1747 if context is not None:
1748 callcontext.extra_context = self._populate_context_lookup(context.clone())
1749
1750 for callee in self.func.infer(context):
1751 if isinstance(callee, util.UninferableBase):
1752 yield callee
1753 continue
1754 try:
1755 if hasattr(callee, "infer_call_result"):
1756 callcontext.callcontext = CallContext(
1757 args=self.args, keywords=self.keywords, callee=callee
1758 )
1759 yield from callee.infer_call_result(
1760 caller=self, context=callcontext
1761 )
1762 except InferenceError:
1763 continue
1764 return InferenceErrorInfo(node=self, context=context)
1765
1766 def _populate_context_lookup(self, context: InferenceContext | None):
1767 """Allows context to be saved for later for inference inside a function."""
1768 context_lookup: dict[InferenceResult, InferenceContext] = {}
1769 if context is None:
1770 return context_lookup
1771 for arg in self.args:
1772 if isinstance(arg, Starred):
1773 context_lookup[arg.value] = context
1774 else:
1775 context_lookup[arg] = context
1776 keywords = self.keywords if self.keywords is not None else []
1777 for keyword in keywords:
1778 context_lookup[keyword.value] = context
1779 return context_lookup
1780
1781
1782COMPARE_OPS: dict[str, Callable[[Any, Any], bool]] = {
1783 "==": operator.eq,
1784 "!=": operator.ne,
1785 "<": operator.lt,
1786 "<=": operator.le,
1787 ">": operator.gt,
1788 ">=": operator.ge,
1789 "in": lambda a, b: a in b,
1790 "not in": lambda a, b: a not in b,
1791}
1792UNINFERABLE_OPS = {
1793 "is",
1794 "is not",
1795}
1796
1797
1798class Compare(NodeNG):
1799 """Class representing an :class:`ast.Compare` node.
1800
1801 A :class:`Compare` node indicates a comparison.
1802
1803 >>> import astroid
1804 >>> node = astroid.extract_node('a <= b <= c')
1805 >>> node
1806 <Compare l.1 at 0x...>
1807 >>> node.ops
1808 [('<=', <Name.b l.1 at 0x...>), ('<=', <Name.c l.1 at 0x...>)]
1809 """
1810
1811 _astroid_fields = ("left", "ops")
1812
1813 left: NodeNG
1814 """The value at the left being applied to a comparison operator."""
1815
1816 ops: list[tuple[str, NodeNG]]
1817 """The remainder of the operators and their relevant right hand value."""
1818
1819 def postinit(self, left: NodeNG, ops: list[tuple[str, NodeNG]]) -> None:
1820 self.left = left
1821 self.ops = ops
1822
1823 def get_children(self) -> Iterator[NodeNG]:
1824 """Get the child nodes below this node.
1825
1826 Overridden to handle the tuple fields and skip returning the operator
1827 strings.
1828
1829 :returns: The children.
1830 """
1831 yield self.left
1832 for _, comparator in self.ops:
1833 yield comparator # we don't want the 'op'
1834
1835 def last_child(self) -> NodeNG:
1836 """An optimized version of list(get_children())[-1]
1837
1838 :returns: The last child.
1839 """
1840 # XXX maybe if self.ops:
1841 return self.ops[-1][1]
1842 # return self.left
1843
1844 # TODO: move to util?
1845 @staticmethod
1846 def _to_literal(node: SuccessfulInferenceResult) -> Any:
1847 # Can raise SyntaxError, ValueError, or TypeError from ast.literal_eval
1848 # Can raise AttributeError from node.as_string() as not all nodes have a visitor
1849 # Is this the stupidest idea or the simplest idea?
1850 return ast.literal_eval(node.as_string())
1851
1852 def _do_compare(
1853 self,
1854 left_iter: Iterable[InferenceResult],
1855 op: str,
1856 right_iter: Iterable[InferenceResult],
1857 ) -> bool | util.UninferableBase:
1858 """
1859 If all possible combinations are either True or False, return that:
1860 >>> _do_compare([1, 2], '<=', [3, 4])
1861 True
1862 >>> _do_compare([1, 2], '==', [3, 4])
1863 False
1864
1865 If any item is uninferable, or if some combinations are True and some
1866 are False, return Uninferable:
1867 >>> _do_compare([1, 3], '<=', [2, 4])
1868 util.Uninferable
1869 """
1870 retval: bool | None = None
1871 if op in UNINFERABLE_OPS:
1872 return util.Uninferable
1873 op_func = COMPARE_OPS[op]
1874
1875 for left, right in itertools.product(left_iter, right_iter):
1876 if isinstance(left, util.UninferableBase) or isinstance(
1877 right, util.UninferableBase
1878 ):
1879 return util.Uninferable
1880
1881 try:
1882 left, right = self._to_literal(left), self._to_literal(right)
1883 except (SyntaxError, ValueError, AttributeError, TypeError):
1884 return util.Uninferable
1885
1886 try:
1887 expr = op_func(left, right)
1888 except TypeError as exc:
1889 raise AstroidTypeError from exc
1890 except ValueError as exc:
1891 raise AstroidValueError from exc
1892
1893 if retval is None:
1894 retval = expr
1895 elif retval != expr:
1896 return util.Uninferable
1897 # (or both, but "True | False" is basically the same)
1898
1899 assert retval is not None
1900 return retval # it was all the same value
1901
1902 def _infer(
1903 self, context: InferenceContext | None = None
1904 ) -> Generator[nodes.Const | util.UninferableBase]:
1905 """Chained comparison inference logic."""
1906 retval: bool | util.UninferableBase = True
1907
1908 ops = self.ops
1909 left_node = self.left
1910 lhs = list(left_node.infer(context=context))
1911 # should we break early if first element is uninferable?
1912 for op, right_node in ops:
1913 # eagerly evaluate rhs so that values can be reused as lhs
1914 rhs = list(right_node.infer(context=context))
1915 try:
1916 retval = self._do_compare(lhs, op, rhs)
1917 except (AstroidTypeError, AstroidValueError):
1918 retval = util.Uninferable
1919 break
1920 if retval is not True:
1921 break # short-circuit
1922 lhs = rhs # continue
1923 if retval is util.Uninferable:
1924 yield retval # type: ignore[misc]
1925 else:
1926 yield Const(retval)
1927
1928
1929class Comprehension(NodeNG):
1930 """Class representing an :class:`ast.comprehension` node.
1931
1932 A :class:`Comprehension` indicates the loop inside any type of
1933 comprehension including generator expressions.
1934
1935 >>> import astroid
1936 >>> node = astroid.extract_node('[x for x in some_values]')
1937 >>> list(node.get_children())
1938 [<Name.x l.1 at 0x...>, <Comprehension l.1 at 0x...>]
1939 >>> list(node.get_children())[1].as_string()
1940 'for x in some_values'
1941 """
1942
1943 _astroid_fields = ("target", "iter", "ifs")
1944 _other_fields = ("is_async",)
1945
1946 optional_assign = True
1947 """Whether this node optionally assigns a variable."""
1948
1949 target: NodeNG
1950 """What is assigned to by the comprehension."""
1951
1952 iter: NodeNG
1953 """What is iterated over by the comprehension."""
1954
1955 ifs: list[NodeNG]
1956 """The contents of any if statements that filter the comprehension."""
1957
1958 is_async: bool
1959 """Whether this is an asynchronous comprehension or not."""
1960
1961 def postinit(
1962 self,
1963 target: NodeNG,
1964 iter: NodeNG, # pylint: disable = redefined-builtin
1965 ifs: list[NodeNG],
1966 is_async: bool,
1967 ) -> None:
1968 self.target = target
1969 self.iter = iter
1970 self.ifs = ifs
1971 self.is_async = is_async
1972
1973 assigned_stmts = protocols.for_assigned_stmts
1974 """Returns the assigned statement (non inferred) according to the assignment type.
1975 See astroid/protocols.py for actual implementation.
1976 """
1977
1978 def assign_type(self) -> Self:
1979 """The type of assignment that this node performs.
1980
1981 :returns: The assignment type.
1982 """
1983 return self
1984
1985 def _get_filtered_stmts(
1986 self, lookup_node, node, stmts, mystmt: _base_nodes.Statement | None
1987 ):
1988 """method used in filter_stmts"""
1989 if self is mystmt:
1990 if isinstance(lookup_node, (Const, Name)):
1991 return [lookup_node], True
1992
1993 elif self.statement() is mystmt:
1994 # original node's statement is the assignment, only keeps
1995 # current node (gen exp, list comp)
1996
1997 return [node], True
1998
1999 return stmts, False
2000
2001 def get_children(self):
2002 yield self.target
2003 yield self.iter
2004
2005 yield from self.ifs
2006
2007
2008class Const(_base_nodes.NoChildrenNode, Instance):
2009 """Class representing any constant including num, str, bool, None, bytes.
2010
2011 >>> import astroid
2012 >>> node = astroid.extract_node('(5, "This is a string.", True, None, b"bytes")')
2013 >>> node
2014 <Tuple.tuple l.1 at 0x...>
2015 >>> list(node.get_children())
2016 [<Const.int l.1 at 0x...>,
2017 <Const.str l.1 at 0x...>,
2018 <Const.bool l.1 at 0x...>,
2019 <Const.NoneType l.1 at 0x...>,
2020 <Const.bytes l.1 at 0x...>]
2021 """
2022
2023 _other_fields = ("value", "kind")
2024
2025 def __init__(
2026 self,
2027 value: Any,
2028 lineno: int | None = None,
2029 col_offset: int | None = None,
2030 parent: NodeNG = SYNTHETIC_ROOT,
2031 kind: str | None = None,
2032 *,
2033 end_lineno: int | None = None,
2034 end_col_offset: int | None = None,
2035 ) -> None:
2036 """
2037 :param value: The value that the constant represents.
2038
2039 :param lineno: The line that this node appears on in the source code.
2040
2041 :param col_offset: The column that this node appears on in the
2042 source code.
2043
2044 :param parent: The parent node in the syntax tree.
2045
2046 :param kind: The string prefix. "u" for u-prefixed strings and ``None`` otherwise.
2047
2048 :param end_lineno: The last line this node appears on in the source code.
2049
2050 :param end_col_offset: The end column this node appears on in the
2051 source code. Note: This is after the last symbol.
2052 """
2053 if getattr(value, "__name__", None) == "__doc__":
2054 warnings.warn( # pragma: no cover
2055 "You have most likely called a __doc__ field of some object "
2056 "and it didn't return a string. "
2057 "That happens to some symbols from the standard library. "
2058 "Check for isinstance(<X>.__doc__, str).",
2059 RuntimeWarning,
2060 stacklevel=0,
2061 )
2062 self.value = value
2063 """The value that the constant represents."""
2064
2065 self.kind: str | None = kind # can be None
2066 """"The string prefix. "u" for u-prefixed strings and ``None`` otherwise."""
2067
2068 super().__init__(
2069 lineno=lineno,
2070 col_offset=col_offset,
2071 end_lineno=end_lineno,
2072 end_col_offset=end_col_offset,
2073 parent=parent,
2074 )
2075
2076 Instance.__init__(self, None)
2077
2078 infer_unary_op = protocols.const_infer_unary_op
2079 infer_binary_op = protocols.const_infer_binary_op
2080
2081 def __getattr__(self, name):
2082 # This is needed because of Proxy's __getattr__ method.
2083 # Calling object.__new__ on this class without calling
2084 # __init__ would result in an infinite loop otherwise
2085 # since __getattr__ is called when an attribute doesn't
2086 # exist and self._proxied indirectly calls self.value
2087 # and Proxy __getattr__ calls self.value
2088 if name == "value":
2089 raise AttributeError
2090 return super().__getattr__(name)
2091
2092 def getitem(
2093 self, index: SuccessfulInferenceResult, context: InferenceContext | None = None
2094 ) -> Const:
2095 """Get an item from this node if subscriptable.
2096
2097 :param index: The node to use as a subscript index.
2098
2099 :raises AstroidTypeError: When the given index cannot be used as a
2100 subscript index, or if this node is not subscriptable.
2101 """
2102 if isinstance(index, Const):
2103 index_value = index.value
2104 elif isinstance(index, Slice):
2105 index_value = _infer_slice(index, context=context)
2106
2107 else:
2108 raise AstroidTypeError(
2109 f"Could not use type {type(index)} as subscript index"
2110 )
2111
2112 try:
2113 if isinstance(self.value, (str, bytes)):
2114 return Const(self.value[index_value])
2115 except ValueError as exc:
2116 raise AstroidValueError(
2117 f"Could not index {self.value!r} with {index_value!r}"
2118 ) from exc
2119 except IndexError as exc:
2120 raise AstroidIndexError(
2121 message="Index {index!r} out of range",
2122 node=self,
2123 index=index,
2124 context=context,
2125 ) from exc
2126 except TypeError as exc:
2127 raise AstroidTypeError(
2128 message="Type error {error!r}", node=self, index=index, context=context
2129 ) from exc
2130
2131 try:
2132 value_str = str(self.value)
2133 except ValueError:
2134 value_str = f"<{type(self.value).__name__} (too large to display)>"
2135 raise AstroidTypeError(f"{self!r} (value={value_str})")
2136
2137 def has_dynamic_getattr(self) -> bool:
2138 """Check if the node has a custom __getattr__ or __getattribute__.
2139
2140 :returns: Whether the class has a custom __getattr__ or __getattribute__.
2141 For a :class:`Const` this is always ``False``.
2142 """
2143 return False
2144
2145 def itered(self) -> list[ConstFactoryResult]:
2146 """An iterator over the elements this node contains.
2147
2148 :returns: The contents of this node.
2149
2150 :raises TypeError: If this node does not represent something that is iterable.
2151 """
2152 if isinstance(self.value, str):
2153 return [const_factory(elem) for elem in self.value]
2154 raise TypeError(f"Cannot iterate over type {type(self.value)!r}")
2155
2156 def pytype(self) -> str:
2157 """Get the name of the type that this node represents.
2158
2159 :returns: The name of the type.
2160 """
2161 return self._proxied.qname()
2162
2163 def bool_value(
2164 self, context: InferenceContext | None = None
2165 ) -> bool | util.UninferableBase:
2166 """Determine the boolean value of this node.
2167
2168 :returns: The boolean value of this node.
2169 """
2170 # bool(NotImplemented) is deprecated; it raises TypeError starting from Python 3.14
2171 # and returns True for versions under 3.14
2172 if self.value is NotImplemented:
2173 return util.Uninferable if PY314_PLUS else True
2174 return bool(self.value)
2175
2176 def _infer(self, context: InferenceContext | None = None) -> Iterator[Const]:
2177 yield self
2178
2179
2180class Continue(_base_nodes.NoChildrenNode, _base_nodes.Statement):
2181 """Class representing an :class:`ast.Continue` node.
2182
2183 >>> import astroid
2184 >>> node = astroid.extract_node('continue')
2185 >>> node
2186 <Continue l.1 at 0x...>
2187 """
2188
2189
2190class Decorators(NodeNG):
2191 """A node representing a list of decorators.
2192
2193 A :class:`Decorators` is the decorators that are applied to
2194 a method or function.
2195
2196 >>> import astroid
2197 >>> node = astroid.extract_node('''
2198 ... @property
2199 ... def my_property(self):
2200 ... return 3
2201 ... ''')
2202 >>> node
2203 <FunctionDef.my_property l.3 at 0x...>
2204 >>> list(node.get_children())[0]
2205 <Decorators l.2 at 0x...>
2206 """
2207
2208 _astroid_fields = ("nodes",)
2209
2210 nodes: list[NodeNG]
2211 """The decorators that this node contains."""
2212
2213 def postinit(self, nodes: list[NodeNG]) -> None:
2214 self.nodes = nodes
2215
2216 def scope(self) -> LocalsDictNodeNG:
2217 """The first parent node defining a new scope.
2218 These can be Module, FunctionDef, ClassDef, Lambda, or GeneratorExp nodes.
2219
2220 :returns: The first parent scope node.
2221 """
2222 # skip the function or class node to go directly to the upper level scope
2223 if not self.parent:
2224 raise ParentMissingError(target=self)
2225 if not self.parent.parent:
2226 raise ParentMissingError(target=self.parent)
2227 return self.parent.parent.scope()
2228
2229 def frame(self) -> FrameType:
2230 """The first parent node defining a new frame."""
2231 # skip the function or class node to go directly to the upper level frame
2232 if not self.parent:
2233 raise ParentMissingError(target=self)
2234 if not self.parent.parent:
2235 raise ParentMissingError(target=self.parent)
2236 return self.parent.parent.frame()
2237
2238 def get_children(self):
2239 yield from self.nodes
2240
2241
2242class DelAttr(_base_nodes.ParentAssignNode):
2243 """Variation of :class:`ast.Delete` representing deletion of an attribute.
2244
2245 >>> import astroid
2246 >>> node = astroid.extract_node('del self.attr')
2247 >>> node
2248 <Delete l.1 at 0x...>
2249 >>> list(node.get_children())[0]
2250 <DelAttr.attr l.1 at 0x...>
2251 """
2252
2253 _astroid_fields = ("expr",)
2254 _other_fields = ("attrname",)
2255
2256 expr: NodeNG
2257 """The name that this node represents."""
2258
2259 def __init__(
2260 self,
2261 attrname: str,
2262 lineno: int,
2263 col_offset: int,
2264 parent: NodeNG,
2265 *,
2266 end_lineno: int | None,
2267 end_col_offset: int | None,
2268 ) -> None:
2269 self.attrname = attrname
2270 """The name of the attribute that is being deleted."""
2271
2272 super().__init__(
2273 lineno=lineno,
2274 col_offset=col_offset,
2275 end_lineno=end_lineno,
2276 end_col_offset=end_col_offset,
2277 parent=parent,
2278 )
2279
2280 def postinit(self, expr: NodeNG) -> None:
2281 self.expr = expr
2282
2283 def get_children(self):
2284 yield self.expr
2285
2286
2287class Delete(_base_nodes.AssignTypeNode, _base_nodes.Statement):
2288 """Class representing an :class:`ast.Delete` node.
2289
2290 A :class:`Delete` is a ``del`` statement this is deleting something.
2291
2292 >>> import astroid
2293 >>> node = astroid.extract_node('del self.attr')
2294 >>> node
2295 <Delete l.1 at 0x...>
2296 """
2297
2298 _astroid_fields = ("targets",)
2299
2300 def __init__(
2301 self,
2302 lineno: int,
2303 col_offset: int,
2304 parent: NodeNG,
2305 *,
2306 end_lineno: int | None,
2307 end_col_offset: int | None,
2308 ) -> None:
2309 self.targets: list[NodeNG] = []
2310 """What is being deleted."""
2311
2312 super().__init__(
2313 lineno=lineno,
2314 col_offset=col_offset,
2315 end_lineno=end_lineno,
2316 end_col_offset=end_col_offset,
2317 parent=parent,
2318 )
2319
2320 def postinit(self, targets: list[NodeNG]) -> None:
2321 self.targets = targets
2322
2323 def get_children(self):
2324 yield from self.targets
2325
2326
2327class Dict(NodeNG, Instance):
2328 """Class representing an :class:`ast.Dict` node.
2329
2330 A :class:`Dict` is a dictionary that is created with ``{}`` syntax.
2331
2332 >>> import astroid
2333 >>> node = astroid.extract_node('{1: "1"}')
2334 >>> node
2335 <Dict.dict l.1 at 0x...>
2336 """
2337
2338 _astroid_fields = ("items",)
2339
2340 def __init__(
2341 self,
2342 lineno: int | None,
2343 col_offset: int | None,
2344 parent: NodeNG | None,
2345 *,
2346 end_lineno: int | None,
2347 end_col_offset: int | None,
2348 ) -> None:
2349 self.items: list[tuple[InferenceResult, InferenceResult]] = []
2350 """The key-value pairs contained in the dictionary."""
2351
2352 super().__init__(
2353 lineno=lineno,
2354 col_offset=col_offset,
2355 end_lineno=end_lineno,
2356 end_col_offset=end_col_offset,
2357 parent=parent,
2358 )
2359
2360 def postinit(self, items: list[tuple[InferenceResult, InferenceResult]]) -> None:
2361 """Do some setup after initialisation.
2362
2363 :param items: The key-value pairs contained in the dictionary.
2364 """
2365 self.items = items
2366
2367 infer_unary_op = protocols.dict_infer_unary_op
2368
2369 def pytype(self) -> Literal["builtins.dict"]:
2370 """Get the name of the type that this node represents.
2371
2372 :returns: The name of the type.
2373 """
2374 return "builtins.dict"
2375
2376 def get_children(self) -> Iterator[InferenceResult]:
2377 """Get the key and value nodes below this node.
2378
2379 Children are returned in the order that they are defined in the source
2380 code, key first then the value.
2381
2382 :returns: The children.
2383 """
2384 for key, value in self.items:
2385 yield key
2386 yield value
2387
2388 def last_child(self) -> InferenceResult | None:
2389 """An optimized version of list(get_children())[-1]
2390
2391 :returns: The last child, or None if no children exist.
2392 """
2393 if self.items:
2394 return self.items[-1][1]
2395 return None
2396
2397 def itered(self) -> list[InferenceResult]:
2398 """An iterator over the keys this node contains.
2399
2400 :returns: The keys of this node.
2401 """
2402 return [key for (key, _) in self.items]
2403
2404 def getitem(
2405 self, index: Const | Slice, context: InferenceContext | None = None
2406 ) -> NodeNG:
2407 """Get an item from this node.
2408
2409 :param index: The node to use as a subscript index.
2410
2411 :raises AstroidTypeError: When the given index cannot be used as a
2412 subscript index, or if this node is not subscriptable.
2413 :raises AstroidIndexError: If the given index does not exist in the
2414 dictionary.
2415 """
2416 for key, value in self.items:
2417 # TODO(cpopa): no support for overriding yet, {1:2, **{1: 3}}.
2418 if isinstance(key, DictUnpack):
2419 inferred_value = util.safe_infer(value, context)
2420 if not isinstance(inferred_value, Dict):
2421 continue
2422
2423 try:
2424 return inferred_value.getitem(index, context)
2425 except (AstroidTypeError, AstroidIndexError):
2426 continue
2427
2428 for inferredkey in key.infer(context):
2429 if isinstance(inferredkey, util.UninferableBase):
2430 continue
2431 if isinstance(inferredkey, Const) and isinstance(index, Const):
2432 if inferredkey.value == index.value:
2433 return value
2434
2435 raise AstroidIndexError(index)
2436
2437 def bool_value(self, context: InferenceContext | None = None) -> bool:
2438 """Determine the boolean value of this node.
2439
2440 :returns: The boolean value of this node.
2441 """
2442 return bool(self.items)
2443
2444 def _infer(self, context: InferenceContext | None = None) -> Iterator[nodes.Dict]:
2445 if not any(isinstance(k, DictUnpack) for k, _ in self.items):
2446 yield self
2447 else:
2448 items = self._infer_map(context)
2449 new_seq = type(self)(
2450 lineno=self.lineno,
2451 col_offset=self.col_offset,
2452 parent=self.parent,
2453 end_lineno=self.end_lineno,
2454 end_col_offset=self.end_col_offset,
2455 )
2456 new_seq.postinit(list(items.items()))
2457 yield new_seq
2458
2459 @staticmethod
2460 def _update_with_replacement(
2461 lhs_dict: dict[SuccessfulInferenceResult, SuccessfulInferenceResult],
2462 rhs_dict: dict[SuccessfulInferenceResult, SuccessfulInferenceResult],
2463 ) -> dict[SuccessfulInferenceResult, SuccessfulInferenceResult]:
2464 """Delete nodes that equate to duplicate keys.
2465
2466 Since an astroid node doesn't 'equal' another node with the same value,
2467 this function uses the as_string method to make sure duplicate keys
2468 don't get through
2469
2470 Note that both the key and the value are astroid nodes
2471
2472 Fixes issue with DictUnpack causing duplicate keys
2473 in inferred Dict items
2474
2475 :param lhs_dict: Dictionary to 'merge' nodes into
2476 :param rhs_dict: Dictionary with nodes to pull from
2477 :return : merged dictionary of nodes
2478 """
2479 combined_dict = itertools.chain(lhs_dict.items(), rhs_dict.items())
2480 # Overwrite keys which have the same string values
2481 string_map = {key.as_string(): (key, value) for key, value in combined_dict}
2482 # Return to dictionary
2483 return dict(string_map.values())
2484
2485 def _infer_map(
2486 self, context: InferenceContext | None
2487 ) -> dict[SuccessfulInferenceResult, SuccessfulInferenceResult]:
2488 """Infer all values based on Dict.items."""
2489 values: dict[SuccessfulInferenceResult, SuccessfulInferenceResult] = {}
2490 for name, value in self.items:
2491 if isinstance(name, DictUnpack):
2492 double_starred = util.safe_infer(value, context)
2493 if not double_starred:
2494 raise InferenceError
2495 if not isinstance(double_starred, Dict):
2496 raise InferenceError(node=self, context=context)
2497 unpack_items = double_starred._infer_map(context)
2498 values = self._update_with_replacement(values, unpack_items)
2499 else:
2500 key = util.safe_infer(name, context=context)
2501 safe_value = util.safe_infer(value, context=context)
2502 if any(not elem for elem in (key, safe_value)):
2503 raise InferenceError(node=self, context=context)
2504 # safe_value is SuccessfulInferenceResult as bool(Uninferable) == False
2505 values = self._update_with_replacement(values, {key: safe_value})
2506 return values
2507
2508
2509class Expr(_base_nodes.Statement):
2510 """Class representing an :class:`ast.Expr` node.
2511
2512 An :class:`Expr` is any expression that does not have its value used or
2513 stored.
2514
2515 >>> import astroid
2516 >>> node = astroid.extract_node('method()')
2517 >>> node
2518 <Call l.1 at 0x...>
2519 >>> node.parent
2520 <Expr l.1 at 0x...>
2521 """
2522
2523 _astroid_fields = ("value",)
2524
2525 value: NodeNG
2526 """What the expression does."""
2527
2528 def postinit(self, value: NodeNG) -> None:
2529 self.value = value
2530
2531 def get_children(self):
2532 yield self.value
2533
2534 def _get_yield_nodes_skip_functions(self):
2535 if not self.value.is_function:
2536 yield from self.value._get_yield_nodes_skip_functions()
2537
2538 def _get_yield_nodes_skip_lambdas(self):
2539 if not self.value.is_lambda:
2540 yield from self.value._get_yield_nodes_skip_lambdas()
2541
2542
2543class EmptyNode(_base_nodes.NoChildrenNode):
2544 """Holds an arbitrary object in the :attr:`~astroid.nodes.LocalsDictNodeNG.locals`."""
2545
2546 object = None
2547
2548 def __init__(
2549 self,
2550 lineno: None = None,
2551 col_offset: None = None,
2552 parent: NodeNG = SYNTHETIC_ROOT,
2553 *,
2554 end_lineno: None = None,
2555 end_col_offset: None = None,
2556 ) -> None:
2557 super().__init__(
2558 lineno=lineno,
2559 col_offset=col_offset,
2560 end_lineno=end_lineno,
2561 end_col_offset=end_col_offset,
2562 parent=parent,
2563 )
2564
2565 def has_underlying_object(self) -> bool:
2566 return self.object is not None and self.object is not _EMPTY_OBJECT_MARKER
2567
2568 @decorators.raise_if_nothing_inferred
2569 @decorators.path_wrapper
2570 def _infer(
2571 self, context: InferenceContext | None = None
2572 ) -> Generator[InferenceResult]:
2573 if not self.has_underlying_object():
2574 yield util.Uninferable
2575 else:
2576 try:
2577 yield from AstroidManager().infer_ast_from_something(
2578 self.object, context=context
2579 )
2580 except AstroidError:
2581 yield util.Uninferable
2582
2583
2584class ExceptHandler(
2585 _base_nodes.MultiLineBlockNode, _base_nodes.AssignTypeNode, _base_nodes.Statement
2586):
2587 """Class representing an :class:`ast.ExceptHandler`. node.
2588
2589 An :class:`ExceptHandler` is an ``except`` block on a try-except.
2590
2591 >>> import astroid
2592 >>> node = astroid.extract_node('''
2593 ... try:
2594 ... do_something()
2595 ... except Exception as error:
2596 ... print("Error!")
2597 ... ''')
2598 >>> node
2599 <Try l.2 at 0x...>
2600 >>> node.handlers
2601 [<ExceptHandler l.4 at 0x...>]
2602 """
2603
2604 _astroid_fields = ("type", "name", "body")
2605 _multi_line_block_fields = ("body",)
2606
2607 type: NodeNG | None
2608 """The types that the block handles."""
2609
2610 name: AssignName | None
2611 """The name that the caught exception is assigned to."""
2612
2613 body: list[NodeNG]
2614 """The contents of the block."""
2615
2616 assigned_stmts = protocols.excepthandler_assigned_stmts
2617 """Returns the assigned statement (non inferred) according to the assignment type.
2618 See astroid/protocols.py for actual implementation.
2619 """
2620
2621 def postinit(
2622 self,
2623 type: NodeNG | None, # pylint: disable = redefined-builtin
2624 name: AssignName | None,
2625 body: list[NodeNG],
2626 ) -> None:
2627 self.type = type
2628 self.name = name
2629 self.body = body
2630
2631 def get_children(self):
2632 if self.type is not None:
2633 yield self.type
2634
2635 if self.name is not None:
2636 yield self.name
2637
2638 yield from self.body
2639
2640 @cached_property
2641 def blockstart_tolineno(self) -> int | None:
2642 """The line on which the beginning of this block ends."""
2643 if self.name:
2644 return self.name.tolineno
2645 if self.type:
2646 return self.type.tolineno
2647 return self.lineno
2648
2649 def catch(self, exceptions: list[str] | None) -> bool:
2650 """Check if this node handles any of the given
2651
2652 :param exceptions: The names of the exceptions to check for.
2653 """
2654 if self.type is None or exceptions is None:
2655 return True
2656 return any(node.name in exceptions for node in self.type._get_name_nodes())
2657
2658
2659class For(
2660 _base_nodes.MultiLineWithElseBlockNode,
2661 _base_nodes.AssignTypeNode,
2662 _base_nodes.Statement,
2663):
2664 """Class representing an :class:`ast.For` node.
2665
2666 >>> import astroid
2667 >>> node = astroid.extract_node('for thing in things: print(thing)')
2668 >>> node
2669 <For l.1 at 0x...>
2670 """
2671
2672 _astroid_fields = ("target", "iter", "body", "orelse")
2673 _other_other_fields = ("type_annotation",)
2674 _multi_line_block_fields = ("body", "orelse")
2675
2676 optional_assign = True
2677 """Whether this node optionally assigns a variable.
2678
2679 This is always ``True`` for :class:`For` nodes.
2680 """
2681
2682 target: NodeNG
2683 """What the loop assigns to."""
2684
2685 iter: NodeNG
2686 """What the loop iterates over."""
2687
2688 body: list[NodeNG]
2689 """The contents of the body of the loop."""
2690
2691 orelse: list[NodeNG]
2692 """The contents of the ``else`` block of the loop."""
2693
2694 type_annotation: NodeNG | None
2695 """If present, this will contain the type annotation passed by a type comment"""
2696
2697 def postinit(
2698 self,
2699 target: NodeNG,
2700 iter: NodeNG, # pylint: disable = redefined-builtin
2701 body: list[NodeNG],
2702 orelse: list[NodeNG],
2703 type_annotation: NodeNG | None,
2704 ) -> None:
2705 self.target = target
2706 self.iter = iter
2707 self.body = body
2708 self.orelse = orelse
2709 self.type_annotation = type_annotation
2710
2711 assigned_stmts = protocols.for_assigned_stmts
2712 """Returns the assigned statement (non inferred) according to the assignment type.
2713 See astroid/protocols.py for actual implementation.
2714 """
2715
2716 @cached_property
2717 def blockstart_tolineno(self) -> int:
2718 """The line on which the beginning of this block ends."""
2719 return self.iter.tolineno
2720
2721 def get_children(self):
2722 yield self.target
2723 yield self.iter
2724
2725 yield from self.body
2726 yield from self.orelse
2727
2728
2729class AsyncFor(For):
2730 """Class representing an :class:`ast.AsyncFor` node.
2731
2732 An :class:`AsyncFor` is an asynchronous :class:`For` built with
2733 the ``async`` keyword.
2734
2735 >>> import astroid
2736 >>> node = astroid.extract_node('''
2737 ... async def func(things):
2738 ... async for thing in things:
2739 ... print(thing)
2740 ... ''')
2741 >>> node
2742 <AsyncFunctionDef.func l.2 at 0x...>
2743 >>> node.body[0]
2744 <AsyncFor l.3 at 0x...>
2745 """
2746
2747
2748class Await(NodeNG):
2749 """Class representing an :class:`ast.Await` node.
2750
2751 An :class:`Await` is the ``await`` keyword.
2752
2753 >>> import astroid
2754 >>> node = astroid.extract_node('''
2755 ... async def func(things):
2756 ... await other_func()
2757 ... ''')
2758 >>> node
2759 <AsyncFunctionDef.func l.2 at 0x...>
2760 >>> node.body[0]
2761 <Expr l.3 at 0x...>
2762 >>> list(node.body[0].get_children())[0]
2763 <Await l.3 at 0x...>
2764 """
2765
2766 _astroid_fields = ("value",)
2767
2768 value: NodeNG
2769 """What to wait for."""
2770
2771 def postinit(self, value: NodeNG) -> None:
2772 self.value = value
2773
2774 def get_children(self):
2775 yield self.value
2776
2777
2778class ImportFrom(_base_nodes.ImportNode):
2779 """Class representing an :class:`ast.ImportFrom` node.
2780
2781 >>> import astroid
2782 >>> node = astroid.extract_node('from my_package import my_module')
2783 >>> node
2784 <ImportFrom l.1 at 0x...>
2785 """
2786
2787 _other_fields = ("modname", "names", "level", "is_lazy")
2788
2789 def __init__(
2790 self,
2791 fromname: str | None,
2792 names: list[tuple[str, str | None]],
2793 level: int | None = 0,
2794 lineno: int | None = None,
2795 col_offset: int | None = None,
2796 parent: NodeNG | None = None,
2797 *,
2798 end_lineno: int | None = None,
2799 end_col_offset: int | None = None,
2800 is_lazy: int = 0,
2801 ) -> None:
2802 """
2803 :param fromname: The module that is being imported from.
2804
2805 :param names: What is being imported from the module.
2806
2807 :param level: The level of relative import.
2808
2809 :param is_lazy: Whether this is a PEP 810 lazy import (``lazy from ...``).
2810
2811 :param lineno: The line that this node appears on in the source code.
2812
2813 :param col_offset: The column that this node appears on in the
2814 source code.
2815
2816 :param parent: The parent node in the syntax tree.
2817
2818 :param end_lineno: The last line this node appears on in the source code.
2819
2820 :param end_col_offset: The end column this node appears on in the
2821 source code. Note: This is after the last symbol.
2822 """
2823 self.modname: str | None = fromname # can be None
2824 """The module that is being imported from.
2825
2826 This is ``None`` for relative imports.
2827 """
2828
2829 self.names: list[tuple[str, str | None]] = names
2830 """What is being imported from the module.
2831
2832 Each entry is a :class:`tuple` of the name being imported,
2833 and the alias that the name is assigned to (if any).
2834 """
2835
2836 self.level: int | None = level # can be None
2837 """The level of relative import.
2838
2839 Essentially this is the number of dots in the import.
2840 This is ``None`` for absolute imports.
2841 """
2842
2843 self.is_lazy: int = is_lazy
2844 """Whether this is a PEP 810 lazy import (``lazy from ... import ...``).
2845
2846 Always ``0`` before Python 3.15.
2847 """
2848
2849 super().__init__(
2850 lineno=lineno,
2851 col_offset=col_offset,
2852 end_lineno=end_lineno,
2853 end_col_offset=end_col_offset,
2854 parent=parent,
2855 )
2856
2857 @decorators.raise_if_nothing_inferred
2858 @decorators.path_wrapper
2859 def _infer(
2860 self, context: InferenceContext | None = None
2861 ) -> Generator[InferenceResult]:
2862 """Infer a ImportFrom node: return the imported module/object."""
2863 context = context or InferenceContext()
2864 name = context.lookupname
2865 if name is None:
2866 raise InferenceError(node=self, context=context)
2867 try:
2868 module = self.do_import_module()
2869 except AstroidBuildingError as exc:
2870 raise InferenceError(node=self, context=context) from exc
2871
2872 try:
2873 context = copy_context(context)
2874 context.lookupname = name
2875 stmts = module.getattr(name, ignore_locals=module is self.root())
2876 return _infer_stmts(stmts, context)
2877 except AttributeInferenceError as error:
2878 raise InferenceError(
2879 str(error), target=self, attribute=name, context=context
2880 ) from error
2881
2882
2883class Attribute(NodeNG):
2884 """Class representing an :class:`ast.Attribute` node."""
2885
2886 expr: NodeNG
2887
2888 _astroid_fields = ("expr",)
2889 _other_fields = ("attrname",)
2890
2891 def __init__(
2892 self,
2893 attrname: str,
2894 lineno: int,
2895 col_offset: int,
2896 parent: NodeNG,
2897 *,
2898 end_lineno: int | None,
2899 end_col_offset: int | None,
2900 ) -> None:
2901 self.attrname = attrname
2902 """The name of the attribute."""
2903
2904 super().__init__(
2905 lineno=lineno,
2906 col_offset=col_offset,
2907 end_lineno=end_lineno,
2908 end_col_offset=end_col_offset,
2909 parent=parent,
2910 )
2911
2912 def postinit(self, expr: NodeNG) -> None:
2913 self.expr = expr
2914
2915 def get_children(self):
2916 yield self.expr
2917
2918 @decorators.raise_if_nothing_inferred
2919 @decorators.path_wrapper
2920 def _infer(
2921 self, context: InferenceContext | None = None
2922 ) -> Generator[InferenceResult, None, InferenceErrorInfo]:
2923 return _infer_attribute(self, context)
2924
2925
2926class Global(_base_nodes.NoChildrenNode, _base_nodes.Statement):
2927 """Class representing an :class:`ast.Global` node.
2928
2929 >>> import astroid
2930 >>> node = astroid.extract_node('global a_global')
2931 >>> node
2932 <Global l.1 at 0x...>
2933 """
2934
2935 _other_fields = ("names",)
2936
2937 def __init__(
2938 self,
2939 names: list[str],
2940 lineno: int | None = None,
2941 col_offset: int | None = None,
2942 parent: NodeNG | None = None,
2943 *,
2944 end_lineno: int | None = None,
2945 end_col_offset: int | None = None,
2946 ) -> None:
2947 """
2948 :param names: The names being declared as global.
2949
2950 :param lineno: The line that this node appears on in the source code.
2951
2952 :param col_offset: The column that this node appears on in the
2953 source code.
2954
2955 :param parent: The parent node in the syntax tree.
2956
2957 :param end_lineno: The last line this node appears on in the source code.
2958
2959 :param end_col_offset: The end column this node appears on in the
2960 source code. Note: This is after the last symbol.
2961 """
2962 self.names: list[str] = names
2963 """The names being declared as global."""
2964
2965 super().__init__(
2966 lineno=lineno,
2967 col_offset=col_offset,
2968 end_lineno=end_lineno,
2969 end_col_offset=end_col_offset,
2970 parent=parent,
2971 )
2972
2973 def _infer_name(self, frame, name):
2974 return name
2975
2976 @decorators.raise_if_nothing_inferred
2977 @decorators.path_wrapper
2978 def _infer(
2979 self, context: InferenceContext | None = None
2980 ) -> Generator[InferenceResult]:
2981 if context is None or context.lookupname is None:
2982 raise InferenceError(node=self, context=context)
2983 try:
2984 # pylint: disable-next=no-member
2985 return _infer_stmts(self.root().getattr(context.lookupname), context)
2986 except AttributeInferenceError as error:
2987 raise InferenceError(
2988 str(error), target=self, attribute=context.lookupname, context=context
2989 ) from error
2990
2991
2992class If(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
2993 """Class representing an :class:`ast.If` node.
2994
2995 >>> import astroid
2996 >>> node = astroid.extract_node('if condition: print(True)')
2997 >>> node
2998 <If l.1 at 0x...>
2999 """
3000
3001 _astroid_fields = ("test", "body", "orelse")
3002 _multi_line_block_fields = ("body", "orelse")
3003
3004 test: NodeNG
3005 """The condition that the statement tests."""
3006
3007 body: list[NodeNG]
3008 """The contents of the block."""
3009
3010 orelse: list[NodeNG]
3011 """The contents of the ``else`` block."""
3012
3013 def postinit(self, test: NodeNG, body: list[NodeNG], orelse: list[NodeNG]) -> None:
3014 self.test = test
3015 self.body = body
3016 self.orelse = orelse
3017
3018 @cached_property
3019 def blockstart_tolineno(self) -> int:
3020 """The line on which the beginning of this block ends."""
3021 return self.test.tolineno
3022
3023 def get_children(self):
3024 yield self.test
3025
3026 yield from self.body
3027 yield from self.orelse
3028
3029 def has_elif_block(self) -> bool:
3030 return len(self.orelse) == 1 and isinstance(self.orelse[0], If)
3031
3032 def _get_yield_nodes_skip_functions(self):
3033 """An If node can contain a Yield node in the test"""
3034 yield from self.test._get_yield_nodes_skip_functions()
3035 yield from super()._get_yield_nodes_skip_functions()
3036
3037 def _get_yield_nodes_skip_lambdas(self):
3038 """An If node can contain a Yield node in the test"""
3039 yield from self.test._get_yield_nodes_skip_lambdas()
3040 yield from super()._get_yield_nodes_skip_lambdas()
3041
3042
3043class IfExp(NodeNG):
3044 """Class representing an :class:`ast.IfExp` node.
3045 >>> import astroid
3046 >>> node = astroid.extract_node('value if condition else other')
3047 >>> node
3048 <IfExp l.1 at 0x...>
3049 """
3050
3051 _astroid_fields = ("test", "body", "orelse")
3052
3053 test: NodeNG
3054 """The condition that the statement tests."""
3055
3056 body: NodeNG
3057 """The contents of the block."""
3058
3059 orelse: NodeNG
3060 """The contents of the ``else`` block."""
3061
3062 def postinit(self, test: NodeNG, body: NodeNG, orelse: NodeNG) -> None:
3063 self.test = test
3064 self.body = body
3065 self.orelse = orelse
3066
3067 def get_children(self):
3068 yield self.test
3069 yield self.body
3070 yield self.orelse
3071
3072 def op_left_associative(self) -> Literal[False]:
3073 # `1 if True else 2 if False else 3` is parsed as
3074 # `1 if True else (2 if False else 3)`
3075 return False
3076
3077 @decorators.raise_if_nothing_inferred
3078 def _infer(
3079 self, context: InferenceContext | None = None
3080 ) -> Generator[InferenceResult]:
3081 """Support IfExp inference.
3082
3083 If we can't infer the truthiness of the condition, we default
3084 to inferring both branches. Otherwise, we infer either branch
3085 depending on the condition.
3086 """
3087
3088 # We use two separate contexts for evaluating lhs and rhs because
3089 # evaluating lhs may leave some undesired entries in context.path
3090 # which may not let us infer right value of rhs.
3091 context = context or InferenceContext()
3092 lhs_context = copy_context(context)
3093 rhs_context = copy_context(context)
3094
3095 # Infer bool condition. Stop inferring if in doubt and fallback to
3096 # evaluating both branches.
3097 condition: bool | None = None
3098 try:
3099 for test in self.test.infer(context=context.clone()):
3100 if isinstance(test, util.UninferableBase):
3101 condition = None
3102 break
3103 test_bool_value = test.bool_value()
3104 if isinstance(test_bool_value, util.UninferableBase):
3105 condition = None
3106 break
3107 if condition is None:
3108 condition = test_bool_value
3109 elif test_bool_value != condition:
3110 condition = None
3111 break
3112 except InferenceError:
3113 condition = None
3114
3115 if condition is True or condition is None:
3116 yield from self.body.infer(context=lhs_context)
3117 if condition is False or condition is None:
3118 yield from self.orelse.infer(context=rhs_context)
3119
3120
3121class Import(_base_nodes.ImportNode):
3122 """Class representing an :class:`ast.Import` node.
3123 >>> import astroid
3124 >>> node = astroid.extract_node('import astroid')
3125 >>> node
3126 <Import l.1 at 0x...>
3127 """
3128
3129 _other_fields = ("names", "is_lazy")
3130
3131 def __init__(
3132 self,
3133 names: list[tuple[str, str | None]],
3134 lineno: int | None = None,
3135 col_offset: int | None = None,
3136 parent: NodeNG | None = None,
3137 *,
3138 end_lineno: int | None = None,
3139 end_col_offset: int | None = None,
3140 is_lazy: int = 0,
3141 ) -> None:
3142 """
3143 :param names: The names being imported.
3144
3145 :param is_lazy: Whether this is a PEP 810 lazy import (``lazy import ...``).
3146
3147 :param lineno: The line that this node appears on in the source code.
3148
3149 :param col_offset: The column that this node appears on in the
3150 source code.
3151
3152 :param parent: The parent node in the syntax tree.
3153
3154 :param end_lineno: The last line this node appears on in the source code.
3155
3156 :param end_col_offset: The end column this node appears on in the
3157 source code. Note: This is after the last symbol.
3158 """
3159 self.names: list[tuple[str, str | None]] = names
3160 """The names being imported.
3161
3162 Each entry is a :class:`tuple` of the name being imported,
3163 and the alias that the name is assigned to (if any).
3164 """
3165
3166 self.is_lazy: int = is_lazy
3167 """Whether this is a PEP 810 lazy import (``lazy import ...``).
3168
3169 Always ``0`` before Python 3.15.
3170 """
3171
3172 super().__init__(
3173 lineno=lineno,
3174 col_offset=col_offset,
3175 end_lineno=end_lineno,
3176 end_col_offset=end_col_offset,
3177 parent=parent,
3178 )
3179
3180 @decorators.raise_if_nothing_inferred
3181 @decorators.path_wrapper
3182 def _infer(
3183 self,
3184 context: InferenceContext | None = None,
3185 ) -> Generator[nodes.Module]:
3186 """Infer an Import node: return the imported module/object."""
3187 context = context or InferenceContext()
3188 name = context.lookupname
3189 if name is None:
3190 raise InferenceError(node=self, context=context)
3191
3192 try:
3193 yield self.do_import_module(name)
3194 except AstroidBuildingError as exc:
3195 raise InferenceError(node=self, context=context) from exc
3196
3197
3198class Keyword(NodeNG):
3199 """Class representing an :class:`ast.keyword` node.
3200
3201 >>> import astroid
3202 >>> node = astroid.extract_node('function(a_kwarg=True)')
3203 >>> node
3204 <Call l.1 at 0x...>
3205 >>> node.keywords
3206 [<Keyword l.1 at 0x...>]
3207 """
3208
3209 _astroid_fields = ("value",)
3210 _other_fields = ("arg",)
3211
3212 value: NodeNG
3213 """The value being assigned to the keyword argument."""
3214
3215 def __init__(
3216 self,
3217 arg: str | None,
3218 lineno: int | None,
3219 col_offset: int | None,
3220 parent: NodeNG,
3221 *,
3222 end_lineno: int | None,
3223 end_col_offset: int | None,
3224 ) -> None:
3225 self.arg = arg
3226 """The argument being assigned to."""
3227
3228 super().__init__(
3229 lineno=lineno,
3230 col_offset=col_offset,
3231 end_lineno=end_lineno,
3232 end_col_offset=end_col_offset,
3233 parent=parent,
3234 )
3235
3236 def postinit(self, value: NodeNG) -> None:
3237 self.value = value
3238
3239 def get_children(self):
3240 yield self.value
3241
3242
3243class List(BaseContainer):
3244 """Class representing an :class:`ast.List` node.
3245
3246 >>> import astroid
3247 >>> node = astroid.extract_node('[1, 2, 3]')
3248 >>> node
3249 <List.list l.1 at 0x...>
3250 """
3251
3252 _other_fields = ("ctx",)
3253
3254 def __init__(
3255 self,
3256 ctx: Context | None = None,
3257 lineno: int | None = None,
3258 col_offset: int | None = None,
3259 parent: NodeNG | None = None,
3260 *,
3261 end_lineno: int | None = None,
3262 end_col_offset: int | None = None,
3263 ) -> None:
3264 """
3265 :param ctx: Whether the list is assigned to or loaded from.
3266
3267 :param lineno: The line that this node appears on in the source code.
3268
3269 :param col_offset: The column that this node appears on in the
3270 source code.
3271
3272 :param parent: The parent node in the syntax tree.
3273
3274 :param end_lineno: The last line this node appears on in the source code.
3275
3276 :param end_col_offset: The end column this node appears on in the
3277 source code. Note: This is after the last symbol.
3278 """
3279 self.ctx: Context | None = ctx
3280 """Whether the list is assigned to or loaded from."""
3281
3282 super().__init__(
3283 lineno=lineno,
3284 col_offset=col_offset,
3285 end_lineno=end_lineno,
3286 end_col_offset=end_col_offset,
3287 parent=parent,
3288 )
3289
3290 assigned_stmts = protocols.sequence_assigned_stmts
3291 """Returns the assigned statement (non inferred) according to the assignment type.
3292 See astroid/protocols.py for actual implementation.
3293 """
3294
3295 infer_unary_op = protocols.list_infer_unary_op
3296 infer_binary_op = protocols.tl_infer_binary_op
3297
3298 def pytype(self) -> Literal["builtins.list"]:
3299 """Get the name of the type that this node represents.
3300
3301 :returns: The name of the type.
3302 """
3303 return "builtins.list"
3304
3305 def getitem(
3306 self, index: SuccessfulInferenceResult, context: InferenceContext | None = None
3307 ) -> InferenceResult:
3308 """Get an item from this node.
3309
3310 :param index: The node to use as a subscript index.
3311 """
3312 return _container_getitem(self, self.elts, index, context=context)
3313
3314
3315class Nonlocal(_base_nodes.NoChildrenNode, _base_nodes.Statement):
3316 """Class representing an :class:`ast.Nonlocal` node.
3317
3318 >>> import astroid
3319 >>> node = astroid.extract_node('''
3320 ... def function():
3321 ... nonlocal var
3322 ... ''')
3323 >>> node
3324 <FunctionDef.function l.2 at 0x...>
3325 >>> node.body[0]
3326 <Nonlocal l.3 at 0x...>
3327 """
3328
3329 _other_fields = ("names",)
3330
3331 def __init__(
3332 self,
3333 names: list[str],
3334 lineno: int | None = None,
3335 col_offset: int | None = None,
3336 parent: NodeNG | None = None,
3337 *,
3338 end_lineno: int | None = None,
3339 end_col_offset: int | None = None,
3340 ) -> None:
3341 """
3342 :param names: The names being declared as not local.
3343
3344 :param lineno: The line that this node appears on in the source code.
3345
3346 :param col_offset: The column that this node appears on in the
3347 source code.
3348
3349 :param parent: The parent node in the syntax tree.
3350
3351 :param end_lineno: The last line this node appears on in the source code.
3352
3353 :param end_col_offset: The end column this node appears on in the
3354 source code. Note: This is after the last symbol.
3355 """
3356 self.names: list[str] = names
3357 """The names being declared as not local."""
3358
3359 super().__init__(
3360 lineno=lineno,
3361 col_offset=col_offset,
3362 end_lineno=end_lineno,
3363 end_col_offset=end_col_offset,
3364 parent=parent,
3365 )
3366
3367 def _infer_name(self, frame, name):
3368 return name
3369
3370
3371class ParamSpec(_base_nodes.AssignTypeNode):
3372 """Class representing a :class:`ast.ParamSpec` node.
3373
3374 >>> import astroid
3375 >>> node = astroid.extract_node('type Alias[**P] = Callable[P, int]')
3376 >>> node.type_params[0]
3377 <ParamSpec l.1 at 0x...>
3378 """
3379
3380 _astroid_fields = ("name", "default_value")
3381 name: AssignName
3382 default_value: NodeNG | None
3383
3384 def __init__(
3385 self,
3386 lineno: int,
3387 col_offset: int,
3388 parent: NodeNG,
3389 *,
3390 end_lineno: int,
3391 end_col_offset: int,
3392 ) -> None:
3393 super().__init__(
3394 lineno=lineno,
3395 col_offset=col_offset,
3396 end_lineno=end_lineno,
3397 end_col_offset=end_col_offset,
3398 parent=parent,
3399 )
3400
3401 def postinit(self, *, name: AssignName, default_value: NodeNG | None) -> None:
3402 self.name = name
3403 self.default_value = default_value
3404
3405 def pytype(self) -> Literal["typing.ParamSpec"]:
3406 """Get the name of the type that this node represents.
3407
3408 :returns: The name of the type.
3409 """
3410 return "typing.ParamSpec"
3411
3412 def qname(self) -> Literal["typing.ParamSpec"]:
3413 """Get the qualified name of the type that this node represents.
3414
3415 :returns: The qualified name of the type.
3416 """
3417 return "typing.ParamSpec"
3418
3419 def _infer(self, context: InferenceContext | None = None) -> Iterator[ParamSpec]:
3420 yield self
3421
3422 assigned_stmts = protocols.generic_type_assigned_stmts
3423 """Returns the assigned statement (non inferred) according to the assignment type.
3424 See astroid/protocols.py for actual implementation.
3425 """
3426
3427
3428class Pass(_base_nodes.NoChildrenNode, _base_nodes.Statement):
3429 """Class representing an :class:`ast.Pass` node.
3430
3431 >>> import astroid
3432 >>> node = astroid.extract_node('pass')
3433 >>> node
3434 <Pass l.1 at 0x...>
3435 """
3436
3437
3438class Raise(_base_nodes.Statement):
3439 """Class representing an :class:`ast.Raise` node.
3440
3441 >>> import astroid
3442 >>> node = astroid.extract_node('raise RuntimeError("Something bad happened!")')
3443 >>> node
3444 <Raise l.1 at 0x...>
3445 """
3446
3447 _astroid_fields = ("exc", "cause")
3448
3449 exc: NodeNG | None
3450 """What is being raised."""
3451
3452 cause: NodeNG | None
3453 """The exception being used to raise this one."""
3454
3455 def postinit(
3456 self,
3457 exc: NodeNG | None,
3458 cause: NodeNG | None,
3459 ) -> None:
3460 self.exc = exc
3461 self.cause = cause
3462
3463 def raises_not_implemented(self) -> bool:
3464 """Check if this node raises a :class:`NotImplementedError`.
3465
3466 :returns: Whether this node raises a :class:`NotImplementedError`.
3467 """
3468 if not self.exc:
3469 return False
3470 return any(
3471 name.name == "NotImplementedError" for name in self.exc._get_name_nodes()
3472 )
3473
3474 def get_children(self):
3475 if self.exc is not None:
3476 yield self.exc
3477
3478 if self.cause is not None:
3479 yield self.cause
3480
3481
3482class Return(_base_nodes.Statement):
3483 """Class representing an :class:`ast.Return` node.
3484
3485 >>> import astroid
3486 >>> node = astroid.extract_node('return True')
3487 >>> node
3488 <Return l.1 at 0x...>
3489 """
3490
3491 _astroid_fields = ("value",)
3492
3493 value: NodeNG | None
3494 """The value being returned."""
3495
3496 def postinit(self, value: NodeNG | None) -> None:
3497 self.value = value
3498
3499 def get_children(self):
3500 if self.value is not None:
3501 yield self.value
3502
3503 def is_tuple_return(self) -> bool:
3504 return isinstance(self.value, Tuple)
3505
3506 def _get_return_nodes_skip_functions(self):
3507 yield self
3508
3509
3510class Set(BaseContainer):
3511 """Class representing an :class:`ast.Set` node.
3512
3513 >>> import astroid
3514 >>> node = astroid.extract_node('{1, 2, 3}')
3515 >>> node
3516 <Set.set l.1 at 0x...>
3517 """
3518
3519 infer_unary_op = protocols.set_infer_unary_op
3520
3521 def pytype(self) -> Literal["builtins.set"]:
3522 """Get the name of the type that this node represents.
3523
3524 :returns: The name of the type.
3525 """
3526 return "builtins.set"
3527
3528
3529class Slice(NodeNG):
3530 """Class representing an :class:`ast.Slice` node.
3531
3532 >>> import astroid
3533 >>> node = astroid.extract_node('things[1:3]')
3534 >>> node
3535 <Subscript l.1 at 0x...>
3536 >>> node.slice
3537 <Slice.slice l.1 at 0x...>
3538 """
3539
3540 _astroid_fields = ("lower", "upper", "step")
3541
3542 lower: NodeNG | None
3543 """The lower index in the slice."""
3544
3545 upper: NodeNG | None
3546 """The upper index in the slice."""
3547
3548 step: NodeNG | None
3549 """The step to take between indexes."""
3550
3551 def postinit(
3552 self,
3553 lower: NodeNG | None,
3554 upper: NodeNG | None,
3555 step: NodeNG | None,
3556 ) -> None:
3557 self.lower = lower
3558 self.upper = upper
3559 self.step = step
3560
3561 def _wrap_attribute(self, attr):
3562 """Wrap the empty attributes of the Slice in a Const node."""
3563 if not attr:
3564 const = const_factory(attr)
3565 const.parent = self
3566 return const
3567 return attr
3568
3569 @cached_property
3570 def _proxied(self) -> nodes.ClassDef:
3571 builtins = AstroidManager().builtins_module
3572 return builtins.getattr("slice")[0]
3573
3574 def pytype(self) -> Literal["builtins.slice"]:
3575 """Get the name of the type that this node represents.
3576
3577 :returns: The name of the type.
3578 """
3579 return "builtins.slice"
3580
3581 def qname(self) -> Literal["builtins.slice"]:
3582 """Get the qualified name of the type that this node represents.
3583
3584 :returns: The qualified name of the type.
3585 """
3586 return "builtins.slice"
3587
3588 @property
3589 def name(self) -> Literal["slice"]:
3590 """The name of the type that this node represents.
3591
3592 Inferred builtin values such as ``Const`` or ``List`` expose the name
3593 of their type through ``Instance``; a ``Slice`` is not an ``Instance``,
3594 so it gives the name of ``builtins.slice`` explicitly.
3595 """
3596 return "slice"
3597
3598 def display_type(self) -> Literal["Slice"]:
3599 """A human readable type of this node.
3600
3601 :returns: The type of this node.
3602 """
3603 return "Slice"
3604
3605 def igetattr(
3606 self, attrname: str, context: InferenceContext | None = None
3607 ) -> Iterator[SuccessfulInferenceResult]:
3608 """Infer the possible values of the given attribute on the slice.
3609
3610 :param attrname: The name of the attribute to infer.
3611
3612 :returns: The inferred possible values.
3613 """
3614 if attrname == "start":
3615 yield self._wrap_attribute(self.lower)
3616 elif attrname == "stop":
3617 yield self._wrap_attribute(self.upper)
3618 elif attrname == "step":
3619 yield self._wrap_attribute(self.step)
3620 else:
3621 yield from self.getattr(attrname, context=context)
3622
3623 def getattr(self, attrname, context: InferenceContext | None = None):
3624 return self._proxied.getattr(attrname, context)
3625
3626 def get_children(self):
3627 if self.lower is not None:
3628 yield self.lower
3629
3630 if self.upper is not None:
3631 yield self.upper
3632
3633 if self.step is not None:
3634 yield self.step
3635
3636 def _infer(self, context: InferenceContext | None = None) -> Iterator[Slice]:
3637 yield self
3638
3639
3640class Starred(_base_nodes.ParentAssignNode):
3641 """Class representing an :class:`ast.Starred` node.
3642
3643 >>> import astroid
3644 >>> node = astroid.extract_node('*args')
3645 >>> node
3646 <Starred l.1 at 0x...>
3647 """
3648
3649 _astroid_fields = ("value",)
3650 _other_fields = ("ctx",)
3651
3652 value: NodeNG
3653 """What is being unpacked."""
3654
3655 def __init__(
3656 self,
3657 ctx: Context,
3658 lineno: int,
3659 col_offset: int,
3660 parent: NodeNG,
3661 *,
3662 end_lineno: int | None,
3663 end_col_offset: int | None,
3664 ) -> None:
3665 self.ctx = ctx
3666 """Whether the starred item is assigned to or loaded from."""
3667
3668 super().__init__(
3669 lineno=lineno,
3670 col_offset=col_offset,
3671 end_lineno=end_lineno,
3672 end_col_offset=end_col_offset,
3673 parent=parent,
3674 )
3675
3676 def postinit(self, value: NodeNG) -> None:
3677 self.value = value
3678
3679 assigned_stmts = protocols.starred_assigned_stmts
3680 """Returns the assigned statement (non inferred) according to the assignment type.
3681 See astroid/protocols.py for actual implementation.
3682 """
3683
3684 def get_children(self):
3685 yield self.value
3686
3687
3688class Subscript(NodeNG):
3689 """Class representing an :class:`ast.Subscript` node.
3690
3691 >>> import astroid
3692 >>> node = astroid.extract_node('things[1:3]')
3693 >>> node
3694 <Subscript l.1 at 0x...>
3695 """
3696
3697 _SUBSCRIPT_SENTINEL = object()
3698 _astroid_fields = ("value", "slice")
3699 _other_fields = ("ctx",)
3700
3701 value: NodeNG
3702 """What is being indexed."""
3703
3704 slice: NodeNG
3705 """The slice being used to lookup."""
3706
3707 def __init__(
3708 self,
3709 ctx: Context,
3710 lineno: int,
3711 col_offset: int,
3712 parent: NodeNG,
3713 *,
3714 end_lineno: int | None,
3715 end_col_offset: int | None,
3716 ) -> None:
3717 self.ctx = ctx
3718 """Whether the subscripted item is assigned to or loaded from."""
3719
3720 super().__init__(
3721 lineno=lineno,
3722 col_offset=col_offset,
3723 end_lineno=end_lineno,
3724 end_col_offset=end_col_offset,
3725 parent=parent,
3726 )
3727
3728 # pylint: disable=redefined-builtin; had to use the same name as builtin ast module.
3729 def postinit(self, value: NodeNG, slice: NodeNG) -> None:
3730 self.value = value
3731 self.slice = slice
3732
3733 def get_children(self):
3734 yield self.value
3735 yield self.slice
3736
3737 def _infer_subscript(
3738 self, context: InferenceContext | None = None
3739 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
3740 """Inference for subscripts.
3741
3742 We're understanding if the index is a Const
3743 or a slice, passing the result of inference
3744 to the value's `getitem` method, which should
3745 handle each supported index type accordingly.
3746 """
3747 # pylint: disable-next=import-outside-toplevel
3748 from astroid import helpers
3749 from astroid.nodes import ClassDef # pylint: disable=import-outside-toplevel
3750
3751 found_one = False
3752 for value in self.value.infer(context):
3753 if isinstance(value, util.UninferableBase):
3754 yield util.Uninferable
3755 return None
3756 for index in self.slice.infer(context):
3757 if isinstance(index, util.UninferableBase):
3758 yield util.Uninferable
3759 return None
3760
3761 # Try to deduce the index value.
3762 index_value = self._SUBSCRIPT_SENTINEL
3763 if value.__class__ == Instance:
3764 index_value = index
3765 elif index.__class__ == Instance:
3766 instance_as_index = helpers.class_instance_as_index(index)
3767 if instance_as_index:
3768 index_value = instance_as_index
3769 elif isinstance(value, ClassDef):
3770 # Subscripting a class, e.g. ``Container[Alias]``,
3771 # takes the index as a type argument, not as an integer.
3772 index_value = index
3773 else:
3774 index_value = index
3775
3776 if index_value is self._SUBSCRIPT_SENTINEL:
3777 raise InferenceError(node=self, context=context)
3778
3779 try:
3780 assigned = value.getitem(index_value, context)
3781 except (
3782 AstroidTypeError,
3783 AstroidIndexError,
3784 AstroidValueError,
3785 AttributeInferenceError,
3786 AttributeError,
3787 ) as exc:
3788 raise InferenceError(node=self, context=context) from exc
3789
3790 # Prevent inferring if the inferred subscript
3791 # is the same as the original subscripted object.
3792 if self is assigned or isinstance(assigned, util.UninferableBase):
3793 yield util.Uninferable
3794 return None
3795 yield from assigned.infer(context)
3796 found_one = True
3797
3798 if found_one:
3799 return InferenceErrorInfo(node=self, context=context)
3800 return None
3801
3802 @decorators.raise_if_nothing_inferred
3803 @decorators.path_wrapper
3804 def _infer(self, context: InferenceContext | None = None):
3805 return self._infer_subscript(context)
3806
3807 @decorators.raise_if_nothing_inferred
3808 def infer_lhs(self, context: InferenceContext | None = None):
3809 return self._infer_subscript(context)
3810
3811
3812class Try(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
3813 """Class representing a :class:`ast.Try` node.
3814
3815 >>> import astroid
3816 >>> node = astroid.extract_node('''
3817 ... try:
3818 ... do_something()
3819 ... except Exception as error:
3820 ... print("Error!")
3821 ... finally:
3822 ... print("Cleanup!")
3823 ... ''')
3824 >>> node
3825 <Try l.2 at 0x...>
3826 """
3827
3828 _astroid_fields = ("body", "handlers", "orelse", "finalbody")
3829 _multi_line_block_fields = ("body", "handlers", "orelse", "finalbody")
3830
3831 def __init__(
3832 self,
3833 *,
3834 lineno: int,
3835 col_offset: int,
3836 end_lineno: int,
3837 end_col_offset: int,
3838 parent: NodeNG,
3839 ) -> None:
3840 """
3841 :param lineno: The line that this node appears on in the source code.
3842
3843 :param col_offset: The column that this node appears on in the
3844 source code.
3845
3846 :param parent: The parent node in the syntax tree.
3847
3848 :param end_lineno: The last line this node appears on in the source code.
3849
3850 :param end_col_offset: The end column this node appears on in the
3851 source code. Note: This is after the last symbol.
3852 """
3853 self.body: list[NodeNG] = []
3854 """The contents of the block to catch exceptions from."""
3855
3856 self.handlers: list[ExceptHandler] = []
3857 """The exception handlers."""
3858
3859 self.orelse: list[NodeNG] = []
3860 """The contents of the ``else`` block."""
3861
3862 self.finalbody: list[NodeNG] = []
3863 """The contents of the ``finally`` block."""
3864
3865 super().__init__(
3866 lineno=lineno,
3867 col_offset=col_offset,
3868 end_lineno=end_lineno,
3869 end_col_offset=end_col_offset,
3870 parent=parent,
3871 )
3872
3873 def postinit(
3874 self,
3875 *,
3876 body: list[NodeNG],
3877 handlers: list[ExceptHandler],
3878 orelse: list[NodeNG],
3879 finalbody: list[NodeNG],
3880 ) -> None:
3881 """Do some setup after initialisation.
3882
3883 :param body: The contents of the block to catch exceptions from.
3884
3885 :param handlers: The exception handlers.
3886
3887 :param orelse: The contents of the ``else`` block.
3888
3889 :param finalbody: The contents of the ``finally`` block.
3890 """
3891 self.body = body
3892 self.handlers = handlers
3893 self.orelse = orelse
3894 self.finalbody = finalbody
3895
3896 def _infer_name(self, frame, name):
3897 return name
3898
3899 def block_range(self, lineno: int) -> tuple[int, int]:
3900 """Get a range from a given line number to where this node ends."""
3901 for exhandler in self.handlers:
3902 if exhandler.type and lineno == exhandler.type.fromlineno:
3903 return lineno, exhandler.tolineno
3904 if exhandler.body[0].fromlineno <= lineno <= exhandler.body[-1].tolineno:
3905 return lineno, exhandler.body[-1].tolineno
3906 if self.finalbody:
3907 if self.finalbody[0].fromlineno - 1 == lineno:
3908 return lineno, self.finalbody[0].tolineno
3909 if self.finalbody[0].fromlineno <= lineno <= self.finalbody[-1].tolineno:
3910 return lineno, self.finalbody[-1].tolineno
3911
3912 # If not within any of the ExceptHandlers or `finally` body, fall back to regular
3913 # handling of block_range for nodes with a potential `else` statement.
3914 return super().block_range(lineno)
3915
3916 def get_children(self):
3917 yield from self.body
3918 yield from self.handlers
3919 yield from self.orelse
3920 yield from self.finalbody
3921
3922
3923class TryStar(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
3924 """Class representing an :class:`ast.TryStar` node."""
3925
3926 _astroid_fields = ("body", "handlers", "orelse", "finalbody")
3927 _multi_line_block_fields = ("body", "handlers", "orelse", "finalbody")
3928
3929 def __init__(
3930 self,
3931 *,
3932 lineno: int | None = None,
3933 col_offset: int | None = None,
3934 end_lineno: int | None = None,
3935 end_col_offset: int | None = None,
3936 parent: NodeNG | None = None,
3937 ) -> None:
3938 """
3939 :param lineno: The line that this node appears on in the source code.
3940 :param col_offset: The column that this node appears on in the
3941 source code.
3942 :param parent: The parent node in the syntax tree.
3943 :param end_lineno: The last line this node appears on in the source code.
3944 :param end_col_offset: The end column this node appears on in the
3945 source code. Note: This is after the last symbol.
3946 """
3947 self.body: list[NodeNG] = []
3948 """The contents of the block to catch exceptions from."""
3949
3950 self.handlers: list[ExceptHandler] = []
3951 """The exception handlers."""
3952
3953 self.orelse: list[NodeNG] = []
3954 """The contents of the ``else`` block."""
3955
3956 self.finalbody: list[NodeNG] = []
3957 """The contents of the ``finally`` block."""
3958
3959 super().__init__(
3960 lineno=lineno,
3961 col_offset=col_offset,
3962 end_lineno=end_lineno,
3963 end_col_offset=end_col_offset,
3964 parent=parent,
3965 )
3966
3967 def postinit(
3968 self,
3969 *,
3970 body: list[NodeNG] | None = None,
3971 handlers: list[ExceptHandler] | None = None,
3972 orelse: list[NodeNG] | None = None,
3973 finalbody: list[NodeNG] | None = None,
3974 ) -> None:
3975 """Do some setup after initialisation.
3976 :param body: The contents of the block to catch exceptions from.
3977 :param handlers: The exception handlers.
3978 :param orelse: The contents of the ``else`` block.
3979 :param finalbody: The contents of the ``finally`` block.
3980 """
3981 if body:
3982 self.body = body
3983 if handlers:
3984 self.handlers = handlers
3985 if orelse:
3986 self.orelse = orelse
3987 if finalbody:
3988 self.finalbody = finalbody
3989
3990 def _infer_name(self, frame, name):
3991 return name
3992
3993 def get_children(self):
3994 yield from self.body
3995 yield from self.handlers
3996 yield from self.orelse
3997 yield from self.finalbody
3998
3999 def block_range(self, lineno: int) -> tuple[int, int]:
4000 """Get a range from a given line number to where this node ends."""
4001 for exhandler in self.handlers:
4002 if exhandler.type and lineno == exhandler.type.fromlineno:
4003 return lineno, exhandler.tolineno
4004 if exhandler.body[0].fromlineno <= lineno <= exhandler.body[-1].tolineno:
4005 return lineno, exhandler.body[-1].tolineno
4006 if self.finalbody:
4007 if self.finalbody[0].fromlineno - 1 == lineno:
4008 return lineno, self.finalbody[0].tolineno
4009 if self.finalbody[0].fromlineno <= lineno <= self.finalbody[-1].tolineno:
4010 return lineno, self.finalbody[-1].tolineno
4011
4012 # If not within any of the ExceptHandlers or `finally` body, fall back to regular
4013 # handling of block_range for nodes with a potential `else` statement.
4014 return super().block_range(lineno)
4015
4016
4017class Tuple(BaseContainer):
4018 """Class representing an :class:`ast.Tuple` node.
4019
4020 >>> import astroid
4021 >>> node = astroid.extract_node('(1, 2, 3)')
4022 >>> node
4023 <Tuple.tuple l.1 at 0x...>
4024 """
4025
4026 _other_fields = ("ctx",)
4027
4028 def __init__(
4029 self,
4030 ctx: Context | None = None,
4031 lineno: int | None = None,
4032 col_offset: int | None = None,
4033 parent: NodeNG | None = None,
4034 *,
4035 end_lineno: int | None = None,
4036 end_col_offset: int | None = None,
4037 ) -> None:
4038 """
4039 :param ctx: Whether the tuple is assigned to or loaded from.
4040
4041 :param lineno: The line that this node appears on in the source code.
4042
4043 :param col_offset: The column that this node appears on in the
4044 source code.
4045
4046 :param parent: The parent node in the syntax tree.
4047
4048 :param end_lineno: The last line this node appears on in the source code.
4049
4050 :param end_col_offset: The end column this node appears on in the
4051 source code. Note: This is after the last symbol.
4052 """
4053 self.ctx: Context | None = ctx
4054 """Whether the tuple is assigned to or loaded from."""
4055
4056 super().__init__(
4057 lineno=lineno,
4058 col_offset=col_offset,
4059 end_lineno=end_lineno,
4060 end_col_offset=end_col_offset,
4061 parent=parent,
4062 )
4063
4064 assigned_stmts = protocols.sequence_assigned_stmts
4065 """Returns the assigned statement (non inferred) according to the assignment type.
4066 See astroid/protocols.py for actual implementation.
4067 """
4068
4069 infer_unary_op = protocols.tuple_infer_unary_op
4070 infer_binary_op = protocols.tl_infer_binary_op
4071
4072 def pytype(self) -> Literal["builtins.tuple"]:
4073 """Get the name of the type that this node represents.
4074
4075 :returns: The name of the type.
4076 """
4077 return "builtins.tuple"
4078
4079 def getitem(
4080 self, index: SuccessfulInferenceResult, context: InferenceContext | None = None
4081 ) -> InferenceResult:
4082 """Get an item from this node.
4083
4084 :param index: The node to use as a subscript index.
4085 """
4086 return _container_getitem(self, self.elts, index, context=context)
4087
4088
4089class TypeAlias(_base_nodes.AssignTypeNode, _base_nodes.Statement):
4090 """Class representing a :class:`ast.TypeAlias` node.
4091
4092 >>> import astroid
4093 >>> node = astroid.extract_node('type Point = tuple[float, float]')
4094 >>> node
4095 <TypeAlias l.1 at 0x...>
4096 """
4097
4098 _astroid_fields = ("name", "type_params", "value")
4099
4100 name: AssignName
4101 type_params: list[TypeVar | ParamSpec | TypeVarTuple]
4102 value: NodeNG
4103
4104 def __init__(
4105 self,
4106 lineno: int,
4107 col_offset: int,
4108 parent: NodeNG,
4109 *,
4110 end_lineno: int,
4111 end_col_offset: int,
4112 ) -> None:
4113 super().__init__(
4114 lineno=lineno,
4115 col_offset=col_offset,
4116 end_lineno=end_lineno,
4117 end_col_offset=end_col_offset,
4118 parent=parent,
4119 )
4120
4121 def postinit(
4122 self,
4123 *,
4124 name: AssignName,
4125 type_params: list[TypeVar | ParamSpec | TypeVarTuple],
4126 value: NodeNG,
4127 ) -> None:
4128 self.name = name
4129 self.type_params = type_params
4130 self.value = value
4131
4132 def pytype(self) -> Literal["typing.TypeAliasType"]:
4133 """Get the name of the type that this node represents.
4134
4135 :returns: The name of the type.
4136 """
4137 return "typing.TypeAliasType"
4138
4139 def qname(self) -> Literal["typing.TypeAliasType"]:
4140 """Get the qualified name of the type that this node represents.
4141
4142 :returns: The qualified name of the type.
4143 """
4144 return "typing.TypeAliasType"
4145
4146 def _infer(self, context: InferenceContext | None = None) -> Iterator[TypeAlias]:
4147 yield self
4148
4149 assigned_stmts: ClassVar[
4150 Callable[
4151 [
4152 TypeAlias,
4153 AssignName,
4154 InferenceContext | None,
4155 None,
4156 ],
4157 Generator[NodeNG],
4158 ]
4159 ] = protocols.type_alias_assigned_stmts
4160
4161
4162class TypeVar(_base_nodes.AssignTypeNode):
4163 """Class representing a :class:`ast.TypeVar` node.
4164
4165 >>> import astroid
4166 >>> node = astroid.extract_node('type Point[T] = tuple[float, float]')
4167 >>> node.type_params[0]
4168 <TypeVar l.1 at 0x...>
4169 """
4170
4171 _astroid_fields = ("name", "bound", "default_value")
4172 name: AssignName
4173 bound: NodeNG | None
4174 default_value: NodeNG | None
4175
4176 def __init__(
4177 self,
4178 lineno: int,
4179 col_offset: int,
4180 parent: NodeNG,
4181 *,
4182 end_lineno: int,
4183 end_col_offset: int,
4184 ) -> None:
4185 super().__init__(
4186 lineno=lineno,
4187 col_offset=col_offset,
4188 end_lineno=end_lineno,
4189 end_col_offset=end_col_offset,
4190 parent=parent,
4191 )
4192
4193 def postinit(
4194 self,
4195 *,
4196 name: AssignName,
4197 bound: NodeNG | None,
4198 default_value: NodeNG | None = None,
4199 ) -> None:
4200 self.name = name
4201 self.bound = bound
4202 self.default_value = default_value
4203
4204 def pytype(self) -> Literal["typing.TypeVar"]:
4205 """Get the name of the type that this node represents.
4206
4207 :returns: The name of the type.
4208 """
4209 return "typing.TypeVar"
4210
4211 def qname(self) -> Literal["typing.TypeVar"]:
4212 """Get the qualified name of the type that this node represents.
4213
4214 :returns: The qualified name of the type.
4215 """
4216 return "typing.TypeVar"
4217
4218 def _infer(self, context: InferenceContext | None = None) -> Iterator[TypeVar]:
4219 yield self
4220
4221 assigned_stmts = protocols.generic_type_assigned_stmts
4222 """Returns the assigned statement (non inferred) according to the assignment type.
4223 See astroid/protocols.py for actual implementation.
4224 """
4225
4226
4227class TypeVarTuple(_base_nodes.AssignTypeNode):
4228 """Class representing a :class:`ast.TypeVarTuple` node.
4229
4230 >>> import astroid
4231 >>> node = astroid.extract_node('type Alias[*Ts] = tuple[*Ts]')
4232 >>> node.type_params[0]
4233 <TypeVarTuple l.1 at 0x...>
4234 """
4235
4236 _astroid_fields = ("name", "default_value")
4237 name: AssignName
4238 default_value: NodeNG | None
4239
4240 def __init__(
4241 self,
4242 lineno: int,
4243 col_offset: int,
4244 parent: NodeNG,
4245 *,
4246 end_lineno: int,
4247 end_col_offset: int,
4248 ) -> None:
4249 super().__init__(
4250 lineno=lineno,
4251 col_offset=col_offset,
4252 end_lineno=end_lineno,
4253 end_col_offset=end_col_offset,
4254 parent=parent,
4255 )
4256
4257 def postinit(
4258 self, *, name: AssignName, default_value: NodeNG | None = None
4259 ) -> None:
4260 self.name = name
4261 self.default_value = default_value
4262
4263 def pytype(self) -> Literal["typing.TypeVarTuple"]:
4264 """Get the name of the type that this node represents.
4265
4266 :returns: The name of the type.
4267 """
4268 return "typing.TypeVarTuple"
4269
4270 def qname(self) -> Literal["typing.TypeVarTuple"]:
4271 """Get the qualified name of the type that this node represents.
4272
4273 :returns: The qualified name of the type.
4274 """
4275 return "typing.TypeVarTuple"
4276
4277 def _infer(self, context: InferenceContext | None = None) -> Iterator[TypeVarTuple]:
4278 yield self
4279
4280 assigned_stmts = protocols.generic_type_assigned_stmts
4281 """Returns the assigned statement (non inferred) according to the assignment type.
4282 See astroid/protocols.py for actual implementation.
4283 """
4284
4285
4286UNARY_OP_METHOD = {
4287 "+": "__pos__",
4288 "-": "__neg__",
4289 "~": "__invert__",
4290 "not": None, # 'not' delegates to __bool__, there is no dedicated method
4291}
4292
4293
4294class UnaryOp(_base_nodes.OperatorNode):
4295 """Class representing an :class:`ast.UnaryOp` node.
4296
4297 >>> import astroid
4298 >>> node = astroid.extract_node('-5')
4299 >>> node
4300 <UnaryOp l.1 at 0x...>
4301 """
4302
4303 _astroid_fields = ("operand",)
4304 _other_fields = ("op",)
4305
4306 operand: NodeNG
4307 """What the unary operator is applied to."""
4308
4309 def __init__(
4310 self,
4311 op: str,
4312 lineno: int,
4313 col_offset: int,
4314 parent: NodeNG,
4315 *,
4316 end_lineno: int | None,
4317 end_col_offset: int | None,
4318 ) -> None:
4319 self.op = op
4320 """The operator."""
4321
4322 super().__init__(
4323 lineno=lineno,
4324 col_offset=col_offset,
4325 end_lineno=end_lineno,
4326 end_col_offset=end_col_offset,
4327 parent=parent,
4328 )
4329
4330 def postinit(self, operand: NodeNG) -> None:
4331 self.operand = operand
4332
4333 def type_errors(
4334 self, context: InferenceContext | None = None
4335 ) -> list[util.BadUnaryOperationMessage]:
4336 """Get a list of type errors which can occur during inference.
4337
4338 Each TypeError is represented by a :class:`~astroid.util.BadUnaryOperationMessage`,
4339 which holds the original exception.
4340
4341 If any inferred result is uninferable, an empty list is returned.
4342 """
4343 bad = []
4344 try:
4345 for result in self._infer_unaryop(context=context):
4346 if result is util.Uninferable:
4347 raise InferenceError
4348 if isinstance(result, util.BadUnaryOperationMessage):
4349 bad.append(result)
4350 except InferenceError:
4351 return []
4352 return bad
4353
4354 def get_children(self):
4355 yield self.operand
4356
4357 def op_precedence(self) -> int:
4358 if self.op == "not":
4359 return OP_PRECEDENCE[self.op]
4360
4361 return super().op_precedence()
4362
4363 def _infer_unaryop(
4364 self, context: InferenceContext | None = None
4365 ) -> Generator[
4366 InferenceResult | util.BadUnaryOperationMessage, None, InferenceErrorInfo
4367 ]:
4368 """Infer what an UnaryOp should return when evaluated."""
4369 from astroid.nodes import ClassDef # pylint: disable=import-outside-toplevel
4370
4371 for operand in self.operand.infer(context):
4372 try:
4373 yield operand.infer_unary_op(self.op)
4374 except TypeError as exc:
4375 # The operand doesn't support this operation.
4376 yield util.BadUnaryOperationMessage(operand, self.op, exc)
4377 except AttributeError as exc:
4378 meth = UNARY_OP_METHOD[self.op]
4379 if meth is None:
4380 # `not node`. Determine node's boolean
4381 # value and negate its result, unless it is
4382 # Uninferable, which will be returned as is.
4383 bool_value = operand.bool_value()
4384 if not isinstance(bool_value, util.UninferableBase):
4385 yield const_factory(not bool_value)
4386 else:
4387 yield util.Uninferable
4388 else:
4389 if not isinstance(operand, (Instance, ClassDef)):
4390 # The operation was used on something which
4391 # doesn't support it.
4392 yield util.BadUnaryOperationMessage(operand, self.op, exc)
4393 continue
4394
4395 try:
4396 try:
4397 methods = dunder_lookup.lookup(operand, meth)
4398 except AttributeInferenceError:
4399 yield util.BadUnaryOperationMessage(operand, self.op, exc)
4400 continue
4401
4402 meth = methods[0]
4403 inferred = next(meth.infer(context=context), None)
4404 if (
4405 isinstance(inferred, util.UninferableBase)
4406 or not inferred.callable()
4407 ):
4408 continue
4409
4410 context = copy_context(context)
4411 context.boundnode = operand
4412 context.callcontext = CallContext(args=[], callee=inferred)
4413
4414 call_results = inferred.infer_call_result(self, context=context)
4415 result = next(call_results, None)
4416 if result is None:
4417 # Failed to infer, return the same type.
4418 yield operand
4419 else:
4420 yield result
4421 except AttributeInferenceError as inner_exc:
4422 # The unary operation special method was not found.
4423 yield util.BadUnaryOperationMessage(operand, self.op, inner_exc)
4424 except InferenceError:
4425 yield util.Uninferable
4426
4427 @decorators.raise_if_nothing_inferred
4428 @decorators.path_wrapper
4429 def _infer(
4430 self, context: InferenceContext | None = None
4431 ) -> Generator[InferenceResult, None, InferenceErrorInfo]:
4432 """Infer what an UnaryOp should return when evaluated."""
4433 yield from self._filter_operation_errors(
4434 self._infer_unaryop, context, util.BadUnaryOperationMessage
4435 )
4436 return InferenceErrorInfo(node=self, context=context)
4437
4438
4439class While(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
4440 """Class representing an :class:`ast.While` node.
4441
4442 >>> import astroid
4443 >>> node = astroid.extract_node('''
4444 ... while condition():
4445 ... print("True")
4446 ... ''')
4447 >>> node
4448 <While l.2 at 0x...>
4449 """
4450
4451 _astroid_fields = ("test", "body", "orelse")
4452 _multi_line_block_fields = ("body", "orelse")
4453
4454 test: NodeNG
4455 """The condition that the loop tests."""
4456
4457 body: list[NodeNG]
4458 """The contents of the loop."""
4459
4460 orelse: list[NodeNG]
4461 """The contents of the ``else`` block."""
4462
4463 def postinit(
4464 self,
4465 test: NodeNG,
4466 body: list[NodeNG],
4467 orelse: list[NodeNG],
4468 ) -> None:
4469 self.test = test
4470 self.body = body
4471 self.orelse = orelse
4472
4473 @cached_property
4474 def blockstart_tolineno(self) -> int:
4475 """The line on which the beginning of this block ends."""
4476 return self.test.tolineno
4477
4478 def get_children(self):
4479 yield self.test
4480
4481 yield from self.body
4482 yield from self.orelse
4483
4484 def _get_yield_nodes_skip_functions(self):
4485 """A While node can contain a Yield node in the test"""
4486 yield from self.test._get_yield_nodes_skip_functions()
4487 yield from super()._get_yield_nodes_skip_functions()
4488
4489 def _get_yield_nodes_skip_lambdas(self):
4490 """A While node can contain a Yield node in the test"""
4491 yield from self.test._get_yield_nodes_skip_lambdas()
4492 yield from super()._get_yield_nodes_skip_lambdas()
4493
4494
4495class With(
4496 _base_nodes.MultiLineWithElseBlockNode,
4497 _base_nodes.AssignTypeNode,
4498 _base_nodes.Statement,
4499):
4500 """Class representing an :class:`ast.With` node.
4501
4502 >>> import astroid
4503 >>> node = astroid.extract_node('''
4504 ... with open(file_path) as file_:
4505 ... print(file_.read())
4506 ... ''')
4507 >>> node
4508 <With l.2 at 0x...>
4509 """
4510
4511 _astroid_fields = ("items", "body")
4512 _other_other_fields = ("type_annotation",)
4513 _multi_line_block_fields = ("body",)
4514
4515 def __init__(
4516 self,
4517 lineno: int | None = None,
4518 col_offset: int | None = None,
4519 parent: NodeNG | None = None,
4520 *,
4521 end_lineno: int | None = None,
4522 end_col_offset: int | None = None,
4523 ) -> None:
4524 """
4525 :param lineno: The line that this node appears on in the source code.
4526
4527 :param col_offset: The column that this node appears on in the
4528 source code.
4529
4530 :param parent: The parent node in the syntax tree.
4531
4532 :param end_lineno: The last line this node appears on in the source code.
4533
4534 :param end_col_offset: The end column this node appears on in the
4535 source code. Note: This is after the last symbol.
4536 """
4537 self.items: list[tuple[NodeNG, NodeNG | None]] = []
4538 """The pairs of context managers and the names they are assigned to."""
4539
4540 self.body: list[NodeNG] = []
4541 """The contents of the ``with`` block."""
4542
4543 self.type_annotation: NodeNG | None = None # can be None
4544 """If present, this will contain the type annotation passed by a type comment"""
4545
4546 super().__init__(
4547 lineno=lineno,
4548 col_offset=col_offset,
4549 end_lineno=end_lineno,
4550 end_col_offset=end_col_offset,
4551 parent=parent,
4552 )
4553
4554 def postinit(
4555 self,
4556 items: list[tuple[NodeNG, NodeNG | None]] | None = None,
4557 body: list[NodeNG] | None = None,
4558 type_annotation: NodeNG | None = None,
4559 ) -> None:
4560 """Do some setup after initialisation.
4561
4562 :param items: The pairs of context managers and the names
4563 they are assigned to.
4564
4565 :param body: The contents of the ``with`` block.
4566 """
4567 if items is not None:
4568 self.items = items
4569 if body is not None:
4570 self.body = body
4571 self.type_annotation = type_annotation
4572
4573 assigned_stmts = protocols.with_assigned_stmts
4574 """Returns the assigned statement (non inferred) according to the assignment type.
4575 See astroid/protocols.py for actual implementation.
4576 """
4577
4578 @cached_property
4579 def blockstart_tolineno(self) -> int:
4580 """The line on which the beginning of this block ends."""
4581 return self.items[-1][0].tolineno
4582
4583 def get_children(self) -> Iterator[NodeNG]:
4584 """Get the child nodes below this node.
4585
4586 :returns: The children.
4587 """
4588 for expr, var in self.items:
4589 yield expr
4590 if var:
4591 yield var
4592 yield from self.body
4593
4594
4595class AsyncWith(With):
4596 """Asynchronous ``with`` built with the ``async`` keyword."""
4597
4598
4599class Yield(NodeNG):
4600 """Class representing an :class:`ast.Yield` node.
4601
4602 >>> import astroid
4603 >>> node = astroid.extract_node('yield True')
4604 >>> node
4605 <Yield l.1 at 0x...>
4606 """
4607
4608 _astroid_fields = ("value",)
4609
4610 value: NodeNG | None
4611 """The value to yield."""
4612
4613 def postinit(self, value: NodeNG | None) -> None:
4614 self.value = value
4615
4616 def get_children(self):
4617 if self.value is not None:
4618 yield self.value
4619
4620 def _get_yield_nodes_skip_functions(self):
4621 yield self
4622
4623 def _get_yield_nodes_skip_lambdas(self):
4624 yield self
4625
4626
4627class YieldFrom(Yield): # TODO value is required, not optional
4628 """Class representing an :class:`ast.YieldFrom` node."""
4629
4630
4631class DictUnpack(_base_nodes.NoChildrenNode):
4632 """Represents the unpacking of dicts into dicts using :pep:`448`."""
4633
4634
4635# Functions for the ``conversion`` codes of ``FormattedValue``: ``!s``, ``!r``, ``!a``.
4636_FORMAT_CONVERSIONS: dict[int, Callable[[object], str]] = {
4637 ord("s"): str,
4638 ord("r"): repr,
4639 ord("a"): ascii,
4640}
4641
4642
4643class FormattedValue(NodeNG):
4644 """Class representing an :class:`ast.FormattedValue` node.
4645
4646 Represents a :pep:`498` format string.
4647
4648 >>> import astroid
4649 >>> node = astroid.extract_node('f"Format {type_}"')
4650 >>> node
4651 <JoinedStr l.1 at 0x...>
4652 >>> node.values
4653 [<Const.str l.1 at 0x...>, <FormattedValue l.1 at 0x...>]
4654 """
4655
4656 _astroid_fields = ("value", "format_spec")
4657 _other_fields = ("conversion",)
4658
4659 def __init__(
4660 self,
4661 lineno: int | None = None,
4662 col_offset: int | None = None,
4663 parent: NodeNG | None = None,
4664 *,
4665 end_lineno: int | None = None,
4666 end_col_offset: int | None = None,
4667 ) -> None:
4668 """
4669 :param lineno: The line that this node appears on in the source code.
4670
4671 :param col_offset: The column that this node appears on in the
4672 source code.
4673
4674 :param parent: The parent node in the syntax tree.
4675
4676 :param end_lineno: The last line this node appears on in the source code.
4677
4678 :param end_col_offset: The end column this node appears on in the
4679 source code. Note: This is after the last symbol.
4680 """
4681 self.value: NodeNG
4682 """The value to be formatted into the string."""
4683
4684 self.conversion: int
4685 """The type of formatting to be applied to the value.
4686
4687 .. seealso::
4688 :class:`ast.FormattedValue`
4689 """
4690
4691 self.format_spec: JoinedStr | None = None
4692 """The formatting to be applied to the value.
4693
4694 .. seealso::
4695 :class:`ast.FormattedValue`
4696 """
4697
4698 super().__init__(
4699 lineno=lineno,
4700 col_offset=col_offset,
4701 end_lineno=end_lineno,
4702 end_col_offset=end_col_offset,
4703 parent=parent,
4704 )
4705
4706 def postinit(
4707 self,
4708 *,
4709 value: NodeNG,
4710 conversion: int,
4711 format_spec: JoinedStr | None = None,
4712 ) -> None:
4713 """Do some setup after initialisation.
4714
4715 :param value: The value to be formatted into the string.
4716
4717 :param conversion: The type of formatting to be applied to the value.
4718
4719 :param format_spec: The formatting to be applied to the value.
4720 """
4721 self.value = value
4722 self.conversion = conversion
4723 self.format_spec = format_spec
4724
4725 def get_children(self):
4726 yield self.value
4727
4728 if self.format_spec is not None:
4729 yield self.format_spec
4730
4731 def _infer(
4732 self, context: InferenceContext | None = None
4733 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4734 format_specs = Const("") if self.format_spec is None else self.format_spec
4735 uninferable_already_generated = False
4736 for format_spec in format_specs.infer(context):
4737 if not isinstance(format_spec, Const):
4738 if not uninferable_already_generated:
4739 yield util.Uninferable
4740 uninferable_already_generated = True
4741 continue
4742 for value in self.value.infer(context):
4743 if value is util.Uninferable:
4744 yield util.Uninferable
4745 return
4746 value_to_format = value
4747 if isinstance(value, Const):
4748 value_to_format = value.value
4749 if isinstance(format_spec.value, str) and util.format_spec_too_large(
4750 format_spec.value
4751 ):
4752 yield util.Uninferable
4753 uninferable_already_generated = True
4754 continue
4755 try:
4756 convert = _FORMAT_CONVERSIONS.get(self.conversion)
4757 if convert is not None and isinstance(value, Const):
4758 formatted = format(convert(value.value), format_spec.value)
4759 else:
4760 formatted = format(value_to_format, format_spec.value)
4761 yield Const(
4762 formatted,
4763 lineno=self.lineno,
4764 col_offset=self.col_offset,
4765 end_lineno=self.end_lineno,
4766 end_col_offset=self.end_col_offset,
4767 )
4768 continue
4769 except (ValueError, TypeError, MemoryError, OverflowError):
4770 # ValueError/TypeError: invalid format spec
4771 # MemoryError: format spec with huge width (e.g. f'{0:11111111111}')
4772 # OverflowError: "c" with an out-of-range code point (e.g. f'{-1:c}')
4773 yield util.Uninferable
4774 uninferable_already_generated = True
4775 continue
4776
4777
4778UNINFERABLE_VALUE = "{Uninferable}"
4779
4780
4781class JoinedStr(NodeNG):
4782 """Represents a list of string expressions to be joined.
4783
4784 >>> import astroid
4785 >>> node = astroid.extract_node('f"Format {type_}"')
4786 >>> node
4787 <JoinedStr l.1 at 0x...>
4788 """
4789
4790 _astroid_fields = ("values",)
4791
4792 def __init__(
4793 self,
4794 lineno: int | None = None,
4795 col_offset: int | None = None,
4796 parent: NodeNG | None = None,
4797 *,
4798 end_lineno: int | None = None,
4799 end_col_offset: int | None = None,
4800 ) -> None:
4801 """
4802 :param lineno: The line that this node appears on in the source code.
4803
4804 :param col_offset: The column that this node appears on in the
4805 source code.
4806
4807 :param parent: The parent node in the syntax tree.
4808
4809 :param end_lineno: The last line this node appears on in the source code.
4810
4811 :param end_col_offset: The end column this node appears on in the
4812 source code. Note: This is after the last symbol.
4813 """
4814 self.values: list[NodeNG] = []
4815 """The string expressions to be joined."""
4816
4817 super().__init__(
4818 lineno=lineno,
4819 col_offset=col_offset,
4820 end_lineno=end_lineno,
4821 end_col_offset=end_col_offset,
4822 parent=parent,
4823 )
4824
4825 def postinit(self, values: list[NodeNG] | None = None) -> None:
4826 """Do some setup after initialisation.
4827
4828 :param value: The string expressions to be joined.
4829 """
4830 if values is not None:
4831 self.values = values
4832
4833 def get_children(self):
4834 yield from self.values
4835
4836 def _infer(
4837 self, context: InferenceContext | None = None
4838 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4839 if self.values:
4840 yield from self._infer_with_values(context)
4841 else:
4842 yield Const("")
4843
4844 def _infer_with_values(
4845 self, context: InferenceContext | None = None
4846 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4847 uninferable_already_generated = False
4848 for inferred in self._infer_from_values(self.values, context):
4849 failed = inferred is util.Uninferable or (
4850 isinstance(inferred, Const) and UNINFERABLE_VALUE in inferred.value
4851 )
4852 if failed:
4853 if not uninferable_already_generated:
4854 uninferable_already_generated = True
4855 yield util.Uninferable
4856 continue
4857 yield inferred
4858
4859 @classmethod
4860 def _infer_from_values(
4861 cls, nodes: list[NodeNG], context: InferenceContext | None = None
4862 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4863 if not nodes:
4864 return
4865 if len(nodes) == 1:
4866 for node in cls._safe_infer_from_node(nodes[0], context):
4867 if isinstance(node, Const):
4868 yield node
4869 continue
4870 yield Const(UNINFERABLE_VALUE)
4871 return
4872 for prefix in cls._safe_infer_from_node(nodes[0], context):
4873 for suffix in cls._infer_from_values(nodes[1:], context):
4874 result = ""
4875 for node in (prefix, suffix):
4876 if isinstance(node, Const):
4877 result += str(node.value)
4878 continue
4879 result += UNINFERABLE_VALUE
4880 yield Const(result)
4881
4882 @classmethod
4883 def _safe_infer_from_node(
4884 cls, node: NodeNG, context: InferenceContext | None = None
4885 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4886 try:
4887 yield from node._infer(context)
4888 except InferenceError:
4889 yield util.Uninferable
4890
4891
4892class NamedExpr(_base_nodes.AssignTypeNode):
4893 """Represents the assignment from the assignment expression
4894
4895 >>> import astroid
4896 >>> module = astroid.parse('if a := 1: pass')
4897 >>> module.body[0].test
4898 <NamedExpr l.1 at 0x...>
4899 """
4900
4901 _astroid_fields = ("target", "value")
4902
4903 optional_assign = True
4904 """Whether this node optionally assigns a variable.
4905
4906 Since NamedExpr are not always called they do not always assign."""
4907
4908 def __init__(
4909 self,
4910 lineno: int | None = None,
4911 col_offset: int | None = None,
4912 parent: NodeNG | None = None,
4913 *,
4914 end_lineno: int | None = None,
4915 end_col_offset: int | None = None,
4916 ) -> None:
4917 """
4918 :param lineno: The line that this node appears on in the source code.
4919
4920 :param col_offset: The column that this node appears on in the
4921 source code.
4922
4923 :param parent: The parent node in the syntax tree.
4924
4925 :param end_lineno: The last line this node appears on in the source code.
4926
4927 :param end_col_offset: The end column this node appears on in the
4928 source code. Note: This is after the last symbol.
4929 """
4930 self.target: NodeNG
4931 """The assignment target"""
4932
4933 self.value: NodeNG
4934 """The value that gets assigned in the expression"""
4935
4936 super().__init__(
4937 lineno=lineno,
4938 col_offset=col_offset,
4939 end_lineno=end_lineno,
4940 end_col_offset=end_col_offset,
4941 parent=parent,
4942 )
4943
4944 def postinit(self, target: NodeNG, value: NodeNG) -> None:
4945 self.target = target
4946 self.value = value
4947
4948 assigned_stmts = protocols.named_expr_assigned_stmts
4949 """Returns the assigned statement (non inferred) according to the assignment type.
4950 See astroid/protocols.py for actual implementation.
4951 """
4952
4953 def frame(self) -> FrameType:
4954 """The first parent frame node.
4955
4956 A frame node is a :class:`Module`, :class:`FunctionDef`,
4957 or :class:`ClassDef`.
4958
4959 :returns: The first parent frame node.
4960 """
4961 if not self.parent:
4962 raise ParentMissingError(target=self)
4963
4964 # For certain parents NamedExpr evaluate to the scope of the parent
4965 if isinstance(self.parent, (Arguments, Keyword, Comprehension)):
4966 if not self.parent.parent:
4967 raise ParentMissingError(target=self.parent)
4968 if not self.parent.parent.parent:
4969 raise ParentMissingError(target=self.parent.parent)
4970 return self.parent.parent.parent.frame()
4971
4972 return self.parent.frame()
4973
4974 def scope(self) -> LocalsDictNodeNG:
4975 """The first parent node defining a new scope.
4976 These can be Module, FunctionDef, ClassDef, Lambda, or GeneratorExp nodes.
4977
4978 :returns: The first parent scope node.
4979 """
4980 if not self.parent:
4981 raise ParentMissingError(target=self)
4982
4983 # For certain parents NamedExpr evaluate to the scope of the parent
4984 if isinstance(self.parent, (Arguments, Keyword, Comprehension)):
4985 if not self.parent.parent:
4986 raise ParentMissingError(target=self.parent)
4987 if not self.parent.parent.parent:
4988 raise ParentMissingError(target=self.parent.parent)
4989 return self.parent.parent.parent.scope()
4990
4991 return self.parent.scope()
4992
4993 def set_local(self, name: str, stmt: NodeNG) -> None:
4994 """Define that the given name is declared in the given statement node.
4995 NamedExpr's in Arguments, Keyword or Comprehension are evaluated in their
4996 parent's parent scope. So we add to their frame's locals.
4997
4998 .. seealso:: :meth:`scope`
4999
5000 :param name: The name that is being defined.
5001
5002 :param stmt: The statement that defines the given name.
5003 """
5004 self.frame().set_local(name, stmt)
5005
5006
5007class Unknown(_base_nodes.AssignTypeNode):
5008 """This node represents a node in a constructed AST where
5009 introspection is not possible.
5010
5011 Used in the args attribute of FunctionDef nodes where function signature
5012 introspection failed, and as a placeholder in ObjectModel.
5013 """
5014
5015 name = "Unknown"
5016
5017 def __init__(
5018 self,
5019 parent: NodeNG,
5020 lineno: None = None,
5021 col_offset: None = None,
5022 *,
5023 end_lineno: None = None,
5024 end_col_offset: None = None,
5025 ) -> None:
5026 super().__init__(
5027 lineno=lineno,
5028 col_offset=col_offset,
5029 end_lineno=end_lineno,
5030 end_col_offset=end_col_offset,
5031 parent=parent,
5032 )
5033
5034 def qname(self) -> Literal["Unknown"]:
5035 return "Unknown"
5036
5037 def pytype(self) -> Literal["Unknown"]:
5038 return "Unknown"
5039
5040 def _infer(self, context: InferenceContext | None = None):
5041 """Inference on an Unknown node immediately terminates."""
5042 yield util.Uninferable
5043
5044
5045UNATTACHED_UNKNOWN = Unknown(parent=SYNTHETIC_ROOT)
5046
5047
5048class EvaluatedObject(NodeNG):
5049 """Contains an object that has already been inferred
5050
5051 This class is useful to pre-evaluate a particular node,
5052 with the resulting class acting as the non-evaluated node.
5053 """
5054
5055 name = "EvaluatedObject"
5056 _astroid_fields = ("original",)
5057 _other_fields = ("value",)
5058
5059 def __init__(
5060 self, original: SuccessfulInferenceResult, value: InferenceResult
5061 ) -> None:
5062 self.original: SuccessfulInferenceResult = original
5063 """The original node that has already been evaluated"""
5064
5065 self.value: InferenceResult = value
5066 """The inferred value"""
5067
5068 super().__init__(
5069 lineno=self.original.lineno,
5070 col_offset=self.original.col_offset,
5071 parent=self.original.parent,
5072 end_lineno=self.original.end_lineno,
5073 end_col_offset=self.original.end_col_offset,
5074 )
5075
5076 def _infer(
5077 self, context: InferenceContext | None = None
5078 ) -> Generator[NodeNG | util.UninferableBase]:
5079 yield self.value
5080
5081
5082# Pattern matching #######################################################
5083
5084
5085class Match(_base_nodes.Statement, _base_nodes.MultiLineBlockNode):
5086 """Class representing a :class:`ast.Match` node.
5087
5088 >>> import astroid
5089 >>> node = astroid.extract_node('''
5090 ... match x:
5091 ... case 200:
5092 ... ...
5093 ... case _:
5094 ... ...
5095 ... ''')
5096 >>> node
5097 <Match l.2 at 0x...>
5098 """
5099
5100 _astroid_fields = ("subject", "cases")
5101 _multi_line_block_fields = ("cases",)
5102
5103 def __init__(
5104 self,
5105 lineno: int | None = None,
5106 col_offset: int | None = None,
5107 parent: NodeNG | None = None,
5108 *,
5109 end_lineno: int | None = None,
5110 end_col_offset: int | None = None,
5111 ) -> None:
5112 self.subject: NodeNG
5113 self.cases: list[MatchCase]
5114 super().__init__(
5115 lineno=lineno,
5116 col_offset=col_offset,
5117 end_lineno=end_lineno,
5118 end_col_offset=end_col_offset,
5119 parent=parent,
5120 )
5121
5122 def postinit(
5123 self,
5124 *,
5125 subject: NodeNG,
5126 cases: list[MatchCase],
5127 ) -> None:
5128 self.subject = subject
5129 self.cases = cases
5130
5131
5132class Pattern(NodeNG):
5133 """Base class for all Pattern nodes."""
5134
5135
5136class MatchCase(_base_nodes.MultiLineBlockNode):
5137 """Class representing a :class:`ast.match_case` node.
5138
5139 >>> import astroid
5140 >>> node = astroid.extract_node('''
5141 ... match x:
5142 ... case 200:
5143 ... ...
5144 ... ''')
5145 >>> node.cases[0]
5146 <MatchCase l.3 at 0x...>
5147 """
5148
5149 _astroid_fields = ("pattern", "guard", "body")
5150 _multi_line_block_fields = ("body",)
5151
5152 lineno: None
5153 col_offset: None
5154 end_lineno: None
5155 end_col_offset: None
5156
5157 def __init__(self, *, parent: NodeNG | None = None) -> None:
5158 self.pattern: Pattern
5159 self.guard: NodeNG | None
5160 self.body: list[NodeNG]
5161 super().__init__(
5162 parent=parent,
5163 lineno=None,
5164 col_offset=None,
5165 end_lineno=None,
5166 end_col_offset=None,
5167 )
5168
5169 def postinit(
5170 self,
5171 *,
5172 pattern: Pattern,
5173 guard: NodeNG | None,
5174 body: list[NodeNG],
5175 ) -> None:
5176 self.pattern = pattern
5177 self.guard = guard
5178 self.body = body
5179
5180
5181class MatchValue(Pattern):
5182 """Class representing a :class:`ast.MatchValue` node.
5183
5184 >>> import astroid
5185 >>> node = astroid.extract_node('''
5186 ... match x:
5187 ... case 200:
5188 ... ...
5189 ... ''')
5190 >>> node.cases[0].pattern
5191 <MatchValue l.3 at 0x...>
5192 """
5193
5194 _astroid_fields = ("value",)
5195
5196 def __init__(
5197 self,
5198 lineno: int | None = None,
5199 col_offset: int | None = None,
5200 parent: NodeNG | None = None,
5201 *,
5202 end_lineno: int | None = None,
5203 end_col_offset: int | None = None,
5204 ) -> None:
5205 self.value: NodeNG
5206 super().__init__(
5207 lineno=lineno,
5208 col_offset=col_offset,
5209 end_lineno=end_lineno,
5210 end_col_offset=end_col_offset,
5211 parent=parent,
5212 )
5213
5214 def postinit(self, *, value: NodeNG) -> None:
5215 self.value = value
5216
5217
5218class MatchSingleton(Pattern):
5219 """Class representing a :class:`ast.MatchSingleton` node.
5220
5221 >>> import astroid
5222 >>> node = astroid.extract_node('''
5223 ... match x:
5224 ... case True:
5225 ... ...
5226 ... case False:
5227 ... ...
5228 ... case None:
5229 ... ...
5230 ... ''')
5231 >>> node.cases[0].pattern
5232 <MatchSingleton l.3 at 0x...>
5233 >>> node.cases[1].pattern
5234 <MatchSingleton l.5 at 0x...>
5235 >>> node.cases[2].pattern
5236 <MatchSingleton l.7 at 0x...>
5237 """
5238
5239 _other_fields = ("value",)
5240
5241 def __init__(
5242 self,
5243 *,
5244 value: Literal[True, False, None],
5245 lineno: int | None = None,
5246 col_offset: int | None = None,
5247 end_lineno: int | None = None,
5248 end_col_offset: int | None = None,
5249 parent: NodeNG | None = None,
5250 ) -> None:
5251 self.value = value
5252 super().__init__(
5253 lineno=lineno,
5254 col_offset=col_offset,
5255 end_lineno=end_lineno,
5256 end_col_offset=end_col_offset,
5257 parent=parent,
5258 )
5259
5260
5261class MatchSequence(Pattern):
5262 """Class representing a :class:`ast.MatchSequence` node.
5263
5264 >>> import astroid
5265 >>> node = astroid.extract_node('''
5266 ... match x:
5267 ... case [1, 2]:
5268 ... ...
5269 ... case (1, 2, *_):
5270 ... ...
5271 ... ''')
5272 >>> node.cases[0].pattern
5273 <MatchSequence l.3 at 0x...>
5274 >>> node.cases[1].pattern
5275 <MatchSequence l.5 at 0x...>
5276 """
5277
5278 _astroid_fields = ("patterns",)
5279
5280 def __init__(
5281 self,
5282 lineno: int | None = None,
5283 col_offset: int | None = None,
5284 parent: NodeNG | None = None,
5285 *,
5286 end_lineno: int | None = None,
5287 end_col_offset: int | None = None,
5288 ) -> None:
5289 self.patterns: list[Pattern]
5290 super().__init__(
5291 lineno=lineno,
5292 col_offset=col_offset,
5293 end_lineno=end_lineno,
5294 end_col_offset=end_col_offset,
5295 parent=parent,
5296 )
5297
5298 def postinit(self, *, patterns: list[Pattern]) -> None:
5299 self.patterns = patterns
5300
5301
5302class MatchMapping(_base_nodes.AssignTypeNode, Pattern):
5303 """Class representing a :class:`ast.MatchMapping` node.
5304
5305 >>> import astroid
5306 >>> node = astroid.extract_node('''
5307 ... match x:
5308 ... case {1: "Hello", 2: "World", 3: _, **rest}:
5309 ... ...
5310 ... ''')
5311 >>> node.cases[0].pattern
5312 <MatchMapping l.3 at 0x...>
5313 """
5314
5315 _astroid_fields = ("keys", "patterns", "rest")
5316
5317 def __init__(
5318 self,
5319 lineno: int | None = None,
5320 col_offset: int | None = None,
5321 parent: NodeNG | None = None,
5322 *,
5323 end_lineno: int | None = None,
5324 end_col_offset: int | None = None,
5325 ) -> None:
5326 self.keys: list[NodeNG]
5327 self.patterns: list[Pattern]
5328 self.rest: AssignName | None
5329 super().__init__(
5330 lineno=lineno,
5331 col_offset=col_offset,
5332 end_lineno=end_lineno,
5333 end_col_offset=end_col_offset,
5334 parent=parent,
5335 )
5336
5337 def postinit(
5338 self,
5339 *,
5340 keys: list[NodeNG],
5341 patterns: list[Pattern],
5342 rest: AssignName | None,
5343 ) -> None:
5344 self.keys = keys
5345 self.patterns = patterns
5346 self.rest = rest
5347
5348 assigned_stmts = protocols.match_mapping_assigned_stmts
5349 """Returns the assigned statement (non inferred) according to the assignment type.
5350 See astroid/protocols.py for actual implementation.
5351 """
5352
5353
5354class MatchClass(Pattern):
5355 """Class representing a :class:`ast.MatchClass` node.
5356
5357 >>> import astroid
5358 >>> node = astroid.extract_node('''
5359 ... match x:
5360 ... case Point2D(0, 0):
5361 ... ...
5362 ... case Point3D(x=0, y=0, z=0):
5363 ... ...
5364 ... ''')
5365 >>> node.cases[0].pattern
5366 <MatchClass l.3 at 0x...>
5367 >>> node.cases[1].pattern
5368 <MatchClass l.5 at 0x...>
5369 """
5370
5371 _astroid_fields = ("cls", "patterns", "kwd_patterns")
5372 _other_fields = ("kwd_attrs",)
5373
5374 def __init__(
5375 self,
5376 lineno: int | None = None,
5377 col_offset: int | None = None,
5378 parent: NodeNG | None = None,
5379 *,
5380 end_lineno: int | None = None,
5381 end_col_offset: int | None = None,
5382 ) -> None:
5383 self.cls: NodeNG
5384 self.patterns: list[Pattern]
5385 self.kwd_attrs: list[str]
5386 self.kwd_patterns: list[Pattern]
5387 super().__init__(
5388 lineno=lineno,
5389 col_offset=col_offset,
5390 end_lineno=end_lineno,
5391 end_col_offset=end_col_offset,
5392 parent=parent,
5393 )
5394
5395 def postinit(
5396 self,
5397 *,
5398 cls: NodeNG,
5399 patterns: list[Pattern],
5400 kwd_attrs: list[str],
5401 kwd_patterns: list[Pattern],
5402 ) -> None:
5403 self.cls = cls
5404 self.patterns = patterns
5405 self.kwd_attrs = kwd_attrs
5406 self.kwd_patterns = kwd_patterns
5407
5408
5409class MatchStar(_base_nodes.AssignTypeNode, Pattern):
5410 """Class representing a :class:`ast.MatchStar` node.
5411
5412 >>> import astroid
5413 >>> node = astroid.extract_node('''
5414 ... match x:
5415 ... case [1, *_]:
5416 ... ...
5417 ... ''')
5418 >>> node.cases[0].pattern.patterns[1]
5419 <MatchStar l.3 at 0x...>
5420 """
5421
5422 _astroid_fields = ("name",)
5423
5424 def __init__(
5425 self,
5426 lineno: int | None = None,
5427 col_offset: int | None = None,
5428 parent: NodeNG | None = None,
5429 *,
5430 end_lineno: int | None = None,
5431 end_col_offset: int | None = None,
5432 ) -> None:
5433 self.name: AssignName | None
5434 super().__init__(
5435 lineno=lineno,
5436 col_offset=col_offset,
5437 end_lineno=end_lineno,
5438 end_col_offset=end_col_offset,
5439 parent=parent,
5440 )
5441
5442 def postinit(self, *, name: AssignName | None) -> None:
5443 self.name = name
5444
5445 assigned_stmts = protocols.match_star_assigned_stmts
5446 """Returns the assigned statement (non inferred) according to the assignment type.
5447 See astroid/protocols.py for actual implementation.
5448 """
5449
5450
5451class MatchAs(_base_nodes.AssignTypeNode, Pattern):
5452 """Class representing a :class:`ast.MatchAs` node.
5453
5454 >>> import astroid
5455 >>> node = astroid.extract_node('''
5456 ... match x:
5457 ... case [1, a]:
5458 ... ...
5459 ... case {'key': b}:
5460 ... ...
5461 ... case Point2D(0, 0) as c:
5462 ... ...
5463 ... case d:
5464 ... ...
5465 ... ''')
5466 >>> node.cases[0].pattern.patterns[1]
5467 <MatchAs l.3 at 0x...>
5468 >>> node.cases[1].pattern.patterns[0]
5469 <MatchAs l.5 at 0x...>
5470 >>> node.cases[2].pattern
5471 <MatchAs l.7 at 0x...>
5472 >>> node.cases[3].pattern
5473 <MatchAs l.9 at 0x...>
5474 """
5475
5476 _astroid_fields = ("pattern", "name")
5477
5478 def __init__(
5479 self,
5480 lineno: int | None = None,
5481 col_offset: int | None = None,
5482 parent: NodeNG | None = None,
5483 *,
5484 end_lineno: int | None = None,
5485 end_col_offset: int | None = None,
5486 ) -> None:
5487 self.pattern: Pattern | None
5488 self.name: AssignName | None
5489 super().__init__(
5490 lineno=lineno,
5491 col_offset=col_offset,
5492 end_lineno=end_lineno,
5493 end_col_offset=end_col_offset,
5494 parent=parent,
5495 )
5496
5497 def postinit(
5498 self,
5499 *,
5500 pattern: Pattern | None,
5501 name: AssignName | None,
5502 ) -> None:
5503 self.pattern = pattern
5504 self.name = name
5505
5506 assigned_stmts = protocols.match_as_assigned_stmts
5507 """Returns the assigned statement (non inferred) according to the assignment type.
5508 See astroid/protocols.py for actual implementation.
5509 """
5510
5511
5512class MatchOr(Pattern):
5513 """Class representing a :class:`ast.MatchOr` node.
5514
5515 >>> import astroid
5516 >>> node = astroid.extract_node('''
5517 ... match x:
5518 ... case 400 | 401 | 402:
5519 ... ...
5520 ... ''')
5521 >>> node.cases[0].pattern
5522 <MatchOr l.3 at 0x...>
5523 """
5524
5525 _astroid_fields = ("patterns",)
5526
5527 def __init__(
5528 self,
5529 lineno: int | None = None,
5530 col_offset: int | None = None,
5531 parent: NodeNG | None = None,
5532 *,
5533 end_lineno: int | None = None,
5534 end_col_offset: int | None = None,
5535 ) -> None:
5536 self.patterns: list[Pattern]
5537 super().__init__(
5538 lineno=lineno,
5539 col_offset=col_offset,
5540 end_lineno=end_lineno,
5541 end_col_offset=end_col_offset,
5542 parent=parent,
5543 )
5544
5545 def postinit(self, *, patterns: list[Pattern]) -> None:
5546 self.patterns = patterns
5547
5548
5549class TemplateStr(NodeNG):
5550 """Class representing an :class:`ast.TemplateStr` node.
5551
5552 >>> import astroid
5553 >>> node = astroid.extract_node('t"{name} finished {place!s}"')
5554 >>> node
5555 <TemplateStr l.1 at 0x...>
5556 """
5557
5558 _astroid_fields = ("values",)
5559
5560 def __init__(
5561 self,
5562 lineno: int | None = None,
5563 col_offset: int | None = None,
5564 parent: NodeNG | None = None,
5565 *,
5566 end_lineno: int | None = None,
5567 end_col_offset: int | None = None,
5568 ) -> None:
5569 self.values: list[NodeNG]
5570 super().__init__(
5571 lineno=lineno,
5572 col_offset=col_offset,
5573 end_lineno=end_lineno,
5574 end_col_offset=end_col_offset,
5575 parent=parent,
5576 )
5577
5578 def postinit(self, *, values: list[NodeNG]) -> None:
5579 self.values = values
5580
5581 def get_children(self) -> Iterator[NodeNG]:
5582 yield from self.values
5583
5584
5585class Interpolation(NodeNG):
5586 """Class representing an :class:`ast.Interpolation` node.
5587
5588 >>> import astroid
5589 >>> node = astroid.extract_node('t"{name} finished {place!s}"')
5590 >>> node
5591 <TemplateStr l.1 at 0x...>
5592 >>> node.values[0]
5593 <Interpolation l.1 at 0x...>
5594 >>> node.values[2]
5595 <Interpolation l.1 at 0x...>
5596 """
5597
5598 _astroid_fields = ("value", "format_spec")
5599 _other_fields = ("str", "conversion")
5600
5601 def __init__(
5602 self,
5603 lineno: int | None = None,
5604 col_offset: int | None = None,
5605 parent: NodeNG | None = None,
5606 *,
5607 end_lineno: int | None = None,
5608 end_col_offset: int | None = None,
5609 ) -> None:
5610 self.value: NodeNG
5611 """Any expression node."""
5612
5613 self.str: str
5614 """Text of the interpolation expression."""
5615
5616 self.conversion: int
5617 """The type of formatting to be applied to the value.
5618
5619 .. seealso::
5620 :class:`ast.Interpolation`
5621 """
5622
5623 self.format_spec: JoinedStr | None = None
5624 """The formatting to be applied to the value.
5625
5626 .. seealso::
5627 :class:`ast.Interpolation`
5628 """
5629
5630 super().__init__(
5631 lineno=lineno,
5632 col_offset=col_offset,
5633 end_lineno=end_lineno,
5634 end_col_offset=end_col_offset,
5635 parent=parent,
5636 )
5637
5638 def postinit(
5639 self,
5640 *,
5641 value: NodeNG,
5642 str: str, # pylint: disable=redefined-builtin
5643 conversion: int = -1,
5644 format_spec: JoinedStr | None = None,
5645 ) -> None:
5646 self.value = value
5647 self.str = str
5648 self.conversion = conversion
5649 self.format_spec = format_spec
5650
5651 def get_children(self) -> Iterator[NodeNG]:
5652 yield self.value
5653 if self.format_spec:
5654 yield self.format_spec
5655
5656
5657# constants ##############################################################
5658
5659# The _proxied attribute of all container types (List, Tuple, etc.)
5660# are set during bootstrapping by _astroid_bootstrapping().
5661CONST_CLS: dict[type, type[NodeNG]] = {
5662 list: List,
5663 tuple: Tuple,
5664 dict: Dict,
5665 set: Set,
5666 type(None): Const,
5667 type(NotImplemented): Const,
5668 type(...): Const,
5669 bool: Const,
5670 int: Const,
5671 float: Const,
5672 complex: Const,
5673 str: Const,
5674 bytes: Const,
5675}
5676
5677
5678def _create_basic_elements(
5679 value: Iterable[Any], node: List | Set | Tuple, building: set[int]
5680) -> list[NodeNG]:
5681 """Create a list of nodes to function as the elements of a new node."""
5682 elements: list[NodeNG] = []
5683 for element in value:
5684 # NOTE: avoid accessing any attributes of element in the loop.
5685 element_node = _const_factory(element, building)
5686 element_node.parent = node
5687 elements.append(element_node)
5688 return elements
5689
5690
5691def _create_dict_items(
5692 values: Mapping[Any, Any], node: Dict, building: set[int]
5693) -> list[tuple[SuccessfulInferenceResult, SuccessfulInferenceResult]]:
5694 """Create a list of node pairs to function as the items of a new dict node."""
5695 elements: list[tuple[SuccessfulInferenceResult, SuccessfulInferenceResult]] = []
5696 for key, value in values.items():
5697 # NOTE: avoid accessing any attributes of both key and value in the loop.
5698 key_node = _const_factory(key, building)
5699 key_node.parent = node
5700 value_node = _const_factory(value, building)
5701 value_node.parent = node
5702 elements.append((key_node, value_node))
5703 return elements
5704
5705
5706def const_factory(value: Any) -> ConstFactoryResult:
5707 """Return an astroid node for a python value."""
5708 return _const_factory(value, set())
5709
5710
5711def _const_factory(value: Any, building: set[int]) -> ConstFactoryResult:
5712 """Return an astroid node for value.
5713
5714 ``building`` holds the ids of the containers whose elements are being
5715 converted, i.e. the containers value is nested in.
5716 """
5717 # NOTE: avoid accessing any attributes of value until it is known that value
5718 # is of a const type, to avoid possibly triggering code for a live object.
5719 # Accesses include value.__class__ and isinstance(value, ...), but not type(value).
5720 # See: https://github.com/pylint-dev/astroid/issues/2686
5721 value_type = type(value)
5722 assert not issubclass(value_type, NodeNG)
5723
5724 # This only handles instances of the CONST types. Any
5725 # subclasses get inferred as EmptyNode.
5726 # TODO: See if we should revisit these with the normal builder.
5727 if value_type not in CONST_CLS:
5728 node = EmptyNode()
5729 node.object = value
5730 return node
5731
5732 instance: List | Set | Tuple | Dict
5733 initializer_cls = CONST_CLS[value_type]
5734 if initializer_cls is Const:
5735 return Const(value)
5736
5737 # A live container can hold itself, directly or through other containers
5738 # (``namespace = globals()``): converting it again would recurse forever,
5739 # so the back reference becomes an EmptyNode, like a non-const object.
5740 value_id = id(value)
5741 if value_id in building:
5742 node = EmptyNode()
5743 node.object = value
5744 return node
5745 building.add(value_id)
5746 if issubclass(initializer_cls, (List, Set, Tuple)):
5747 instance = initializer_cls(
5748 lineno=None,
5749 col_offset=None,
5750 parent=SYNTHETIC_ROOT,
5751 end_lineno=None,
5752 end_col_offset=None,
5753 )
5754 instance.postinit(_create_basic_elements(value, instance, building))
5755 else:
5756 assert issubclass(initializer_cls, Dict)
5757 instance = initializer_cls(
5758 lineno=None,
5759 col_offset=None,
5760 parent=SYNTHETIC_ROOT,
5761 end_lineno=None,
5762 end_col_offset=None,
5763 )
5764 instance.postinit(_create_dict_items(value, instance, building))
5765 building.remove(value_id)
5766 return instance