Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/protocols.py: 36%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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
5"""This module contains a set of functions to handle python protocols for nodes
6where it makes sense.
7"""
9from __future__ import annotations
11import collections
12import itertools
13import operator as operator_mod
14from collections.abc import Callable, Generator, Iterator, Sequence
15from typing import TYPE_CHECKING, Any, TypeVar
17from astroid import bases, decorators, nodes, util
18from astroid.builder import extract_node
19from astroid.const import Context
20from astroid.context import InferenceContext, copy_context
21from astroid.exceptions import (
22 AstroidIndexError,
23 AstroidTypeError,
24 AttributeInferenceError,
25 InferenceError,
26 NoDefault,
27)
28from astroid.nodes import node_classes
29from astroid.typing import (
30 ConstFactoryResult,
31 InferenceResult,
32 SuccessfulInferenceResult,
33)
35if TYPE_CHECKING:
36 _TupleListNodeT = TypeVar("_TupleListNodeT", nodes.Tuple, nodes.List)
38_CONTEXTLIB_MGR = "contextlib.contextmanager"
40_UNARY_OPERATORS: dict[str, Callable[[Any], Any]] = {
41 "+": operator_mod.pos,
42 "-": operator_mod.neg,
43 "~": operator_mod.invert,
44 "not": operator_mod.not_,
45}
48def _infer_unary_op(obj: Any, op: str) -> ConstFactoryResult:
49 """Perform unary operation on `obj`, unless it is `NotImplemented`.
51 Can raise TypeError if operation is unsupported.
52 """
53 if obj is NotImplemented:
54 value = obj
55 else:
56 func = _UNARY_OPERATORS[op]
57 value = func(obj)
58 return nodes.const_factory(value)
61def tuple_infer_unary_op(self, op):
62 return _infer_unary_op(tuple(self.elts), op)
65def list_infer_unary_op(self, op):
66 return _infer_unary_op(self.elts, op)
69def set_infer_unary_op(self, op):
70 return _infer_unary_op(set(self.elts), op)
73def const_infer_unary_op(self, op):
74 return _infer_unary_op(self.value, op)
77def dict_infer_unary_op(self, op):
78 return _infer_unary_op(dict(self.items), op)
81# Binary operations
83BIN_OP_IMPL = {
84 "+": lambda a, b: a + b,
85 "-": lambda a, b: a - b,
86 "/": lambda a, b: a / b,
87 "//": lambda a, b: a // b,
88 "*": lambda a, b: a * b,
89 "**": lambda a, b: a**b,
90 "%": lambda a, b: a % b,
91 "&": lambda a, b: a & b,
92 "|": lambda a, b: a | b,
93 "^": lambda a, b: a ^ b,
94 "<<": lambda a, b: a << b,
95 ">>": lambda a, b: a >> b,
96 "@": operator_mod.matmul,
97}
98for _KEY, _IMPL in list(BIN_OP_IMPL.items()):
99 BIN_OP_IMPL[_KEY + "="] = _IMPL
102def _old_style_format_too_large(template: str | bytes, values: object) -> bool:
103 """Whether ``template % values`` would exceed the 1e8 size cap.
105 Walks the conversion specifiers the way CPython parses them, resolving
106 ``*`` width/precision fields from the positional arguments.
107 """
108 if isinstance(template, bytes):
109 template = template.decode("latin-1")
110 if isinstance(values, dict):
111 args: tuple[object, ...] = ()
112 elif isinstance(values, tuple):
113 args = values
114 else:
115 args = (values,)
116 index = 0 # next positional argument
117 i, end = 0, len(template)
118 while i < end:
119 if template[i] != "%":
120 i += 1
121 continue
122 i += 1
123 if i < end and template[i] == "(":
124 # Skip the mapping key, counting nested parentheses like CPython.
125 depth, i = 1, i + 1
126 while i < end and depth:
127 if template[i] == "(":
128 depth += 1
129 elif template[i] == ")":
130 depth -= 1
131 i += 1
132 while i < end and template[i] in "#0- +":
133 i += 1
134 for dot in ("", "."): # width, then precision
135 if dot:
136 if i >= end or template[i] != ".":
137 break
138 i += 1
139 if i < end and template[i] == "*":
140 i += 1
141 if index < len(args):
142 star = args[index]
143 index += 1
144 # A negative width means left-justify with that magnitude.
145 if isinstance(star, int) and abs(star) > 1e8:
146 return True
147 else:
148 start = i
149 while i < end and "0" <= template[i] <= "9":
150 i += 1
151 digits = template[start:i]
152 # len > 9 already exceeds the cap and avoids int() choking.
153 if digits and (len(digits) > 9 or int(digits) > 1e8):
154 return True
155 while i < end and template[i] in "hlL":
156 i += 1
157 if i < end:
158 if template[i] != "%":
159 index += 1 # the conversion itself consumes an argument
160 i += 1
161 return False
164@decorators.yes_if_nothing_inferred
165def const_infer_binary_op(
166 self: nodes.Const,
167 opnode: nodes.AugAssign | nodes.BinOp,
168 operator: str,
169 other: InferenceResult,
170 context: InferenceContext,
171 _: SuccessfulInferenceResult,
172) -> Generator[ConstFactoryResult | util.UninferableBase]:
173 not_implemented = nodes.Const(NotImplemented)
174 if isinstance(other, nodes.Const):
175 if (
176 operator == "**"
177 and isinstance(self.value, (int, float))
178 and isinstance(other.value, (int, float))
179 and (self.value > 1e5 or other.value > 1e5)
180 ):
181 yield not_implemented
182 return
183 # Repeating a str/bytes by a large count ("x" * n or n * "x") would
184 # eagerly build the whole object, the same way list/tuple repetition
185 # is bounded in _multiply_seq_by_int. Don't materialize it.
186 if operator == "*":
187 sequence, count = self.value, other.value
188 if isinstance(sequence, int) and isinstance(count, (str, bytes)):
189 sequence, count = count, sequence
190 if (
191 isinstance(sequence, (str, bytes))
192 and isinstance(count, int)
193 and len(sequence) * count > 1e8
194 ):
195 yield util.Uninferable
196 return
197 # Left-shifting by a large amount builds an enormous int, the integer
198 # analog of the ** guard above.
199 if (
200 operator == "<<"
201 and isinstance(self.value, int)
202 and isinstance(other.value, int)
203 and other.value > 1e8
204 ):
205 yield util.Uninferable
206 return
207 # Don't materialize an overly large str/bytes concatenation.
208 if (
209 operator == "+"
210 and isinstance(self.value, (str, bytes))
211 and isinstance(other.value, type(self.value))
212 and len(self.value) + len(other.value) > 1e8
213 ):
214 yield util.Uninferable
215 return
216 # An oversized width or precision ("%1000000000d" % 1) would
217 # materialize the whole interpolation, like the repetition above.
218 if (
219 operator in {"%", "%="}
220 and isinstance(self.value, (str, bytes))
221 and _old_style_format_too_large(self.value, other.value)
222 ):
223 yield util.Uninferable
224 return
225 try:
226 impl = BIN_OP_IMPL[operator]
227 try:
228 yield nodes.const_factory(impl(self.value, other.value))
229 except TypeError:
230 # ArithmeticError is not enough: float >> float is a TypeError
231 yield not_implemented
232 except Exception: # pylint: disable=broad-except
233 yield util.Uninferable
234 except TypeError:
235 yield not_implemented
236 elif isinstance(self.value, str) and operator == "%":
237 # TODO(cpopa): implement string interpolation later on.
238 yield util.Uninferable
239 else:
240 yield not_implemented
243def _multiply_seq_by_int(
244 self: _TupleListNodeT,
245 opnode: nodes.AugAssign | nodes.BinOp,
246 value: int,
247 context: InferenceContext,
248) -> _TupleListNodeT:
249 node = self.__class__(parent=opnode)
250 if not (value > 0 and self.elts):
251 node.elts = []
252 return node
253 if len(self.elts) * value > 1e8:
254 node.elts = [util.Uninferable]
255 return node
256 filtered_elts = (
257 util.safe_infer(elt, context) or util.Uninferable
258 for elt in self.elts
259 if not isinstance(elt, util.UninferableBase)
260 )
261 node.elts = list(filtered_elts) * value
262 return node
265def _infer_sequence_elements(
266 elts: Sequence[InferenceResult], context: InferenceContext
267) -> Iterator[SuccessfulInferenceResult]:
268 for elt in elts:
269 inferred = util.safe_infer(elt, context)
270 if inferred is None or isinstance(inferred, util.UninferableBase):
271 yield node_classes.UNATTACHED_UNKNOWN
272 else:
273 yield inferred
276@decorators.yes_if_nothing_inferred
277def tl_infer_binary_op(
278 self: _TupleListNodeT,
279 opnode: nodes.AugAssign | nodes.BinOp,
280 operator: str,
281 other: InferenceResult,
282 context: InferenceContext,
283 method: SuccessfulInferenceResult,
284) -> Generator[_TupleListNodeT | nodes.Const | util.UninferableBase]:
285 """Infer a binary operation on a tuple or list.
287 The instance on which the binary operation is performed is a tuple
288 or list. This refers to the left-hand side of the operation, so:
289 'tuple() + 1' or '[] + A()'
290 """
291 from astroid import helpers # pylint: disable=import-outside-toplevel
293 # For tuples and list the boundnode is no longer the tuple or list instance
294 context.boundnode = None
295 not_implemented = nodes.Const(NotImplemented)
296 # "+=" only reaches here for lists: tuples have no __iadd__, so the
297 # augmented flow falls back to "+" for them. list.__iadd__ accepts a
298 # tuple, unlike list.__add__.
299 if (isinstance(other, self.__class__) and operator == "+") or (
300 isinstance(other, (nodes.List, nodes.Tuple)) and operator == "+="
301 ):
302 # Don't build (and infer every element of) an overly large sequence.
303 if len(self.elts) + len(other.elts) > 1e8:
304 yield util.Uninferable
305 return
306 node = self.__class__(parent=opnode)
307 node.elts = list(
308 itertools.chain(
309 _infer_sequence_elements(self.elts, context),
310 _infer_sequence_elements(other.elts, context),
311 )
312 )
313 yield node
314 elif isinstance(other, nodes.Const) and operator == "*":
315 if not isinstance(other.value, int):
316 yield not_implemented
317 return
318 yield _multiply_seq_by_int(self, opnode, other.value, context)
319 elif isinstance(other, bases.Instance) and operator == "*":
320 # Verify if the instance supports __index__.
321 as_index = helpers.class_instance_as_index(other)
322 if not as_index:
323 yield util.Uninferable
324 elif not isinstance(as_index.value, int): # pragma: no cover
325 # already checked by class_instance_as_index() but faster than casting
326 raise AssertionError("Please open a bug report.")
327 else:
328 yield _multiply_seq_by_int(self, opnode, as_index.value, context)
329 else:
330 yield not_implemented
333@decorators.yes_if_nothing_inferred
334def instance_class_infer_binary_op(
335 self: nodes.ClassDef,
336 opnode: nodes.AugAssign | nodes.BinOp,
337 operator: str,
338 other: InferenceResult,
339 context: InferenceContext,
340 method: SuccessfulInferenceResult,
341) -> Generator[InferenceResult]:
342 return method.infer_call_result(self, context)
345# assignment ##################################################################
346# pylint: disable-next=pointless-string-statement
347"""The assigned_stmts method is responsible to return the assigned statement
348(e.g. not inferred) according to the assignment type.
350The `assign_path` argument is used to record the lhs path of the original node.
351For instance if we want assigned statements for 'c' in 'a, (b,c)', assign_path
352will be [1, 1] once arrived to the Assign node.
354The `context` argument is the current inference context which should be given
355to any intermediary inference necessary.
356"""
359def _resolve_looppart(parts, assign_path, context):
360 """Recursive function to resolve multiple assignments on loops."""
361 assign_path = assign_path[:]
362 index = assign_path.pop(0)
363 for part in parts:
364 if isinstance(part, util.UninferableBase):
365 continue
366 if not hasattr(part, "itered"):
367 continue
368 try:
369 itered = part.itered()
370 except TypeError:
371 continue
372 try:
373 if isinstance(itered[index], (nodes.Const, nodes.Name)):
374 itered = [part]
375 except IndexError:
376 pass
377 for stmt in itered:
378 index_node = nodes.Const(index)
379 try:
380 assigned = stmt.getitem(index_node, context)
381 except (AttributeError, AstroidTypeError, AstroidIndexError):
382 continue
383 if not assign_path:
384 # we achieved to resolved the assignment path,
385 # don't infer the last part
386 yield assigned
387 elif isinstance(assigned, util.UninferableBase):
388 break
389 else:
390 # we are not yet on the last part of the path
391 # search on each possibly inferred value
392 try:
393 yield from _resolve_looppart(
394 assigned.infer(context), assign_path, context
395 )
396 except InferenceError:
397 break
400@decorators.raise_if_nothing_inferred
401def for_assigned_stmts(
402 self: nodes.For | nodes.Comprehension,
403 node: node_classes.AssignedStmtsPossibleNode = None,
404 context: InferenceContext | None = None,
405 assign_path: list[int] | None = None,
406) -> Any:
407 if isinstance(self, nodes.AsyncFor) or getattr(self, "is_async", False):
408 # Skip inferring of async code for now
409 return {
410 "node": self,
411 "unknown": node,
412 "assign_path": assign_path,
413 "context": context,
414 }
415 if assign_path is None:
416 for lst in self.iter.infer(context):
417 if isinstance(lst, (nodes.Tuple, nodes.List)):
418 yield from lst.elts
419 else:
420 yield from _resolve_looppart(self.iter.infer(context), assign_path, context)
421 return {
422 "node": self,
423 "unknown": node,
424 "assign_path": assign_path,
425 "context": context,
426 }
429def sequence_assigned_stmts(
430 self: nodes.Tuple | nodes.List,
431 node: node_classes.AssignedStmtsPossibleNode = None,
432 context: InferenceContext | None = None,
433 assign_path: list[int] | None = None,
434) -> Any:
435 if assign_path is None:
436 assign_path = []
437 try:
438 index = self.elts.index(node) # type: ignore[arg-type]
439 except ValueError as exc:
440 raise InferenceError(
441 "Tried to retrieve a node {node!r} which does not exist",
442 node=self,
443 assign_path=assign_path,
444 context=context,
445 ) from exc
447 assign_path.insert(0, index)
448 return self.parent.assigned_stmts(
449 node=self, context=context, assign_path=assign_path
450 )
453def assend_assigned_stmts(
454 self: nodes.AssignName | nodes.AssignAttr,
455 node: node_classes.AssignedStmtsPossibleNode = None,
456 context: InferenceContext | None = None,
457 assign_path: list[int] | None = None,
458) -> Any:
459 return self.parent.assigned_stmts(node=self, context=context)
462def _arguments_infer_argname(
463 self, name: str | None, context: InferenceContext | None
464) -> Generator[InferenceResult]:
465 # arguments information may be missing, in which case we can't do anything
466 # more
467 from astroid import arguments # pylint: disable=import-outside-toplevel
469 if not self.arguments:
470 yield util.Uninferable
471 return
473 args = [arg for arg in self.arguments if arg.name not in [self.vararg, self.kwarg]]
474 functype = self.parent.type
475 # first argument of instance/class method
476 if (
477 args
478 and getattr(self.arguments[0], "name", None) == name
479 and functype != "staticmethod"
480 ):
481 cls = self.parent.parent.scope()
482 is_metaclass = isinstance(cls, nodes.ClassDef) and cls.type == "metaclass"
483 # If this is a metaclass, then the first argument will always
484 # be the class, not an instance.
485 if (
486 context
487 and context.boundnode
488 and isinstance(context.boundnode, bases.Instance)
489 ):
490 bound_cls = context.boundnode._proxied
491 if not isinstance(cls, nodes.ClassDef) or bound_cls.is_subtype_of(
492 cls.qname()
493 ):
494 cls = bound_cls
495 if is_metaclass or functype == "classmethod":
496 yield cls
497 return
498 if functype == "method":
499 yield cls.instantiate_class()
500 return
502 if context and context.callcontext:
503 callee = context.callcontext.callee
504 while hasattr(callee, "_proxied"):
505 callee = callee._proxied
506 if getattr(callee, "name", None) == self.parent.name:
507 call_site = arguments.CallSite(context.callcontext, context.extra_context)
508 yield from call_site.infer_argument(self.parent, name, context)
509 return
511 if name == self.vararg:
512 vararg = nodes.const_factory(())
513 vararg.parent = self
514 if not args and self.parent.name == "__init__":
515 cls = self.parent.parent.scope()
516 vararg.elts = [cls.instantiate_class()]
517 yield vararg
518 return
519 if name == self.kwarg:
520 kwarg = nodes.const_factory({})
521 kwarg.parent = self
522 yield kwarg
523 return
524 # if there is a default value, yield it. And then yield Uninferable to reflect
525 # we can't guess given argument value
526 try:
527 context = copy_context(context)
528 yield from self.default_value(name).infer(context)
529 yield util.Uninferable
530 except NoDefault:
531 yield util.Uninferable
534def arguments_assigned_stmts(
535 self: nodes.Arguments,
536 node: node_classes.AssignedStmtsPossibleNode = None,
537 context: InferenceContext | None = None,
538 assign_path: list[int] | None = None,
539) -> Any:
540 from astroid import arguments # pylint: disable=import-outside-toplevel
542 try:
543 node_name = node.name # type: ignore[union-attr]
544 except AttributeError:
545 # Added to handle edge cases where node.name is not defined.
546 # https://github.com/pylint-dev/astroid/pull/1644#discussion_r901545816
547 node_name = None # pragma: no cover
549 if context and context.callcontext:
550 callee = context.callcontext.callee
551 while hasattr(callee, "_proxied"):
552 callee = callee._proxied
553 else:
554 return _arguments_infer_argname(self, node_name, context)
555 if node and getattr(callee, "name", None) == node.frame().name:
556 # reset call context/name
557 callcontext = context.callcontext
558 context = copy_context(context)
559 context.callcontext = None
560 args = arguments.CallSite(callcontext, context=context)
561 return args.infer_argument(self.parent, node_name, context)
562 return _arguments_infer_argname(self, node_name, context)
565@decorators.raise_if_nothing_inferred
566def assign_assigned_stmts(
567 self: nodes.AugAssign | nodes.Assign | nodes.AnnAssign | nodes.TypeAlias,
568 node: node_classes.AssignedStmtsPossibleNode = None,
569 context: InferenceContext | None = None,
570 assign_path: list[int] | None = None,
571) -> Any:
572 if (
573 not assign_path
574 and isinstance(self, nodes.Assign)
575 and self.type_annotation is not None
576 and _is_stub_ellipsis_assign(self)
577 ):
578 yield from infer_instance_from_annotation(self.type_annotation, ctx=context)
579 return None
580 if not assign_path:
581 yield self.value
582 return None
583 yield from _resolve_assignment_parts(
584 self.value.infer(context), assign_path, context
585 )
587 return {
588 "node": self,
589 "unknown": node,
590 "assign_path": assign_path,
591 "context": context,
592 }
595def assign_annassigned_stmts(
596 self: nodes.AnnAssign,
597 node: node_classes.AssignedStmtsPossibleNode = None,
598 context: InferenceContext | None = None,
599 assign_path: list[int] | None = None,
600) -> Any:
601 if (
602 not assign_path
603 and self.annotation is not None
604 and (
605 _is_stub_ellipsis_assign(self)
606 or (self.value is None and _is_stub_node(self))
607 )
608 ):
609 yield from infer_instance_from_annotation(self.annotation, ctx=context)
610 return
611 for inferred in assign_assigned_stmts(self, node, context, assign_path):
612 if inferred is None:
613 yield util.Uninferable
614 else:
615 yield inferred
618_TYPING_WRAPPERS = frozenset(
619 (
620 "typing.ClassVar",
621 "typing.Final",
622 "typing.Annotated",
623 "typing_extensions.ClassVar",
624 "typing_extensions.Final",
625 "typing_extensions.Annotated",
626 )
627)
628_ANNOTATED_WRAPPERS = frozenset(("typing.Annotated", "typing_extensions.Annotated"))
630_INFERABLE_TYPING_TYPES = frozenset(("Dict", "FrozenSet", "List", "Set", "Tuple"))
633def _is_stub_ellipsis_assign(node: nodes.Assign | nodes.AnnAssign) -> bool:
634 """Check if an assignment uses an ellipsis placeholder in a stub."""
635 return (
636 _is_stub_node(node)
637 and isinstance(node.value, node_classes.Const)
638 and node.value.value is ...
639 )
642def _is_stub_node(node: nodes.NodeNG) -> bool:
643 """Check if a node belongs to a stub module."""
644 root = node.root()
645 return isinstance(root, nodes.Module) and root.is_stub
648def _unwrap_typing_wrapper(node: nodes.NodeNG) -> nodes.NodeNG:
649 """Strip ClassVar/Final/Annotated wrappers from an annotation node."""
650 while isinstance(node, nodes.Subscript):
651 try:
652 wrapper = next(node.value.infer())
653 except (InferenceError, StopIteration):
654 break
655 wrapper_qname = wrapper.qname()
656 if wrapper_qname not in _TYPING_WRAPPERS:
657 break
658 if wrapper_qname in _ANNOTATED_WRAPPERS and isinstance(node.slice, nodes.Tuple):
659 node = node.slice.elts[0]
660 else:
661 node = node.slice
662 return node
665def _resolve_forward_ref(node: nodes.Const) -> nodes.ClassDef | None:
666 """Resolve a string annotation (forward reference) to its ClassDef."""
667 _, stmts = node.frame().lookup(node.value)
668 if stmts and isinstance(stmts[0], nodes.ClassDef):
669 return stmts[0]
670 return None
673def infer_instance_from_annotation(
674 node: nodes.NodeNG, ctx: InferenceContext | None = None
675) -> Iterator[InferenceResult]:
676 """Infer an instance corresponding to the type annotation represented by node."""
677 node = _unwrap_typing_wrapper(node)
678 klass = None
679 if isinstance(node, nodes.Const) and isinstance(node.value, str):
680 klass = _resolve_forward_ref(node)
681 if klass is None:
682 yield util.Uninferable
683 return
684 else:
685 try:
686 klass = next(node.infer(context=ctx))
687 except (InferenceError, StopIteration):
688 yield util.Uninferable
689 return
690 if isinstance(klass, nodes.Const) and klass.value is None:
691 yield klass
692 return
693 if not isinstance(klass, nodes.ClassDef):
694 yield util.Uninferable
695 return
696 klass_root = klass.root()
697 if klass_root.name in {"typing", "_collections_abc"} or (
698 # Distinguish synthetic typing modules from unnamed user modules
699 not klass_root.name
700 and klass_root is not node.root()
701 ):
702 if klass.name in _INFERABLE_TYPING_TYPES:
703 yield klass.instantiate_class()
704 else:
705 yield util.Uninferable
706 else:
707 yield klass.instantiate_class()
710def _resolve_assignment_parts(parts, assign_path, context):
711 """Recursive function to resolve multiple assignments."""
712 assign_path = assign_path[:]
713 index = assign_path.pop(0)
714 for part in parts:
715 assigned = None
716 if isinstance(part, nodes.Dict):
717 # A dictionary in an iterating context
718 try:
719 assigned, _ = part.items[index]
720 except IndexError:
721 return
723 elif hasattr(part, "getitem"):
724 index_node = nodes.Const(index)
725 try:
726 assigned = part.getitem(index_node, context)
727 except (AstroidTypeError, AstroidIndexError):
728 return
730 if not assigned:
731 return
733 if not assign_path:
734 # we achieved to resolved the assignment path, don't infer the
735 # last part
736 yield assigned
737 elif isinstance(assigned, util.UninferableBase):
738 return
739 else:
740 # we are not yet on the last part of the path search on each
741 # possibly inferred value
742 try:
743 yield from _resolve_assignment_parts(
744 assigned.infer(context), assign_path, context
745 )
746 except InferenceError:
747 return
750@decorators.raise_if_nothing_inferred
751def excepthandler_assigned_stmts(
752 self: nodes.ExceptHandler,
753 node: node_classes.AssignedStmtsPossibleNode = None,
754 context: InferenceContext | None = None,
755 assign_path: list[int] | None = None,
756) -> Any:
757 from astroid import objects # pylint: disable=import-outside-toplevel
759 def _generate_assigned():
760 for assigned in node_classes.unpack_infer(self.type):
761 if isinstance(assigned, nodes.ClassDef):
762 assigned = objects.ExceptionInstance(assigned)
764 yield assigned
766 if isinstance(self.parent, node_classes.TryStar):
767 # except * handler has assigned ExceptionGroup with caught
768 # exceptions under exceptions attribute
769 # pylint: disable-next=stop-iteration-return
770 eg = next(node_classes.unpack_infer(extract_node("""
771from builtins import ExceptionGroup
772ExceptionGroup
773""")))
774 assigned = objects.ExceptionInstance(eg)
775 assigned.instance_attrs["exceptions"] = [
776 nodes.Tuple.from_elements(_generate_assigned())
777 ]
778 yield assigned
779 else:
780 yield from _generate_assigned()
781 return {
782 "node": self,
783 "unknown": node,
784 "assign_path": assign_path,
785 "context": context,
786 }
789def _infer_context_manager(self, mgr, context):
790 try:
791 inferred = next(mgr.infer(context=context))
792 except StopIteration as e:
793 raise InferenceError(node=mgr) from e
794 if isinstance(inferred, bases.Generator):
795 # Check if it is decorated with contextlib.contextmanager.
796 func = inferred.parent
797 if not func.decorators:
798 raise InferenceError(
799 "No decorators found on inferred generator %s", node=func
800 )
802 for decorator_node in func.decorators.nodes:
803 decorator = next(decorator_node.infer(context=context), None)
804 if isinstance(decorator, nodes.FunctionDef):
805 if decorator.qname() == _CONTEXTLIB_MGR:
806 break
807 else:
808 # It doesn't interest us.
809 raise InferenceError(node=func)
810 try:
811 yield next(inferred.infer_yield_types())
812 except StopIteration as e:
813 raise InferenceError(node=func) from e
815 elif isinstance(inferred, bases.Instance):
816 try:
817 enter = next(inferred.igetattr("__enter__", context=context))
818 except (InferenceError, AttributeInferenceError, StopIteration) as exc:
819 raise InferenceError(node=inferred) from exc
820 if not isinstance(enter, bases.BoundMethod):
821 raise InferenceError(node=enter)
822 yield from enter.infer_call_result(self, context)
823 else:
824 raise InferenceError(node=mgr)
827@decorators.raise_if_nothing_inferred
828def with_assigned_stmts(
829 self: nodes.With,
830 node: node_classes.AssignedStmtsPossibleNode = None,
831 context: InferenceContext | None = None,
832 assign_path: list[int] | None = None,
833) -> Any:
834 """Infer names and other nodes from a *with* statement.
836 This enables only inference for name binding in a *with* statement.
837 For instance, in the following code, inferring `func` will return
838 the `ContextManager` class, not whatever ``__enter__`` returns.
839 We are doing this intentionally, because we consider that the context
840 manager result is whatever __enter__ returns and what it is binded
841 using the ``as`` keyword.
843 class ContextManager(object):
844 def __enter__(self):
845 return 42
846 with ContextManager() as f:
847 pass
849 # ContextManager().infer() will return ContextManager
850 # f.infer() will return 42.
852 Arguments:
853 self: nodes.With
854 node: The target of the assignment, `as (a, b)` in `with foo as (a, b)`.
855 context: Inference context used for caching already inferred objects
856 assign_path:
857 A list of indices, where each index specifies what item to fetch from
858 the inference results.
859 """
860 try:
861 mgr = next(mgr for (mgr, vars) in self.items if vars == node)
862 except StopIteration:
863 return None
864 if assign_path is None:
865 yield from _infer_context_manager(self, mgr, context)
866 else:
867 for result in _infer_context_manager(self, mgr, context):
868 # Walk the assign_path and get the item at the final index.
869 obj = result
870 for index in assign_path:
871 if not hasattr(obj, "elts"):
872 raise InferenceError(
873 "Wrong type ({targets!r}) for {node!r} assignment",
874 node=self,
875 targets=node,
876 assign_path=assign_path,
877 context=context,
878 )
879 try:
880 obj = obj.elts[index]
881 except IndexError as exc:
882 raise InferenceError(
883 "Tried to infer a nonexistent target with index {index} "
884 "in {node!r}.",
885 node=self,
886 targets=node,
887 assign_path=assign_path,
888 context=context,
889 ) from exc
890 except TypeError as exc:
891 raise InferenceError(
892 "Tried to unpack a non-iterable value in {node!r}.",
893 node=self,
894 targets=node,
895 assign_path=assign_path,
896 context=context,
897 ) from exc
898 yield obj
899 return {
900 "node": self,
901 "unknown": node,
902 "assign_path": assign_path,
903 "context": context,
904 }
907@decorators.raise_if_nothing_inferred
908def named_expr_assigned_stmts(
909 self: nodes.NamedExpr,
910 node: node_classes.AssignedStmtsPossibleNode,
911 context: InferenceContext | None = None,
912 assign_path: list[int] | None = None,
913) -> Any:
914 """Infer names and other nodes from an assignment expression."""
915 if self.target == node:
916 yield from self.value.infer(context=context)
917 else:
918 raise InferenceError(
919 "Cannot infer NamedExpr node {node!r}",
920 node=self,
921 assign_path=assign_path,
922 context=context,
923 )
926@decorators.yes_if_nothing_inferred
927def starred_assigned_stmts( # noqa: C901
928 self: nodes.Starred,
929 node: node_classes.AssignedStmtsPossibleNode = None,
930 context: InferenceContext | None = None,
931 assign_path: list[int] | None = None,
932) -> Any:
933 """
934 Arguments:
935 self: nodes.Starred
936 node: a node related to the current underlying Node.
937 context: Inference context used for caching already inferred objects
938 assign_path:
939 A list of indices, where each index specifies what item to fetch from
940 the inference results.
941 """
943 # pylint: disable = too-many-locals, too-many-statements, too-many-branches
945 def _determine_starred_iteration_lookups(
946 starred: nodes.Starred, target: nodes.Tuple, lookups: list[tuple[int, int]]
947 ) -> None:
948 # Determine the lookups for the rhs of the iteration
949 itered = target.itered()
950 for index, element in enumerate(itered):
951 if isinstance(element, nodes.Starred) and element is starred:
952 lookups.append((index, len(itered)))
953 break
954 if isinstance(element, nodes.Tuple):
955 lookups.append((index, len(element.itered())))
956 _determine_starred_iteration_lookups(starred, element, lookups)
958 stmt = self.statement()
959 if not isinstance(stmt, (nodes.Assign, nodes.For)):
960 raise InferenceError(
961 "Statement {stmt!r} enclosing {node!r} must be an Assign or For node.",
962 node=self,
963 stmt=stmt,
964 unknown=node,
965 context=context,
966 )
968 if context is None:
969 context = InferenceContext()
971 if isinstance(stmt, nodes.Assign):
972 value = stmt.value
973 lhs = stmt.targets[0]
974 if not isinstance(lhs, nodes.BaseContainer):
975 yield util.Uninferable
976 return
978 if sum(1 for _ in lhs.nodes_of_class(nodes.Starred)) > 1:
979 raise InferenceError(
980 "Too many starred arguments in the assignment targets {lhs!r}.",
981 node=self,
982 targets=lhs,
983 unknown=node,
984 context=context,
985 )
987 try:
988 rhs = next(value.infer(context))
989 except (InferenceError, StopIteration):
990 yield util.Uninferable
991 return
992 if isinstance(rhs, util.UninferableBase) or not hasattr(rhs, "itered"):
993 yield util.Uninferable
994 return
996 try:
997 elts = collections.deque(rhs.itered()) # type: ignore[union-attr]
998 except TypeError:
999 yield util.Uninferable
1000 return
1002 # Unpack iteratively the values from the rhs of the assignment,
1003 # until the find the starred node. What will remain will
1004 # be the list of values which the Starred node will represent
1005 # This is done in two steps, from left to right to remove
1006 # anything before the starred node and from right to left
1007 # to remove anything after the starred node.
1009 for index, left_node in enumerate(lhs.elts):
1010 if not isinstance(left_node, nodes.Starred):
1011 if not elts:
1012 break
1013 elts.popleft()
1014 continue
1015 lhs_elts = collections.deque(reversed(lhs.elts[index:]))
1016 for right_node in lhs_elts:
1017 if not isinstance(right_node, nodes.Starred):
1018 if not elts:
1019 break
1020 elts.pop()
1021 continue
1023 # We're done unpacking.
1024 packed = nodes.List(
1025 ctx=Context.Store,
1026 parent=self,
1027 lineno=lhs.lineno,
1028 col_offset=lhs.col_offset,
1029 )
1030 packed.postinit(elts=list(elts))
1031 yield packed
1032 break
1034 if isinstance(stmt, nodes.For):
1035 try:
1036 inferred_iterable = next(stmt.iter.infer(context=context))
1037 except (InferenceError, StopIteration):
1038 yield util.Uninferable
1039 return
1040 if isinstance(inferred_iterable, util.UninferableBase) or not hasattr(
1041 inferred_iterable, "itered"
1042 ):
1043 yield util.Uninferable
1044 return
1045 try:
1046 itered = inferred_iterable.itered() # type: ignore[union-attr]
1047 except TypeError:
1048 yield util.Uninferable
1049 return
1051 target = stmt.target
1053 if not isinstance(target, nodes.Tuple):
1054 raise InferenceError(
1055 f"Could not make sense of this, the target must be a tuple, not {type(target)!r}",
1056 context=context,
1057 )
1059 lookups: list[tuple[int, int]] = []
1060 _determine_starred_iteration_lookups(self, target, lookups)
1061 if not lookups:
1062 raise InferenceError(
1063 "Could not make sense of this, needs at least a lookup", context=context
1064 )
1066 # Make the last lookup a slice, since that what we want for a Starred node
1067 last_element_index, last_element_length = lookups[-1]
1068 is_starred_last = last_element_index == (last_element_length - 1)
1070 # The elements after the starred one are counted back from the end of the
1071 # iterable, whose length is unrelated to the target's.
1072 lookup_slice = slice(
1073 last_element_index,
1074 (
1075 None
1076 if is_starred_last
1077 else -(last_element_length - last_element_index - 1)
1078 ),
1079 )
1080 last_lookup = lookup_slice
1082 for element in itered:
1083 # We probably want to infer the potential values *for each* element in an
1084 # iterable, but we can't infer a list of all values, when only a list of
1085 # step values are expected:
1086 #
1087 # for a, *b in [...]:
1088 # b
1089 #
1090 # *b* should now point to just the elements at that particular iteration step,
1091 # which astroid can't know about.
1093 found_element = None
1094 for index, lookup in enumerate(lookups):
1095 if not hasattr(element, "itered"):
1096 break
1097 if index + 1 is len(lookups):
1098 cur_lookup: slice | int = last_lookup
1099 else:
1100 # Grab just the index, not the whole length
1101 cur_lookup = lookup[0]
1102 try:
1103 itered_inner_element = element.itered()
1104 element = itered_inner_element[cur_lookup]
1105 except IndexError:
1106 break
1107 except TypeError:
1108 # Most likely the itered() call failed, cannot make sense of this
1109 yield util.Uninferable
1110 return
1111 else:
1112 found_element = element
1114 unpacked = nodes.List(
1115 ctx=Context.Store,
1116 parent=self,
1117 lineno=self.lineno,
1118 col_offset=self.col_offset,
1119 )
1120 unpacked.postinit(elts=found_element or [])
1121 yield unpacked
1122 return
1124 yield util.Uninferable
1127@decorators.yes_if_nothing_inferred
1128def match_mapping_assigned_stmts(
1129 self: nodes.MatchMapping,
1130 node: nodes.AssignName,
1131 context: InferenceContext | None = None,
1132 assign_path: None = None,
1133) -> Generator[nodes.NodeNG]:
1134 """Return empty generator (return -> raises StopIteration) so inferred value
1135 is Uninferable.
1136 """
1137 return
1138 yield
1141@decorators.yes_if_nothing_inferred
1142def match_star_assigned_stmts(
1143 self: nodes.MatchStar,
1144 node: nodes.AssignName,
1145 context: InferenceContext | None = None,
1146 assign_path: None = None,
1147) -> Generator[nodes.NodeNG]:
1148 """Return empty generator (return -> raises StopIteration) so inferred value
1149 is Uninferable.
1150 """
1151 return
1152 yield
1155@decorators.yes_if_nothing_inferred
1156def match_as_assigned_stmts(
1157 self: nodes.MatchAs,
1158 node: nodes.AssignName,
1159 context: InferenceContext | None = None,
1160 assign_path: None = None,
1161) -> Generator[nodes.NodeNG]:
1162 """Infer MatchAs as the Match subject if it's the only MatchCase pattern
1163 else raise StopIteration to yield Uninferable.
1164 """
1165 if (
1166 isinstance(self.parent, nodes.MatchCase)
1167 and isinstance(self.parent.parent, nodes.Match)
1168 and self.pattern is None
1169 ):
1170 yield self.parent.parent.subject
1173@decorators.yes_if_nothing_inferred
1174def generic_type_assigned_stmts(
1175 self: nodes.TypeVar | nodes.TypeVarTuple | nodes.ParamSpec,
1176 node: nodes.AssignName,
1177 context: InferenceContext | None = None,
1178 assign_path: None = None,
1179) -> Generator[nodes.NodeNG]:
1180 """Return the type parameter node itself so inference doesn't fail
1181 when evaluating __class_getitem__ and so that the node's type is
1182 preserved for downstream checks (e.g. TypeVarTuple starred handling).
1183 """
1184 yield self