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 asssigned 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 re-used 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 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 def display_type(self) -> Literal["Slice"]:
3589 """A human readable type of this node.
3590
3591 :returns: The type of this node.
3592 """
3593 return "Slice"
3594
3595 def igetattr(
3596 self, attrname: str, context: InferenceContext | None = None
3597 ) -> Iterator[SuccessfulInferenceResult]:
3598 """Infer the possible values of the given attribute on the slice.
3599
3600 :param attrname: The name of the attribute to infer.
3601
3602 :returns: The inferred possible values.
3603 """
3604 if attrname == "start":
3605 yield self._wrap_attribute(self.lower)
3606 elif attrname == "stop":
3607 yield self._wrap_attribute(self.upper)
3608 elif attrname == "step":
3609 yield self._wrap_attribute(self.step)
3610 else:
3611 yield from self.getattr(attrname, context=context)
3612
3613 def getattr(self, attrname, context: InferenceContext | None = None):
3614 return self._proxied.getattr(attrname, context)
3615
3616 def get_children(self):
3617 if self.lower is not None:
3618 yield self.lower
3619
3620 if self.upper is not None:
3621 yield self.upper
3622
3623 if self.step is not None:
3624 yield self.step
3625
3626 def _infer(self, context: InferenceContext | None = None) -> Iterator[Slice]:
3627 yield self
3628
3629
3630class Starred(_base_nodes.ParentAssignNode):
3631 """Class representing an :class:`ast.Starred` node.
3632
3633 >>> import astroid
3634 >>> node = astroid.extract_node('*args')
3635 >>> node
3636 <Starred l.1 at 0x...>
3637 """
3638
3639 _astroid_fields = ("value",)
3640 _other_fields = ("ctx",)
3641
3642 value: NodeNG
3643 """What is being unpacked."""
3644
3645 def __init__(
3646 self,
3647 ctx: Context,
3648 lineno: int,
3649 col_offset: int,
3650 parent: NodeNG,
3651 *,
3652 end_lineno: int | None,
3653 end_col_offset: int | None,
3654 ) -> None:
3655 self.ctx = ctx
3656 """Whether the starred item is assigned to or loaded from."""
3657
3658 super().__init__(
3659 lineno=lineno,
3660 col_offset=col_offset,
3661 end_lineno=end_lineno,
3662 end_col_offset=end_col_offset,
3663 parent=parent,
3664 )
3665
3666 def postinit(self, value: NodeNG) -> None:
3667 self.value = value
3668
3669 assigned_stmts = protocols.starred_assigned_stmts
3670 """Returns the assigned statement (non inferred) according to the assignment type.
3671 See astroid/protocols.py for actual implementation.
3672 """
3673
3674 def get_children(self):
3675 yield self.value
3676
3677
3678class Subscript(NodeNG):
3679 """Class representing an :class:`ast.Subscript` node.
3680
3681 >>> import astroid
3682 >>> node = astroid.extract_node('things[1:3]')
3683 >>> node
3684 <Subscript l.1 at 0x...>
3685 """
3686
3687 _SUBSCRIPT_SENTINEL = object()
3688 _astroid_fields = ("value", "slice")
3689 _other_fields = ("ctx",)
3690
3691 value: NodeNG
3692 """What is being indexed."""
3693
3694 slice: NodeNG
3695 """The slice being used to lookup."""
3696
3697 def __init__(
3698 self,
3699 ctx: Context,
3700 lineno: int,
3701 col_offset: int,
3702 parent: NodeNG,
3703 *,
3704 end_lineno: int | None,
3705 end_col_offset: int | None,
3706 ) -> None:
3707 self.ctx = ctx
3708 """Whether the subscripted item is assigned to or loaded from."""
3709
3710 super().__init__(
3711 lineno=lineno,
3712 col_offset=col_offset,
3713 end_lineno=end_lineno,
3714 end_col_offset=end_col_offset,
3715 parent=parent,
3716 )
3717
3718 # pylint: disable=redefined-builtin; had to use the same name as builtin ast module.
3719 def postinit(self, value: NodeNG, slice: NodeNG) -> None:
3720 self.value = value
3721 self.slice = slice
3722
3723 def get_children(self):
3724 yield self.value
3725 yield self.slice
3726
3727 def _infer_subscript(
3728 self, context: InferenceContext | None = None
3729 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
3730 """Inference for subscripts.
3731
3732 We're understanding if the index is a Const
3733 or a slice, passing the result of inference
3734 to the value's `getitem` method, which should
3735 handle each supported index type accordingly.
3736 """
3737 from astroid import helpers # pylint: disable=import-outside-toplevel
3738
3739 found_one = False
3740 for value in self.value.infer(context):
3741 if isinstance(value, util.UninferableBase):
3742 yield util.Uninferable
3743 return None
3744 for index in self.slice.infer(context):
3745 if isinstance(index, util.UninferableBase):
3746 yield util.Uninferable
3747 return None
3748
3749 # Try to deduce the index value.
3750 index_value = self._SUBSCRIPT_SENTINEL
3751 if value.__class__ == Instance:
3752 index_value = index
3753 elif index.__class__ == Instance:
3754 instance_as_index = helpers.class_instance_as_index(index)
3755 if instance_as_index:
3756 index_value = instance_as_index
3757 else:
3758 index_value = index
3759
3760 if index_value is self._SUBSCRIPT_SENTINEL:
3761 raise InferenceError(node=self, context=context)
3762
3763 try:
3764 assigned = value.getitem(index_value, context)
3765 except (
3766 AstroidTypeError,
3767 AstroidIndexError,
3768 AstroidValueError,
3769 AttributeInferenceError,
3770 AttributeError,
3771 ) as exc:
3772 raise InferenceError(node=self, context=context) from exc
3773
3774 # Prevent inferring if the inferred subscript
3775 # is the same as the original subscripted object.
3776 if self is assigned or isinstance(assigned, util.UninferableBase):
3777 yield util.Uninferable
3778 return None
3779 yield from assigned.infer(context)
3780 found_one = True
3781
3782 if found_one:
3783 return InferenceErrorInfo(node=self, context=context)
3784 return None
3785
3786 @decorators.raise_if_nothing_inferred
3787 @decorators.path_wrapper
3788 def _infer(self, context: InferenceContext | None = None):
3789 return self._infer_subscript(context)
3790
3791 @decorators.raise_if_nothing_inferred
3792 def infer_lhs(self, context: InferenceContext | None = None):
3793 return self._infer_subscript(context)
3794
3795
3796class Try(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
3797 """Class representing a :class:`ast.Try` node.
3798
3799 >>> import astroid
3800 >>> node = astroid.extract_node('''
3801 ... try:
3802 ... do_something()
3803 ... except Exception as error:
3804 ... print("Error!")
3805 ... finally:
3806 ... print("Cleanup!")
3807 ... ''')
3808 >>> node
3809 <Try l.2 at 0x...>
3810 """
3811
3812 _astroid_fields = ("body", "handlers", "orelse", "finalbody")
3813 _multi_line_block_fields = ("body", "handlers", "orelse", "finalbody")
3814
3815 def __init__(
3816 self,
3817 *,
3818 lineno: int,
3819 col_offset: int,
3820 end_lineno: int,
3821 end_col_offset: int,
3822 parent: NodeNG,
3823 ) -> None:
3824 """
3825 :param lineno: The line that this node appears on in the source code.
3826
3827 :param col_offset: The column that this node appears on in the
3828 source code.
3829
3830 :param parent: The parent node in the syntax tree.
3831
3832 :param end_lineno: The last line this node appears on in the source code.
3833
3834 :param end_col_offset: The end column this node appears on in the
3835 source code. Note: This is after the last symbol.
3836 """
3837 self.body: list[NodeNG] = []
3838 """The contents of the block to catch exceptions from."""
3839
3840 self.handlers: list[ExceptHandler] = []
3841 """The exception handlers."""
3842
3843 self.orelse: list[NodeNG] = []
3844 """The contents of the ``else`` block."""
3845
3846 self.finalbody: list[NodeNG] = []
3847 """The contents of the ``finally`` block."""
3848
3849 super().__init__(
3850 lineno=lineno,
3851 col_offset=col_offset,
3852 end_lineno=end_lineno,
3853 end_col_offset=end_col_offset,
3854 parent=parent,
3855 )
3856
3857 def postinit(
3858 self,
3859 *,
3860 body: list[NodeNG],
3861 handlers: list[ExceptHandler],
3862 orelse: list[NodeNG],
3863 finalbody: list[NodeNG],
3864 ) -> None:
3865 """Do some setup after initialisation.
3866
3867 :param body: The contents of the block to catch exceptions from.
3868
3869 :param handlers: The exception handlers.
3870
3871 :param orelse: The contents of the ``else`` block.
3872
3873 :param finalbody: The contents of the ``finally`` block.
3874 """
3875 self.body = body
3876 self.handlers = handlers
3877 self.orelse = orelse
3878 self.finalbody = finalbody
3879
3880 def _infer_name(self, frame, name):
3881 return name
3882
3883 def block_range(self, lineno: int) -> tuple[int, int]:
3884 """Get a range from a given line number to where this node ends."""
3885 for exhandler in self.handlers:
3886 if exhandler.type and lineno == exhandler.type.fromlineno:
3887 return lineno, exhandler.tolineno
3888 if exhandler.body[0].fromlineno <= lineno <= exhandler.body[-1].tolineno:
3889 return lineno, exhandler.body[-1].tolineno
3890 if self.finalbody:
3891 if self.finalbody[0].fromlineno - 1 == lineno:
3892 return lineno, self.finalbody[0].tolineno
3893 if self.finalbody[0].fromlineno <= lineno <= self.finalbody[-1].tolineno:
3894 return lineno, self.finalbody[-1].tolineno
3895
3896 # If not within any of the ExceptHandlers or `finally` body, fall back to regular
3897 # handling of block_range for nodes with a potential `else` statement.
3898 return super().block_range(lineno)
3899
3900 def get_children(self):
3901 yield from self.body
3902 yield from self.handlers
3903 yield from self.orelse
3904 yield from self.finalbody
3905
3906
3907class TryStar(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
3908 """Class representing an :class:`ast.TryStar` node."""
3909
3910 _astroid_fields = ("body", "handlers", "orelse", "finalbody")
3911 _multi_line_block_fields = ("body", "handlers", "orelse", "finalbody")
3912
3913 def __init__(
3914 self,
3915 *,
3916 lineno: int | None = None,
3917 col_offset: int | None = None,
3918 end_lineno: int | None = None,
3919 end_col_offset: int | None = None,
3920 parent: NodeNG | None = None,
3921 ) -> None:
3922 """
3923 :param lineno: The line that this node appears on in the source code.
3924 :param col_offset: The column that this node appears on in the
3925 source code.
3926 :param parent: The parent node in the syntax tree.
3927 :param end_lineno: The last line this node appears on in the source code.
3928 :param end_col_offset: The end column this node appears on in the
3929 source code. Note: This is after the last symbol.
3930 """
3931 self.body: list[NodeNG] = []
3932 """The contents of the block to catch exceptions from."""
3933
3934 self.handlers: list[ExceptHandler] = []
3935 """The exception handlers."""
3936
3937 self.orelse: list[NodeNG] = []
3938 """The contents of the ``else`` block."""
3939
3940 self.finalbody: list[NodeNG] = []
3941 """The contents of the ``finally`` block."""
3942
3943 super().__init__(
3944 lineno=lineno,
3945 col_offset=col_offset,
3946 end_lineno=end_lineno,
3947 end_col_offset=end_col_offset,
3948 parent=parent,
3949 )
3950
3951 def postinit(
3952 self,
3953 *,
3954 body: list[NodeNG] | None = None,
3955 handlers: list[ExceptHandler] | None = None,
3956 orelse: list[NodeNG] | None = None,
3957 finalbody: list[NodeNG] | None = None,
3958 ) -> None:
3959 """Do some setup after initialisation.
3960 :param body: The contents of the block to catch exceptions from.
3961 :param handlers: The exception handlers.
3962 :param orelse: The contents of the ``else`` block.
3963 :param finalbody: The contents of the ``finally`` block.
3964 """
3965 if body:
3966 self.body = body
3967 if handlers:
3968 self.handlers = handlers
3969 if orelse:
3970 self.orelse = orelse
3971 if finalbody:
3972 self.finalbody = finalbody
3973
3974 def _infer_name(self, frame, name):
3975 return name
3976
3977 def get_children(self):
3978 yield from self.body
3979 yield from self.handlers
3980 yield from self.orelse
3981 yield from self.finalbody
3982
3983 def block_range(self, lineno: int) -> tuple[int, int]:
3984 """Get a range from a given line number to where this node ends."""
3985 for exhandler in self.handlers:
3986 if exhandler.type and lineno == exhandler.type.fromlineno:
3987 return lineno, exhandler.tolineno
3988 if exhandler.body[0].fromlineno <= lineno <= exhandler.body[-1].tolineno:
3989 return lineno, exhandler.body[-1].tolineno
3990 if self.finalbody:
3991 if self.finalbody[0].fromlineno - 1 == lineno:
3992 return lineno, self.finalbody[0].tolineno
3993 if self.finalbody[0].fromlineno <= lineno <= self.finalbody[-1].tolineno:
3994 return lineno, self.finalbody[-1].tolineno
3995
3996 # If not within any of the ExceptHandlers or `finally` body, fall back to regular
3997 # handling of block_range for nodes with a potential `else` statement.
3998 return super().block_range(lineno)
3999
4000
4001class Tuple(BaseContainer):
4002 """Class representing an :class:`ast.Tuple` node.
4003
4004 >>> import astroid
4005 >>> node = astroid.extract_node('(1, 2, 3)')
4006 >>> node
4007 <Tuple.tuple l.1 at 0x...>
4008 """
4009
4010 _other_fields = ("ctx",)
4011
4012 def __init__(
4013 self,
4014 ctx: Context | None = None,
4015 lineno: int | None = None,
4016 col_offset: int | None = None,
4017 parent: NodeNG | None = None,
4018 *,
4019 end_lineno: int | None = None,
4020 end_col_offset: int | None = None,
4021 ) -> None:
4022 """
4023 :param ctx: Whether the tuple is assigned to or loaded from.
4024
4025 :param lineno: The line that this node appears on in the source code.
4026
4027 :param col_offset: The column that this node appears on in the
4028 source code.
4029
4030 :param parent: The parent node in the syntax tree.
4031
4032 :param end_lineno: The last line this node appears on in the source code.
4033
4034 :param end_col_offset: The end column this node appears on in the
4035 source code. Note: This is after the last symbol.
4036 """
4037 self.ctx: Context | None = ctx
4038 """Whether the tuple is assigned to or loaded from."""
4039
4040 super().__init__(
4041 lineno=lineno,
4042 col_offset=col_offset,
4043 end_lineno=end_lineno,
4044 end_col_offset=end_col_offset,
4045 parent=parent,
4046 )
4047
4048 assigned_stmts = protocols.sequence_assigned_stmts
4049 """Returns the assigned statement (non inferred) according to the assignment type.
4050 See astroid/protocols.py for actual implementation.
4051 """
4052
4053 infer_unary_op = protocols.tuple_infer_unary_op
4054 infer_binary_op = protocols.tl_infer_binary_op
4055
4056 def pytype(self) -> Literal["builtins.tuple"]:
4057 """Get the name of the type that this node represents.
4058
4059 :returns: The name of the type.
4060 """
4061 return "builtins.tuple"
4062
4063 def getitem(
4064 self, index: SuccessfulInferenceResult, context: InferenceContext | None = None
4065 ) -> InferenceResult:
4066 """Get an item from this node.
4067
4068 :param index: The node to use as a subscript index.
4069 """
4070 return _container_getitem(self, self.elts, index, context=context)
4071
4072
4073class TypeAlias(_base_nodes.AssignTypeNode, _base_nodes.Statement):
4074 """Class representing a :class:`ast.TypeAlias` node.
4075
4076 >>> import astroid
4077 >>> node = astroid.extract_node('type Point = tuple[float, float]')
4078 >>> node
4079 <TypeAlias l.1 at 0x...>
4080 """
4081
4082 _astroid_fields = ("name", "type_params", "value")
4083
4084 name: AssignName
4085 type_params: list[TypeVar | ParamSpec | TypeVarTuple]
4086 value: NodeNG
4087
4088 def __init__(
4089 self,
4090 lineno: int,
4091 col_offset: int,
4092 parent: NodeNG,
4093 *,
4094 end_lineno: int,
4095 end_col_offset: int,
4096 ) -> None:
4097 super().__init__(
4098 lineno=lineno,
4099 col_offset=col_offset,
4100 end_lineno=end_lineno,
4101 end_col_offset=end_col_offset,
4102 parent=parent,
4103 )
4104
4105 def postinit(
4106 self,
4107 *,
4108 name: AssignName,
4109 type_params: list[TypeVar | ParamSpec | TypeVarTuple],
4110 value: NodeNG,
4111 ) -> None:
4112 self.name = name
4113 self.type_params = type_params
4114 self.value = value
4115
4116 def pytype(self) -> Literal["typing.TypeAliasType"]:
4117 """Get the name of the type that this node represents.
4118
4119 :returns: The name of the type.
4120 """
4121 return "typing.TypeAliasType"
4122
4123 def qname(self) -> Literal["typing.TypeAliasType"]:
4124 """Get the qualified name of the type that this node represents.
4125
4126 :returns: The qualified name of the type.
4127 """
4128 return "typing.TypeAliasType"
4129
4130 def _infer(self, context: InferenceContext | None = None) -> Iterator[TypeAlias]:
4131 yield self
4132
4133 assigned_stmts: ClassVar[
4134 Callable[
4135 [
4136 TypeAlias,
4137 AssignName,
4138 InferenceContext | None,
4139 None,
4140 ],
4141 Generator[NodeNG],
4142 ]
4143 ] = protocols.assign_assigned_stmts
4144
4145
4146class TypeVar(_base_nodes.AssignTypeNode):
4147 """Class representing a :class:`ast.TypeVar` node.
4148
4149 >>> import astroid
4150 >>> node = astroid.extract_node('type Point[T] = tuple[float, float]')
4151 >>> node.type_params[0]
4152 <TypeVar l.1 at 0x...>
4153 """
4154
4155 _astroid_fields = ("name", "bound", "default_value")
4156 name: AssignName
4157 bound: NodeNG | None
4158 default_value: NodeNG | None
4159
4160 def __init__(
4161 self,
4162 lineno: int,
4163 col_offset: int,
4164 parent: NodeNG,
4165 *,
4166 end_lineno: int,
4167 end_col_offset: int,
4168 ) -> None:
4169 super().__init__(
4170 lineno=lineno,
4171 col_offset=col_offset,
4172 end_lineno=end_lineno,
4173 end_col_offset=end_col_offset,
4174 parent=parent,
4175 )
4176
4177 def postinit(
4178 self,
4179 *,
4180 name: AssignName,
4181 bound: NodeNG | None,
4182 default_value: NodeNG | None = None,
4183 ) -> None:
4184 self.name = name
4185 self.bound = bound
4186 self.default_value = default_value
4187
4188 def pytype(self) -> Literal["typing.TypeVar"]:
4189 """Get the name of the type that this node represents.
4190
4191 :returns: The name of the type.
4192 """
4193 return "typing.TypeVar"
4194
4195 def qname(self) -> Literal["typing.TypeVar"]:
4196 """Get the qualified name of the type that this node represents.
4197
4198 :returns: The qualified name of the type.
4199 """
4200 return "typing.TypeVar"
4201
4202 def _infer(self, context: InferenceContext | None = None) -> Iterator[TypeVar]:
4203 yield self
4204
4205 assigned_stmts = protocols.generic_type_assigned_stmts
4206 """Returns the assigned statement (non inferred) according to the assignment type.
4207 See astroid/protocols.py for actual implementation.
4208 """
4209
4210
4211class TypeVarTuple(_base_nodes.AssignTypeNode):
4212 """Class representing a :class:`ast.TypeVarTuple` node.
4213
4214 >>> import astroid
4215 >>> node = astroid.extract_node('type Alias[*Ts] = tuple[*Ts]')
4216 >>> node.type_params[0]
4217 <TypeVarTuple l.1 at 0x...>
4218 """
4219
4220 _astroid_fields = ("name", "default_value")
4221 name: AssignName
4222 default_value: NodeNG | None
4223
4224 def __init__(
4225 self,
4226 lineno: int,
4227 col_offset: int,
4228 parent: NodeNG,
4229 *,
4230 end_lineno: int,
4231 end_col_offset: int,
4232 ) -> None:
4233 super().__init__(
4234 lineno=lineno,
4235 col_offset=col_offset,
4236 end_lineno=end_lineno,
4237 end_col_offset=end_col_offset,
4238 parent=parent,
4239 )
4240
4241 def postinit(
4242 self, *, name: AssignName, default_value: NodeNG | None = None
4243 ) -> None:
4244 self.name = name
4245 self.default_value = default_value
4246
4247 def pytype(self) -> Literal["typing.TypeVarTuple"]:
4248 """Get the name of the type that this node represents.
4249
4250 :returns: The name of the type.
4251 """
4252 return "typing.TypeVarTuple"
4253
4254 def qname(self) -> Literal["typing.TypeVarTuple"]:
4255 """Get the qualified name of the type that this node represents.
4256
4257 :returns: The qualified name of the type.
4258 """
4259 return "typing.TypeVarTuple"
4260
4261 def _infer(self, context: InferenceContext | None = None) -> Iterator[TypeVarTuple]:
4262 yield self
4263
4264 assigned_stmts = protocols.generic_type_assigned_stmts
4265 """Returns the assigned statement (non inferred) according to the assignment type.
4266 See astroid/protocols.py for actual implementation.
4267 """
4268
4269
4270UNARY_OP_METHOD = {
4271 "+": "__pos__",
4272 "-": "__neg__",
4273 "~": "__invert__",
4274 "not": None, # 'not' delegates to __bool__, there is no dedicated method
4275}
4276
4277
4278class UnaryOp(_base_nodes.OperatorNode):
4279 """Class representing an :class:`ast.UnaryOp` node.
4280
4281 >>> import astroid
4282 >>> node = astroid.extract_node('-5')
4283 >>> node
4284 <UnaryOp l.1 at 0x...>
4285 """
4286
4287 _astroid_fields = ("operand",)
4288 _other_fields = ("op",)
4289
4290 operand: NodeNG
4291 """What the unary operator is applied to."""
4292
4293 def __init__(
4294 self,
4295 op: str,
4296 lineno: int,
4297 col_offset: int,
4298 parent: NodeNG,
4299 *,
4300 end_lineno: int | None,
4301 end_col_offset: int | None,
4302 ) -> None:
4303 self.op = op
4304 """The operator."""
4305
4306 super().__init__(
4307 lineno=lineno,
4308 col_offset=col_offset,
4309 end_lineno=end_lineno,
4310 end_col_offset=end_col_offset,
4311 parent=parent,
4312 )
4313
4314 def postinit(self, operand: NodeNG) -> None:
4315 self.operand = operand
4316
4317 def type_errors(
4318 self, context: InferenceContext | None = None
4319 ) -> list[util.BadUnaryOperationMessage]:
4320 """Get a list of type errors which can occur during inference.
4321
4322 Each TypeError is represented by a :class:`~astroid.util.BadUnaryOperationMessage`,
4323 which holds the original exception.
4324
4325 If any inferred result is uninferable, an empty list is returned.
4326 """
4327 bad = []
4328 try:
4329 for result in self._infer_unaryop(context=context):
4330 if result is util.Uninferable:
4331 raise InferenceError
4332 if isinstance(result, util.BadUnaryOperationMessage):
4333 bad.append(result)
4334 except InferenceError:
4335 return []
4336 return bad
4337
4338 def get_children(self):
4339 yield self.operand
4340
4341 def op_precedence(self) -> int:
4342 if self.op == "not":
4343 return OP_PRECEDENCE[self.op]
4344
4345 return super().op_precedence()
4346
4347 def _infer_unaryop(
4348 self, context: InferenceContext | None = None
4349 ) -> Generator[
4350 InferenceResult | util.BadUnaryOperationMessage, None, InferenceErrorInfo
4351 ]:
4352 """Infer what an UnaryOp should return when evaluated."""
4353 from astroid.nodes import ClassDef # pylint: disable=import-outside-toplevel
4354
4355 for operand in self.operand.infer(context):
4356 try:
4357 yield operand.infer_unary_op(self.op)
4358 except TypeError as exc:
4359 # The operand doesn't support this operation.
4360 yield util.BadUnaryOperationMessage(operand, self.op, exc)
4361 except AttributeError as exc:
4362 meth = UNARY_OP_METHOD[self.op]
4363 if meth is None:
4364 # `not node`. Determine node's boolean
4365 # value and negate its result, unless it is
4366 # Uninferable, which will be returned as is.
4367 bool_value = operand.bool_value()
4368 if not isinstance(bool_value, util.UninferableBase):
4369 yield const_factory(not bool_value)
4370 else:
4371 yield util.Uninferable
4372 else:
4373 if not isinstance(operand, (Instance, ClassDef)):
4374 # The operation was used on something which
4375 # doesn't support it.
4376 yield util.BadUnaryOperationMessage(operand, self.op, exc)
4377 continue
4378
4379 try:
4380 try:
4381 methods = dunder_lookup.lookup(operand, meth)
4382 except AttributeInferenceError:
4383 yield util.BadUnaryOperationMessage(operand, self.op, exc)
4384 continue
4385
4386 meth = methods[0]
4387 inferred = next(meth.infer(context=context), None)
4388 if (
4389 isinstance(inferred, util.UninferableBase)
4390 or not inferred.callable()
4391 ):
4392 continue
4393
4394 context = copy_context(context)
4395 context.boundnode = operand
4396 context.callcontext = CallContext(args=[], callee=inferred)
4397
4398 call_results = inferred.infer_call_result(self, context=context)
4399 result = next(call_results, None)
4400 if result is None:
4401 # Failed to infer, return the same type.
4402 yield operand
4403 else:
4404 yield result
4405 except AttributeInferenceError as inner_exc:
4406 # The unary operation special method was not found.
4407 yield util.BadUnaryOperationMessage(operand, self.op, inner_exc)
4408 except InferenceError:
4409 yield util.Uninferable
4410
4411 @decorators.raise_if_nothing_inferred
4412 @decorators.path_wrapper
4413 def _infer(
4414 self, context: InferenceContext | None = None
4415 ) -> Generator[InferenceResult, None, InferenceErrorInfo]:
4416 """Infer what an UnaryOp should return when evaluated."""
4417 yield from self._filter_operation_errors(
4418 self._infer_unaryop, context, util.BadUnaryOperationMessage
4419 )
4420 return InferenceErrorInfo(node=self, context=context)
4421
4422
4423class While(_base_nodes.MultiLineWithElseBlockNode, _base_nodes.Statement):
4424 """Class representing an :class:`ast.While` node.
4425
4426 >>> import astroid
4427 >>> node = astroid.extract_node('''
4428 ... while condition():
4429 ... print("True")
4430 ... ''')
4431 >>> node
4432 <While l.2 at 0x...>
4433 """
4434
4435 _astroid_fields = ("test", "body", "orelse")
4436 _multi_line_block_fields = ("body", "orelse")
4437
4438 test: NodeNG
4439 """The condition that the loop tests."""
4440
4441 body: list[NodeNG]
4442 """The contents of the loop."""
4443
4444 orelse: list[NodeNG]
4445 """The contents of the ``else`` block."""
4446
4447 def postinit(
4448 self,
4449 test: NodeNG,
4450 body: list[NodeNG],
4451 orelse: list[NodeNG],
4452 ) -> None:
4453 self.test = test
4454 self.body = body
4455 self.orelse = orelse
4456
4457 @cached_property
4458 def blockstart_tolineno(self) -> int:
4459 """The line on which the beginning of this block ends."""
4460 return self.test.tolineno
4461
4462 def get_children(self):
4463 yield self.test
4464
4465 yield from self.body
4466 yield from self.orelse
4467
4468 def _get_yield_nodes_skip_functions(self):
4469 """A While node can contain a Yield node in the test"""
4470 yield from self.test._get_yield_nodes_skip_functions()
4471 yield from super()._get_yield_nodes_skip_functions()
4472
4473 def _get_yield_nodes_skip_lambdas(self):
4474 """A While node can contain a Yield node in the test"""
4475 yield from self.test._get_yield_nodes_skip_lambdas()
4476 yield from super()._get_yield_nodes_skip_lambdas()
4477
4478
4479class With(
4480 _base_nodes.MultiLineWithElseBlockNode,
4481 _base_nodes.AssignTypeNode,
4482 _base_nodes.Statement,
4483):
4484 """Class representing an :class:`ast.With` node.
4485
4486 >>> import astroid
4487 >>> node = astroid.extract_node('''
4488 ... with open(file_path) as file_:
4489 ... print(file_.read())
4490 ... ''')
4491 >>> node
4492 <With l.2 at 0x...>
4493 """
4494
4495 _astroid_fields = ("items", "body")
4496 _other_other_fields = ("type_annotation",)
4497 _multi_line_block_fields = ("body",)
4498
4499 def __init__(
4500 self,
4501 lineno: int | None = None,
4502 col_offset: int | None = None,
4503 parent: NodeNG | None = None,
4504 *,
4505 end_lineno: int | None = None,
4506 end_col_offset: int | None = None,
4507 ) -> None:
4508 """
4509 :param lineno: The line that this node appears on in the source code.
4510
4511 :param col_offset: The column that this node appears on in the
4512 source code.
4513
4514 :param parent: The parent node in the syntax tree.
4515
4516 :param end_lineno: The last line this node appears on in the source code.
4517
4518 :param end_col_offset: The end column this node appears on in the
4519 source code. Note: This is after the last symbol.
4520 """
4521 self.items: list[tuple[NodeNG, NodeNG | None]] = []
4522 """The pairs of context managers and the names they are assigned to."""
4523
4524 self.body: list[NodeNG] = []
4525 """The contents of the ``with`` block."""
4526
4527 self.type_annotation: NodeNG | None = None # can be None
4528 """If present, this will contain the type annotation passed by a type comment"""
4529
4530 super().__init__(
4531 lineno=lineno,
4532 col_offset=col_offset,
4533 end_lineno=end_lineno,
4534 end_col_offset=end_col_offset,
4535 parent=parent,
4536 )
4537
4538 def postinit(
4539 self,
4540 items: list[tuple[NodeNG, NodeNG | None]] | None = None,
4541 body: list[NodeNG] | None = None,
4542 type_annotation: NodeNG | None = None,
4543 ) -> None:
4544 """Do some setup after initialisation.
4545
4546 :param items: The pairs of context managers and the names
4547 they are assigned to.
4548
4549 :param body: The contents of the ``with`` block.
4550 """
4551 if items is not None:
4552 self.items = items
4553 if body is not None:
4554 self.body = body
4555 self.type_annotation = type_annotation
4556
4557 assigned_stmts = protocols.with_assigned_stmts
4558 """Returns the assigned statement (non inferred) according to the assignment type.
4559 See astroid/protocols.py for actual implementation.
4560 """
4561
4562 @cached_property
4563 def blockstart_tolineno(self) -> int:
4564 """The line on which the beginning of this block ends."""
4565 return self.items[-1][0].tolineno
4566
4567 def get_children(self) -> Iterator[NodeNG]:
4568 """Get the child nodes below this node.
4569
4570 :returns: The children.
4571 """
4572 for expr, var in self.items:
4573 yield expr
4574 if var:
4575 yield var
4576 yield from self.body
4577
4578
4579class AsyncWith(With):
4580 """Asynchronous ``with`` built with the ``async`` keyword."""
4581
4582
4583class Yield(NodeNG):
4584 """Class representing an :class:`ast.Yield` node.
4585
4586 >>> import astroid
4587 >>> node = astroid.extract_node('yield True')
4588 >>> node
4589 <Yield l.1 at 0x...>
4590 """
4591
4592 _astroid_fields = ("value",)
4593
4594 value: NodeNG | None
4595 """The value to yield."""
4596
4597 def postinit(self, value: NodeNG | None) -> None:
4598 self.value = value
4599
4600 def get_children(self):
4601 if self.value is not None:
4602 yield self.value
4603
4604 def _get_yield_nodes_skip_functions(self):
4605 yield self
4606
4607 def _get_yield_nodes_skip_lambdas(self):
4608 yield self
4609
4610
4611class YieldFrom(Yield): # TODO value is required, not optional
4612 """Class representing an :class:`ast.YieldFrom` node."""
4613
4614
4615class DictUnpack(_base_nodes.NoChildrenNode):
4616 """Represents the unpacking of dicts into dicts using :pep:`448`."""
4617
4618
4619class FormattedValue(NodeNG):
4620 """Class representing an :class:`ast.FormattedValue` node.
4621
4622 Represents a :pep:`498` format string.
4623
4624 >>> import astroid
4625 >>> node = astroid.extract_node('f"Format {type_}"')
4626 >>> node
4627 <JoinedStr l.1 at 0x...>
4628 >>> node.values
4629 [<Const.str l.1 at 0x...>, <FormattedValue l.1 at 0x...>]
4630 """
4631
4632 _astroid_fields = ("value", "format_spec")
4633 _other_fields = ("conversion",)
4634
4635 def __init__(
4636 self,
4637 lineno: int | None = None,
4638 col_offset: int | None = None,
4639 parent: NodeNG | None = None,
4640 *,
4641 end_lineno: int | None = None,
4642 end_col_offset: int | None = None,
4643 ) -> None:
4644 """
4645 :param lineno: The line that this node appears on in the source code.
4646
4647 :param col_offset: The column that this node appears on in the
4648 source code.
4649
4650 :param parent: The parent node in the syntax tree.
4651
4652 :param end_lineno: The last line this node appears on in the source code.
4653
4654 :param end_col_offset: The end column this node appears on in the
4655 source code. Note: This is after the last symbol.
4656 """
4657 self.value: NodeNG
4658 """The value to be formatted into the string."""
4659
4660 self.conversion: int
4661 """The type of formatting to be applied to the value.
4662
4663 .. seealso::
4664 :class:`ast.FormattedValue`
4665 """
4666
4667 self.format_spec: JoinedStr | None = None
4668 """The formatting to be applied to the value.
4669
4670 .. seealso::
4671 :class:`ast.FormattedValue`
4672 """
4673
4674 super().__init__(
4675 lineno=lineno,
4676 col_offset=col_offset,
4677 end_lineno=end_lineno,
4678 end_col_offset=end_col_offset,
4679 parent=parent,
4680 )
4681
4682 def postinit(
4683 self,
4684 *,
4685 value: NodeNG,
4686 conversion: int,
4687 format_spec: JoinedStr | None = None,
4688 ) -> None:
4689 """Do some setup after initialisation.
4690
4691 :param value: The value to be formatted into the string.
4692
4693 :param conversion: The type of formatting to be applied to the value.
4694
4695 :param format_spec: The formatting to be applied to the value.
4696 """
4697 self.value = value
4698 self.conversion = conversion
4699 self.format_spec = format_spec
4700
4701 def get_children(self):
4702 yield self.value
4703
4704 if self.format_spec is not None:
4705 yield self.format_spec
4706
4707 def _infer(
4708 self, context: InferenceContext | None = None
4709 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4710 format_specs = Const("") if self.format_spec is None else self.format_spec
4711 uninferable_already_generated = False
4712 for format_spec in format_specs.infer(context):
4713 if not isinstance(format_spec, Const):
4714 if not uninferable_already_generated:
4715 yield util.Uninferable
4716 uninferable_already_generated = True
4717 continue
4718 for value in self.value.infer(context):
4719 if value is util.Uninferable:
4720 yield util.Uninferable
4721 return
4722 value_to_format = value
4723 if isinstance(value, Const):
4724 value_to_format = value.value
4725 if isinstance(format_spec.value, str) and util.format_spec_too_large(
4726 format_spec.value
4727 ):
4728 yield util.Uninferable
4729 uninferable_already_generated = True
4730 continue
4731 try:
4732 formatted = format(value_to_format, format_spec.value)
4733 yield Const(
4734 formatted,
4735 lineno=self.lineno,
4736 col_offset=self.col_offset,
4737 end_lineno=self.end_lineno,
4738 end_col_offset=self.end_col_offset,
4739 )
4740 continue
4741 except (ValueError, TypeError, MemoryError, OverflowError):
4742 # ValueError/TypeError: invalid format spec
4743 # MemoryError: format spec with huge width (e.g. f'{0:11111111111}')
4744 # OverflowError: "c" with an out-of-range code point (e.g. f'{-1:c}')
4745 yield util.Uninferable
4746 uninferable_already_generated = True
4747 continue
4748
4749
4750UNINFERABLE_VALUE = "{Uninferable}"
4751
4752
4753class JoinedStr(NodeNG):
4754 """Represents a list of string expressions to be joined.
4755
4756 >>> import astroid
4757 >>> node = astroid.extract_node('f"Format {type_}"')
4758 >>> node
4759 <JoinedStr l.1 at 0x...>
4760 """
4761
4762 _astroid_fields = ("values",)
4763
4764 def __init__(
4765 self,
4766 lineno: int | None = None,
4767 col_offset: int | None = None,
4768 parent: NodeNG | None = None,
4769 *,
4770 end_lineno: int | None = None,
4771 end_col_offset: int | None = None,
4772 ) -> None:
4773 """
4774 :param lineno: The line that this node appears on in the source code.
4775
4776 :param col_offset: The column that this node appears on in the
4777 source code.
4778
4779 :param parent: The parent node in the syntax tree.
4780
4781 :param end_lineno: The last line this node appears on in the source code.
4782
4783 :param end_col_offset: The end column this node appears on in the
4784 source code. Note: This is after the last symbol.
4785 """
4786 self.values: list[NodeNG] = []
4787 """The string expressions to be joined."""
4788
4789 super().__init__(
4790 lineno=lineno,
4791 col_offset=col_offset,
4792 end_lineno=end_lineno,
4793 end_col_offset=end_col_offset,
4794 parent=parent,
4795 )
4796
4797 def postinit(self, values: list[NodeNG] | None = None) -> None:
4798 """Do some setup after initialisation.
4799
4800 :param value: The string expressions to be joined.
4801 """
4802 if values is not None:
4803 self.values = values
4804
4805 def get_children(self):
4806 yield from self.values
4807
4808 def _infer(
4809 self, context: InferenceContext | None = None
4810 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4811 if self.values:
4812 yield from self._infer_with_values(context)
4813 else:
4814 yield Const("")
4815
4816 def _infer_with_values(
4817 self, context: InferenceContext | None = None
4818 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4819 uninferable_already_generated = False
4820 for inferred in self._infer_from_values(self.values, context):
4821 failed = inferred is util.Uninferable or (
4822 isinstance(inferred, Const) and UNINFERABLE_VALUE in inferred.value
4823 )
4824 if failed:
4825 if not uninferable_already_generated:
4826 uninferable_already_generated = True
4827 yield util.Uninferable
4828 continue
4829 yield inferred
4830
4831 @classmethod
4832 def _infer_from_values(
4833 cls, nodes: list[NodeNG], context: InferenceContext | None = None
4834 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4835 if not nodes:
4836 return
4837 if len(nodes) == 1:
4838 for node in cls._safe_infer_from_node(nodes[0], context):
4839 if isinstance(node, Const):
4840 yield node
4841 continue
4842 yield Const(UNINFERABLE_VALUE)
4843 return
4844 for prefix in cls._safe_infer_from_node(nodes[0], context):
4845 for suffix in cls._infer_from_values(nodes[1:], context):
4846 result = ""
4847 for node in (prefix, suffix):
4848 if isinstance(node, Const):
4849 result += str(node.value)
4850 continue
4851 result += UNINFERABLE_VALUE
4852 yield Const(result)
4853
4854 @classmethod
4855 def _safe_infer_from_node(
4856 cls, node: NodeNG, context: InferenceContext | None = None
4857 ) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
4858 try:
4859 yield from node._infer(context)
4860 except InferenceError:
4861 yield util.Uninferable
4862
4863
4864class NamedExpr(_base_nodes.AssignTypeNode):
4865 """Represents the assignment from the assignment expression
4866
4867 >>> import astroid
4868 >>> module = astroid.parse('if a := 1: pass')
4869 >>> module.body[0].test
4870 <NamedExpr l.1 at 0x...>
4871 """
4872
4873 _astroid_fields = ("target", "value")
4874
4875 optional_assign = True
4876 """Whether this node optionally assigns a variable.
4877
4878 Since NamedExpr are not always called they do not always assign."""
4879
4880 def __init__(
4881 self,
4882 lineno: int | None = None,
4883 col_offset: int | None = None,
4884 parent: NodeNG | None = None,
4885 *,
4886 end_lineno: int | None = None,
4887 end_col_offset: int | None = None,
4888 ) -> None:
4889 """
4890 :param lineno: The line that this node appears on in the source code.
4891
4892 :param col_offset: The column that this node appears on in the
4893 source code.
4894
4895 :param parent: The parent node in the syntax tree.
4896
4897 :param end_lineno: The last line this node appears on in the source code.
4898
4899 :param end_col_offset: The end column this node appears on in the
4900 source code. Note: This is after the last symbol.
4901 """
4902 self.target: NodeNG
4903 """The assignment target"""
4904
4905 self.value: NodeNG
4906 """The value that gets assigned in the expression"""
4907
4908 super().__init__(
4909 lineno=lineno,
4910 col_offset=col_offset,
4911 end_lineno=end_lineno,
4912 end_col_offset=end_col_offset,
4913 parent=parent,
4914 )
4915
4916 def postinit(self, target: NodeNG, value: NodeNG) -> None:
4917 self.target = target
4918 self.value = value
4919
4920 assigned_stmts = protocols.named_expr_assigned_stmts
4921 """Returns the assigned statement (non inferred) according to the assignment type.
4922 See astroid/protocols.py for actual implementation.
4923 """
4924
4925 def frame(self) -> FrameType:
4926 """The first parent frame node.
4927
4928 A frame node is a :class:`Module`, :class:`FunctionDef`,
4929 or :class:`ClassDef`.
4930
4931 :returns: The first parent frame node.
4932 """
4933 if not self.parent:
4934 raise ParentMissingError(target=self)
4935
4936 # For certain parents NamedExpr evaluate to the scope of the parent
4937 if isinstance(self.parent, (Arguments, Keyword, Comprehension)):
4938 if not self.parent.parent:
4939 raise ParentMissingError(target=self.parent)
4940 if not self.parent.parent.parent:
4941 raise ParentMissingError(target=self.parent.parent)
4942 return self.parent.parent.parent.frame()
4943
4944 return self.parent.frame()
4945
4946 def scope(self) -> LocalsDictNodeNG:
4947 """The first parent node defining a new scope.
4948 These can be Module, FunctionDef, ClassDef, Lambda, or GeneratorExp nodes.
4949
4950 :returns: The first parent scope node.
4951 """
4952 if not self.parent:
4953 raise ParentMissingError(target=self)
4954
4955 # For certain parents NamedExpr evaluate to the scope of the parent
4956 if isinstance(self.parent, (Arguments, Keyword, Comprehension)):
4957 if not self.parent.parent:
4958 raise ParentMissingError(target=self.parent)
4959 if not self.parent.parent.parent:
4960 raise ParentMissingError(target=self.parent.parent)
4961 return self.parent.parent.parent.scope()
4962
4963 return self.parent.scope()
4964
4965 def set_local(self, name: str, stmt: NodeNG) -> None:
4966 """Define that the given name is declared in the given statement node.
4967 NamedExpr's in Arguments, Keyword or Comprehension are evaluated in their
4968 parent's parent scope. So we add to their frame's locals.
4969
4970 .. seealso:: :meth:`scope`
4971
4972 :param name: The name that is being defined.
4973
4974 :param stmt: The statement that defines the given name.
4975 """
4976 self.frame().set_local(name, stmt)
4977
4978
4979class Unknown(_base_nodes.AssignTypeNode):
4980 """This node represents a node in a constructed AST where
4981 introspection is not possible.
4982
4983 Used in the args attribute of FunctionDef nodes where function signature
4984 introspection failed, and as a placeholder in ObjectModel.
4985 """
4986
4987 name = "Unknown"
4988
4989 def __init__(
4990 self,
4991 parent: NodeNG,
4992 lineno: None = None,
4993 col_offset: None = None,
4994 *,
4995 end_lineno: None = None,
4996 end_col_offset: None = None,
4997 ) -> None:
4998 super().__init__(
4999 lineno=lineno,
5000 col_offset=col_offset,
5001 end_lineno=end_lineno,
5002 end_col_offset=end_col_offset,
5003 parent=parent,
5004 )
5005
5006 def qname(self) -> Literal["Unknown"]:
5007 return "Unknown"
5008
5009 def _infer(self, context: InferenceContext | None = None):
5010 """Inference on an Unknown node immediately terminates."""
5011 yield util.Uninferable
5012
5013
5014UNATTACHED_UNKNOWN = Unknown(parent=SYNTHETIC_ROOT)
5015
5016
5017class EvaluatedObject(NodeNG):
5018 """Contains an object that has already been inferred
5019
5020 This class is useful to pre-evaluate a particular node,
5021 with the resulting class acting as the non-evaluated node.
5022 """
5023
5024 name = "EvaluatedObject"
5025 _astroid_fields = ("original",)
5026 _other_fields = ("value",)
5027
5028 def __init__(
5029 self, original: SuccessfulInferenceResult, value: InferenceResult
5030 ) -> None:
5031 self.original: SuccessfulInferenceResult = original
5032 """The original node that has already been evaluated"""
5033
5034 self.value: InferenceResult = value
5035 """The inferred value"""
5036
5037 super().__init__(
5038 lineno=self.original.lineno,
5039 col_offset=self.original.col_offset,
5040 parent=self.original.parent,
5041 end_lineno=self.original.end_lineno,
5042 end_col_offset=self.original.end_col_offset,
5043 )
5044
5045 def _infer(
5046 self, context: InferenceContext | None = None
5047 ) -> Generator[NodeNG | util.UninferableBase]:
5048 yield self.value
5049
5050
5051# Pattern matching #######################################################
5052
5053
5054class Match(_base_nodes.Statement, _base_nodes.MultiLineBlockNode):
5055 """Class representing a :class:`ast.Match` node.
5056
5057 >>> import astroid
5058 >>> node = astroid.extract_node('''
5059 ... match x:
5060 ... case 200:
5061 ... ...
5062 ... case _:
5063 ... ...
5064 ... ''')
5065 >>> node
5066 <Match l.2 at 0x...>
5067 """
5068
5069 _astroid_fields = ("subject", "cases")
5070 _multi_line_block_fields = ("cases",)
5071
5072 def __init__(
5073 self,
5074 lineno: int | None = None,
5075 col_offset: int | None = None,
5076 parent: NodeNG | None = None,
5077 *,
5078 end_lineno: int | None = None,
5079 end_col_offset: int | None = None,
5080 ) -> None:
5081 self.subject: NodeNG
5082 self.cases: list[MatchCase]
5083 super().__init__(
5084 lineno=lineno,
5085 col_offset=col_offset,
5086 end_lineno=end_lineno,
5087 end_col_offset=end_col_offset,
5088 parent=parent,
5089 )
5090
5091 def postinit(
5092 self,
5093 *,
5094 subject: NodeNG,
5095 cases: list[MatchCase],
5096 ) -> None:
5097 self.subject = subject
5098 self.cases = cases
5099
5100
5101class Pattern(NodeNG):
5102 """Base class for all Pattern nodes."""
5103
5104
5105class MatchCase(_base_nodes.MultiLineBlockNode):
5106 """Class representing a :class:`ast.match_case` node.
5107
5108 >>> import astroid
5109 >>> node = astroid.extract_node('''
5110 ... match x:
5111 ... case 200:
5112 ... ...
5113 ... ''')
5114 >>> node.cases[0]
5115 <MatchCase l.3 at 0x...>
5116 """
5117
5118 _astroid_fields = ("pattern", "guard", "body")
5119 _multi_line_block_fields = ("body",)
5120
5121 lineno: None
5122 col_offset: None
5123 end_lineno: None
5124 end_col_offset: None
5125
5126 def __init__(self, *, parent: NodeNG | None = None) -> None:
5127 self.pattern: Pattern
5128 self.guard: NodeNG | None
5129 self.body: list[NodeNG]
5130 super().__init__(
5131 parent=parent,
5132 lineno=None,
5133 col_offset=None,
5134 end_lineno=None,
5135 end_col_offset=None,
5136 )
5137
5138 def postinit(
5139 self,
5140 *,
5141 pattern: Pattern,
5142 guard: NodeNG | None,
5143 body: list[NodeNG],
5144 ) -> None:
5145 self.pattern = pattern
5146 self.guard = guard
5147 self.body = body
5148
5149
5150class MatchValue(Pattern):
5151 """Class representing a :class:`ast.MatchValue` node.
5152
5153 >>> import astroid
5154 >>> node = astroid.extract_node('''
5155 ... match x:
5156 ... case 200:
5157 ... ...
5158 ... ''')
5159 >>> node.cases[0].pattern
5160 <MatchValue l.3 at 0x...>
5161 """
5162
5163 _astroid_fields = ("value",)
5164
5165 def __init__(
5166 self,
5167 lineno: int | None = None,
5168 col_offset: int | None = None,
5169 parent: NodeNG | None = None,
5170 *,
5171 end_lineno: int | None = None,
5172 end_col_offset: int | None = None,
5173 ) -> None:
5174 self.value: NodeNG
5175 super().__init__(
5176 lineno=lineno,
5177 col_offset=col_offset,
5178 end_lineno=end_lineno,
5179 end_col_offset=end_col_offset,
5180 parent=parent,
5181 )
5182
5183 def postinit(self, *, value: NodeNG) -> None:
5184 self.value = value
5185
5186
5187class MatchSingleton(Pattern):
5188 """Class representing a :class:`ast.MatchSingleton` node.
5189
5190 >>> import astroid
5191 >>> node = astroid.extract_node('''
5192 ... match x:
5193 ... case True:
5194 ... ...
5195 ... case False:
5196 ... ...
5197 ... case None:
5198 ... ...
5199 ... ''')
5200 >>> node.cases[0].pattern
5201 <MatchSingleton l.3 at 0x...>
5202 >>> node.cases[1].pattern
5203 <MatchSingleton l.5 at 0x...>
5204 >>> node.cases[2].pattern
5205 <MatchSingleton l.7 at 0x...>
5206 """
5207
5208 _other_fields = ("value",)
5209
5210 def __init__(
5211 self,
5212 *,
5213 value: Literal[True, False, None],
5214 lineno: int | None = None,
5215 col_offset: int | None = None,
5216 end_lineno: int | None = None,
5217 end_col_offset: int | None = None,
5218 parent: NodeNG | None = None,
5219 ) -> None:
5220 self.value = value
5221 super().__init__(
5222 lineno=lineno,
5223 col_offset=col_offset,
5224 end_lineno=end_lineno,
5225 end_col_offset=end_col_offset,
5226 parent=parent,
5227 )
5228
5229
5230class MatchSequence(Pattern):
5231 """Class representing a :class:`ast.MatchSequence` node.
5232
5233 >>> import astroid
5234 >>> node = astroid.extract_node('''
5235 ... match x:
5236 ... case [1, 2]:
5237 ... ...
5238 ... case (1, 2, *_):
5239 ... ...
5240 ... ''')
5241 >>> node.cases[0].pattern
5242 <MatchSequence l.3 at 0x...>
5243 >>> node.cases[1].pattern
5244 <MatchSequence l.5 at 0x...>
5245 """
5246
5247 _astroid_fields = ("patterns",)
5248
5249 def __init__(
5250 self,
5251 lineno: int | None = None,
5252 col_offset: int | None = None,
5253 parent: NodeNG | None = None,
5254 *,
5255 end_lineno: int | None = None,
5256 end_col_offset: int | None = None,
5257 ) -> None:
5258 self.patterns: list[Pattern]
5259 super().__init__(
5260 lineno=lineno,
5261 col_offset=col_offset,
5262 end_lineno=end_lineno,
5263 end_col_offset=end_col_offset,
5264 parent=parent,
5265 )
5266
5267 def postinit(self, *, patterns: list[Pattern]) -> None:
5268 self.patterns = patterns
5269
5270
5271class MatchMapping(_base_nodes.AssignTypeNode, Pattern):
5272 """Class representing a :class:`ast.MatchMapping` node.
5273
5274 >>> import astroid
5275 >>> node = astroid.extract_node('''
5276 ... match x:
5277 ... case {1: "Hello", 2: "World", 3: _, **rest}:
5278 ... ...
5279 ... ''')
5280 >>> node.cases[0].pattern
5281 <MatchMapping l.3 at 0x...>
5282 """
5283
5284 _astroid_fields = ("keys", "patterns", "rest")
5285
5286 def __init__(
5287 self,
5288 lineno: int | None = None,
5289 col_offset: int | None = None,
5290 parent: NodeNG | None = None,
5291 *,
5292 end_lineno: int | None = None,
5293 end_col_offset: int | None = None,
5294 ) -> None:
5295 self.keys: list[NodeNG]
5296 self.patterns: list[Pattern]
5297 self.rest: AssignName | None
5298 super().__init__(
5299 lineno=lineno,
5300 col_offset=col_offset,
5301 end_lineno=end_lineno,
5302 end_col_offset=end_col_offset,
5303 parent=parent,
5304 )
5305
5306 def postinit(
5307 self,
5308 *,
5309 keys: list[NodeNG],
5310 patterns: list[Pattern],
5311 rest: AssignName | None,
5312 ) -> None:
5313 self.keys = keys
5314 self.patterns = patterns
5315 self.rest = rest
5316
5317 assigned_stmts = protocols.match_mapping_assigned_stmts
5318 """Returns the assigned statement (non inferred) according to the assignment type.
5319 See astroid/protocols.py for actual implementation.
5320 """
5321
5322
5323class MatchClass(Pattern):
5324 """Class representing a :class:`ast.MatchClass` node.
5325
5326 >>> import astroid
5327 >>> node = astroid.extract_node('''
5328 ... match x:
5329 ... case Point2D(0, 0):
5330 ... ...
5331 ... case Point3D(x=0, y=0, z=0):
5332 ... ...
5333 ... ''')
5334 >>> node.cases[0].pattern
5335 <MatchClass l.3 at 0x...>
5336 >>> node.cases[1].pattern
5337 <MatchClass l.5 at 0x...>
5338 """
5339
5340 _astroid_fields = ("cls", "patterns", "kwd_patterns")
5341 _other_fields = ("kwd_attrs",)
5342
5343 def __init__(
5344 self,
5345 lineno: int | None = None,
5346 col_offset: int | None = None,
5347 parent: NodeNG | None = None,
5348 *,
5349 end_lineno: int | None = None,
5350 end_col_offset: int | None = None,
5351 ) -> None:
5352 self.cls: NodeNG
5353 self.patterns: list[Pattern]
5354 self.kwd_attrs: list[str]
5355 self.kwd_patterns: list[Pattern]
5356 super().__init__(
5357 lineno=lineno,
5358 col_offset=col_offset,
5359 end_lineno=end_lineno,
5360 end_col_offset=end_col_offset,
5361 parent=parent,
5362 )
5363
5364 def postinit(
5365 self,
5366 *,
5367 cls: NodeNG,
5368 patterns: list[Pattern],
5369 kwd_attrs: list[str],
5370 kwd_patterns: list[Pattern],
5371 ) -> None:
5372 self.cls = cls
5373 self.patterns = patterns
5374 self.kwd_attrs = kwd_attrs
5375 self.kwd_patterns = kwd_patterns
5376
5377
5378class MatchStar(_base_nodes.AssignTypeNode, Pattern):
5379 """Class representing a :class:`ast.MatchStar` node.
5380
5381 >>> import astroid
5382 >>> node = astroid.extract_node('''
5383 ... match x:
5384 ... case [1, *_]:
5385 ... ...
5386 ... ''')
5387 >>> node.cases[0].pattern.patterns[1]
5388 <MatchStar l.3 at 0x...>
5389 """
5390
5391 _astroid_fields = ("name",)
5392
5393 def __init__(
5394 self,
5395 lineno: int | None = None,
5396 col_offset: int | None = None,
5397 parent: NodeNG | None = None,
5398 *,
5399 end_lineno: int | None = None,
5400 end_col_offset: int | None = None,
5401 ) -> None:
5402 self.name: AssignName | None
5403 super().__init__(
5404 lineno=lineno,
5405 col_offset=col_offset,
5406 end_lineno=end_lineno,
5407 end_col_offset=end_col_offset,
5408 parent=parent,
5409 )
5410
5411 def postinit(self, *, name: AssignName | None) -> None:
5412 self.name = name
5413
5414 assigned_stmts = protocols.match_star_assigned_stmts
5415 """Returns the assigned statement (non inferred) according to the assignment type.
5416 See astroid/protocols.py for actual implementation.
5417 """
5418
5419
5420class MatchAs(_base_nodes.AssignTypeNode, Pattern):
5421 """Class representing a :class:`ast.MatchAs` node.
5422
5423 >>> import astroid
5424 >>> node = astroid.extract_node('''
5425 ... match x:
5426 ... case [1, a]:
5427 ... ...
5428 ... case {'key': b}:
5429 ... ...
5430 ... case Point2D(0, 0) as c:
5431 ... ...
5432 ... case d:
5433 ... ...
5434 ... ''')
5435 >>> node.cases[0].pattern.patterns[1]
5436 <MatchAs l.3 at 0x...>
5437 >>> node.cases[1].pattern.patterns[0]
5438 <MatchAs l.5 at 0x...>
5439 >>> node.cases[2].pattern
5440 <MatchAs l.7 at 0x...>
5441 >>> node.cases[3].pattern
5442 <MatchAs l.9 at 0x...>
5443 """
5444
5445 _astroid_fields = ("pattern", "name")
5446
5447 def __init__(
5448 self,
5449 lineno: int | None = None,
5450 col_offset: int | None = None,
5451 parent: NodeNG | None = None,
5452 *,
5453 end_lineno: int | None = None,
5454 end_col_offset: int | None = None,
5455 ) -> None:
5456 self.pattern: Pattern | None
5457 self.name: AssignName | None
5458 super().__init__(
5459 lineno=lineno,
5460 col_offset=col_offset,
5461 end_lineno=end_lineno,
5462 end_col_offset=end_col_offset,
5463 parent=parent,
5464 )
5465
5466 def postinit(
5467 self,
5468 *,
5469 pattern: Pattern | None,
5470 name: AssignName | None,
5471 ) -> None:
5472 self.pattern = pattern
5473 self.name = name
5474
5475 assigned_stmts = protocols.match_as_assigned_stmts
5476 """Returns the assigned statement (non inferred) according to the assignment type.
5477 See astroid/protocols.py for actual implementation.
5478 """
5479
5480
5481class MatchOr(Pattern):
5482 """Class representing a :class:`ast.MatchOr` node.
5483
5484 >>> import astroid
5485 >>> node = astroid.extract_node('''
5486 ... match x:
5487 ... case 400 | 401 | 402:
5488 ... ...
5489 ... ''')
5490 >>> node.cases[0].pattern
5491 <MatchOr l.3 at 0x...>
5492 """
5493
5494 _astroid_fields = ("patterns",)
5495
5496 def __init__(
5497 self,
5498 lineno: int | None = None,
5499 col_offset: int | None = None,
5500 parent: NodeNG | None = None,
5501 *,
5502 end_lineno: int | None = None,
5503 end_col_offset: int | None = None,
5504 ) -> None:
5505 self.patterns: list[Pattern]
5506 super().__init__(
5507 lineno=lineno,
5508 col_offset=col_offset,
5509 end_lineno=end_lineno,
5510 end_col_offset=end_col_offset,
5511 parent=parent,
5512 )
5513
5514 def postinit(self, *, patterns: list[Pattern]) -> None:
5515 self.patterns = patterns
5516
5517
5518class TemplateStr(NodeNG):
5519 """Class representing an :class:`ast.TemplateStr` node.
5520
5521 >>> import astroid
5522 >>> node = astroid.extract_node('t"{name} finished {place!s}"')
5523 >>> node
5524 <TemplateStr l.1 at 0x...>
5525 """
5526
5527 _astroid_fields = ("values",)
5528
5529 def __init__(
5530 self,
5531 lineno: int | None = None,
5532 col_offset: int | None = None,
5533 parent: NodeNG | None = None,
5534 *,
5535 end_lineno: int | None = None,
5536 end_col_offset: int | None = None,
5537 ) -> None:
5538 self.values: list[NodeNG]
5539 super().__init__(
5540 lineno=lineno,
5541 col_offset=col_offset,
5542 end_lineno=end_lineno,
5543 end_col_offset=end_col_offset,
5544 parent=parent,
5545 )
5546
5547 def postinit(self, *, values: list[NodeNG]) -> None:
5548 self.values = values
5549
5550 def get_children(self) -> Iterator[NodeNG]:
5551 yield from self.values
5552
5553
5554class Interpolation(NodeNG):
5555 """Class representing an :class:`ast.Interpolation` node.
5556
5557 >>> import astroid
5558 >>> node = astroid.extract_node('t"{name} finished {place!s}"')
5559 >>> node
5560 <TemplateStr l.1 at 0x...>
5561 >>> node.values[0]
5562 <Interpolation l.1 at 0x...>
5563 >>> node.values[2]
5564 <Interpolation l.1 at 0x...>
5565 """
5566
5567 _astroid_fields = ("value", "format_spec")
5568 _other_fields = ("str", "conversion")
5569
5570 def __init__(
5571 self,
5572 lineno: int | None = None,
5573 col_offset: int | None = None,
5574 parent: NodeNG | None = None,
5575 *,
5576 end_lineno: int | None = None,
5577 end_col_offset: int | None = None,
5578 ) -> None:
5579 self.value: NodeNG
5580 """Any expression node."""
5581
5582 self.str: str
5583 """Text of the interpolation expression."""
5584
5585 self.conversion: int
5586 """The type of formatting to be applied to the value.
5587
5588 .. seealso::
5589 :class:`ast.Interpolation`
5590 """
5591
5592 self.format_spec: JoinedStr | None = None
5593 """The formatting to be applied to the value.
5594
5595 .. seealso::
5596 :class:`ast.Interpolation`
5597 """
5598
5599 super().__init__(
5600 lineno=lineno,
5601 col_offset=col_offset,
5602 end_lineno=end_lineno,
5603 end_col_offset=end_col_offset,
5604 parent=parent,
5605 )
5606
5607 def postinit(
5608 self,
5609 *,
5610 value: NodeNG,
5611 str: str, # pylint: disable=redefined-builtin
5612 conversion: int = -1,
5613 format_spec: JoinedStr | None = None,
5614 ) -> None:
5615 self.value = value
5616 self.str = str
5617 self.conversion = conversion
5618 self.format_spec = format_spec
5619
5620 def get_children(self) -> Iterator[NodeNG]:
5621 yield self.value
5622 if self.format_spec:
5623 yield self.format_spec
5624
5625
5626# constants ##############################################################
5627
5628# The _proxied attribute of all container types (List, Tuple, etc.)
5629# are set during bootstrapping by _astroid_bootstrapping().
5630CONST_CLS: dict[type, type[NodeNG]] = {
5631 list: List,
5632 tuple: Tuple,
5633 dict: Dict,
5634 set: Set,
5635 type(None): Const,
5636 type(NotImplemented): Const,
5637 type(...): Const,
5638 bool: Const,
5639 int: Const,
5640 float: Const,
5641 complex: Const,
5642 str: Const,
5643 bytes: Const,
5644}
5645
5646
5647def _create_basic_elements(
5648 value: Iterable[Any], node: List | Set | Tuple, building: set[int]
5649) -> list[NodeNG]:
5650 """Create a list of nodes to function as the elements of a new node."""
5651 elements: list[NodeNG] = []
5652 for element in value:
5653 # NOTE: avoid accessing any attributes of element in the loop.
5654 element_node = _const_factory(element, building)
5655 element_node.parent = node
5656 elements.append(element_node)
5657 return elements
5658
5659
5660def _create_dict_items(
5661 values: Mapping[Any, Any], node: Dict, building: set[int]
5662) -> list[tuple[SuccessfulInferenceResult, SuccessfulInferenceResult]]:
5663 """Create a list of node pairs to function as the items of a new dict node."""
5664 elements: list[tuple[SuccessfulInferenceResult, SuccessfulInferenceResult]] = []
5665 for key, value in values.items():
5666 # NOTE: avoid accessing any attributes of both key and value in the loop.
5667 key_node = _const_factory(key, building)
5668 key_node.parent = node
5669 value_node = _const_factory(value, building)
5670 value_node.parent = node
5671 elements.append((key_node, value_node))
5672 return elements
5673
5674
5675def const_factory(value: Any) -> ConstFactoryResult:
5676 """Return an astroid node for a python value."""
5677 return _const_factory(value, set())
5678
5679
5680def _const_factory(value: Any, building: set[int]) -> ConstFactoryResult:
5681 """Return an astroid node for value.
5682
5683 ``building`` holds the ids of the containers whose elements are being
5684 converted, i.e. the containers value is nested in.
5685 """
5686 # NOTE: avoid accessing any attributes of value until it is known that value
5687 # is of a const type, to avoid possibly triggering code for a live object.
5688 # Accesses include value.__class__ and isinstance(value, ...), but not type(value).
5689 # See: https://github.com/pylint-dev/astroid/issues/2686
5690 value_type = type(value)
5691 assert not issubclass(value_type, NodeNG)
5692
5693 # This only handles instances of the CONST types. Any
5694 # subclasses get inferred as EmptyNode.
5695 # TODO: See if we should revisit these with the normal builder.
5696 if value_type not in CONST_CLS:
5697 node = EmptyNode()
5698 node.object = value
5699 return node
5700
5701 instance: List | Set | Tuple | Dict
5702 initializer_cls = CONST_CLS[value_type]
5703 if initializer_cls is Const:
5704 return Const(value)
5705
5706 # A live container can hold itself, directly or through other containers
5707 # (``namespace = globals()``): converting it again would recurse forever,
5708 # so the back reference becomes an EmptyNode, like a non-const object.
5709 value_id = id(value)
5710 if value_id in building:
5711 node = EmptyNode()
5712 node.object = value
5713 return node
5714 building.add(value_id)
5715 if issubclass(initializer_cls, (List, Set, Tuple)):
5716 instance = initializer_cls(
5717 lineno=None,
5718 col_offset=None,
5719 parent=SYNTHETIC_ROOT,
5720 end_lineno=None,
5721 end_col_offset=None,
5722 )
5723 instance.postinit(_create_basic_elements(value, instance, building))
5724 else:
5725 assert issubclass(initializer_cls, Dict)
5726 instance = initializer_cls(
5727 lineno=None,
5728 col_offset=None,
5729 parent=SYNTHETIC_ROOT,
5730 end_lineno=None,
5731 end_col_offset=None,
5732 )
5733 instance.postinit(_create_dict_items(value, instance, building))
5734 building.remove(value_id)
5735 return instance