Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/protocols.py: 35%

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

570 statements  

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"""This module contains a set of functions to handle python protocols for nodes 

6where it makes sense. 

7""" 

8 

9from __future__ import annotations 

10 

11import collections 

12import itertools 

13import operator as operator_mod 

14from collections.abc import Callable, Generator, Iterator, Sequence 

15from typing import TYPE_CHECKING, Any, TypeVar 

16 

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) 

34 

35if TYPE_CHECKING: 

36 _TupleListNodeT = TypeVar("_TupleListNodeT", nodes.Tuple, nodes.List) 

37 

38_CONTEXTLIB_MGR = "contextlib.contextmanager" 

39 

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} 

46 

47 

48def _infer_unary_op(obj: Any, op: str) -> ConstFactoryResult: 

49 """Perform unary operation on `obj`, unless it is `NotImplemented`. 

50 

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) 

59 

60 

61def tuple_infer_unary_op(self, op): 

62 return _infer_unary_op(tuple(self.elts), op) 

63 

64 

65def list_infer_unary_op(self, op): 

66 return _infer_unary_op(self.elts, op) 

67 

68 

69def set_infer_unary_op(self, op): 

70 return _infer_unary_op(set(self.elts), op) 

71 

72 

73def const_infer_unary_op(self, op): 

74 return _infer_unary_op(self.value, op) 

75 

76 

77def dict_infer_unary_op(self, op): 

78 return _infer_unary_op(dict(self.items), op) 

79 

80 

81# Binary operations 

82 

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 

100 

101 

102def _old_style_format_too_large(template: str | bytes, values: object) -> bool: 

103 """Whether ``template % values`` would exceed the 1e8 size cap. 

104 

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 

162 

163 

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 

241 

242 

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 

263 

264 

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 

274 

275 

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. 

286 

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 

292 

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 

331 

332 

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) 

343 

344 

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. 

349 

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. 

353 

354The `context` argument is the current inference context which should be given 

355to any intermediary inference necessary. 

356""" 

357 

358 

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 

398 

399 

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 } 

427 

428 

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 

446 

447 assign_path.insert(0, index) 

448 return self.parent.assigned_stmts( 

449 node=self, context=context, assign_path=assign_path 

450 ) 

451 

452 

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) 

460 

461 

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 

468 

469 if not self.arguments: 

470 yield util.Uninferable 

471 return 

472 

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 

501 

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 

510 

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 

532 

533 

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 

541 

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 

548 

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) 

563 

564 

565@decorators.raise_if_nothing_inferred 

566def assign_assigned_stmts( 

567 self: nodes.AugAssign | nodes.Assign | nodes.AnnAssign, 

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 ) 

586 

587 return { 

588 "node": self, 

589 "unknown": node, 

590 "assign_path": assign_path, 

591 "context": context, 

592 } 

593 

594 

595@decorators.raise_if_nothing_inferred 

596def type_alias_assigned_stmts( 

597 self: nodes.TypeAlias, 

598 node: node_classes.AssignedStmtsPossibleNode = None, 

599 context: InferenceContext | None = None, 

600 assign_path: list[int] | None = None, 

601) -> Any: 

602 """The name of a ``type`` statement is bound to a ``typing.TypeAliasType``, 

603 not to the aliased value. 

604 """ 

605 # pylint: disable-next=stop-iteration-return 

606 alias_type = next(node_classes.unpack_infer(extract_node(""" 

607from typing import TypeAliasType 

608TypeAliasType 

609"""))) 

610 yield alias_type.instantiate_class() 

611 return { 

612 "node": self, 

613 "unknown": node, 

614 "assign_path": assign_path, 

615 "context": context, 

616 } 

617 

618 

619def assign_annassigned_stmts( 

620 self: nodes.AnnAssign, 

621 node: node_classes.AssignedStmtsPossibleNode = None, 

622 context: InferenceContext | None = None, 

623 assign_path: list[int] | None = None, 

624) -> Any: 

625 if ( 

626 not assign_path 

627 and self.annotation is not None 

628 and ( 

629 _is_stub_ellipsis_assign(self) 

630 or (self.value is None and _is_stub_node(self)) 

631 ) 

632 ): 

633 yield from infer_instance_from_annotation(self.annotation, ctx=context) 

634 return 

635 for inferred in assign_assigned_stmts(self, node, context, assign_path): 

636 if inferred is None: 

637 yield util.Uninferable 

638 else: 

639 yield inferred 

640 

641 

642_TYPING_WRAPPERS = frozenset( 

643 ( 

644 "typing.ClassVar", 

645 "typing.Final", 

646 "typing.Annotated", 

647 "typing_extensions.ClassVar", 

648 "typing_extensions.Final", 

649 "typing_extensions.Annotated", 

650 ) 

651) 

652_ANNOTATED_WRAPPERS = frozenset(("typing.Annotated", "typing_extensions.Annotated")) 

653 

654_INFERABLE_TYPING_TYPES = frozenset(("Dict", "FrozenSet", "List", "Set", "Tuple")) 

655 

656 

657def _is_stub_ellipsis_assign(node: nodes.Assign | nodes.AnnAssign) -> bool: 

658 """Check if an assignment uses an ellipsis placeholder in a stub.""" 

659 return ( 

660 _is_stub_node(node) 

661 and isinstance(node.value, node_classes.Const) 

662 and node.value.value is ... 

663 ) 

664 

665 

666def _is_stub_node(node: nodes.NodeNG) -> bool: 

667 """Check if a node belongs to a stub module.""" 

668 root = node.root() 

669 return isinstance(root, nodes.Module) and root.is_stub 

670 

671 

672def _unwrap_typing_wrapper(node: nodes.NodeNG) -> nodes.NodeNG: 

673 """Strip ClassVar/Final/Annotated wrappers from an annotation node.""" 

674 while isinstance(node, nodes.Subscript): 

675 try: 

676 wrapper = next(node.value.infer()) 

677 except (InferenceError, StopIteration): 

678 break 

679 wrapper_qname = wrapper.qname() 

680 if wrapper_qname not in _TYPING_WRAPPERS: 

681 break 

682 if wrapper_qname in _ANNOTATED_WRAPPERS and isinstance(node.slice, nodes.Tuple): 

683 node = node.slice.elts[0] 

684 else: 

685 node = node.slice 

686 return node 

687 

688 

689def _resolve_forward_ref(node: nodes.Const) -> nodes.ClassDef | None: 

690 """Resolve a string annotation (forward reference) to its ClassDef.""" 

691 _, stmts = node.frame().lookup(node.value) 

692 if stmts and isinstance(stmts[0], nodes.ClassDef): 

693 return stmts[0] 

694 return None 

695 

696 

697def infer_instance_from_annotation( 

698 node: nodes.NodeNG, ctx: InferenceContext | None = None 

699) -> Iterator[InferenceResult]: 

700 """Infer an instance corresponding to the type annotation represented by node.""" 

701 node = _unwrap_typing_wrapper(node) 

702 klass = None 

703 if isinstance(node, nodes.Const) and isinstance(node.value, str): 

704 klass = _resolve_forward_ref(node) 

705 if klass is None: 

706 yield util.Uninferable 

707 return 

708 else: 

709 try: 

710 klass = next(node.infer(context=ctx)) 

711 except (InferenceError, StopIteration): 

712 yield util.Uninferable 

713 return 

714 if isinstance(klass, nodes.Const) and klass.value is None: 

715 yield klass 

716 return 

717 if not isinstance(klass, nodes.ClassDef): 

718 yield util.Uninferable 

719 return 

720 klass_root = klass.root() 

721 if klass_root.name in {"typing", "_collections_abc"} or ( 

722 # Distinguish synthetic typing modules from unnamed user modules 

723 not klass_root.name 

724 and klass_root is not node.root() 

725 ): 

726 if klass.name in _INFERABLE_TYPING_TYPES: 

727 yield klass.instantiate_class() 

728 else: 

729 yield util.Uninferable 

730 else: 

731 yield klass.instantiate_class() 

732 

733 

734def _resolve_assignment_parts(parts, assign_path, context): 

735 """Recursive function to resolve multiple assignments.""" 

736 assign_path = assign_path[:] 

737 index = assign_path.pop(0) 

738 for part in parts: 

739 assigned = None 

740 if isinstance(part, nodes.Dict): 

741 # A dictionary in an iterating context 

742 try: 

743 assigned, _ = part.items[index] 

744 except IndexError: 

745 return 

746 

747 elif hasattr(part, "getitem"): 

748 index_node = nodes.Const(index) 

749 try: 

750 assigned = part.getitem(index_node, context) 

751 except (AstroidTypeError, AstroidIndexError): 

752 return 

753 

754 if not assigned: 

755 return 

756 

757 if not assign_path: 

758 # we achieved to resolved the assignment path, don't infer the 

759 # last part 

760 yield assigned 

761 elif isinstance(assigned, util.UninferableBase): 

762 return 

763 else: 

764 # we are not yet on the last part of the path search on each 

765 # possibly inferred value 

766 try: 

767 yield from _resolve_assignment_parts( 

768 assigned.infer(context), assign_path, context 

769 ) 

770 except InferenceError: 

771 return 

772 

773 

774@decorators.raise_if_nothing_inferred 

775def excepthandler_assigned_stmts( 

776 self: nodes.ExceptHandler, 

777 node: node_classes.AssignedStmtsPossibleNode = None, 

778 context: InferenceContext | None = None, 

779 assign_path: list[int] | None = None, 

780) -> Any: 

781 from astroid import objects # pylint: disable=import-outside-toplevel 

782 

783 def _generate_assigned(): 

784 for assigned in node_classes.unpack_infer(self.type): 

785 if isinstance(assigned, nodes.ClassDef): 

786 assigned = objects.ExceptionInstance(assigned) 

787 

788 yield assigned 

789 

790 if isinstance(self.parent, node_classes.TryStar): 

791 # except * handler has assigned ExceptionGroup with caught 

792 # exceptions under exceptions attribute 

793 # pylint: disable-next=stop-iteration-return 

794 eg = next(node_classes.unpack_infer(extract_node(""" 

795from builtins import ExceptionGroup 

796ExceptionGroup 

797"""))) 

798 assigned = objects.ExceptionInstance(eg) 

799 assigned.instance_attrs["exceptions"] = [ 

800 nodes.Tuple.from_elements(_generate_assigned()) 

801 ] 

802 yield assigned 

803 else: 

804 yield from _generate_assigned() 

805 return { 

806 "node": self, 

807 "unknown": node, 

808 "assign_path": assign_path, 

809 "context": context, 

810 } 

811 

812 

813def _infer_context_manager(self, mgr, context): 

814 try: 

815 inferred = next(mgr.infer(context=context)) 

816 except StopIteration as e: 

817 raise InferenceError(node=mgr) from e 

818 if isinstance(inferred, bases.Generator): 

819 # Check if it is decorated with contextlib.contextmanager. 

820 func = inferred.parent 

821 if not func.decorators: 

822 raise InferenceError( 

823 "No decorators found on inferred generator %s", node=func 

824 ) 

825 

826 for decorator_node in func.decorators.nodes: 

827 decorator = next(decorator_node.infer(context=context), None) 

828 if isinstance(decorator, nodes.FunctionDef): 

829 if decorator.qname() == _CONTEXTLIB_MGR: 

830 break 

831 else: 

832 # It doesn't interest us. 

833 raise InferenceError(node=func) 

834 try: 

835 yield next(inferred.infer_yield_types()) 

836 except StopIteration as e: 

837 raise InferenceError(node=func) from e 

838 

839 elif isinstance(inferred, bases.Instance): 

840 try: 

841 enter = next(inferred.igetattr("__enter__", context=context)) 

842 except (InferenceError, AttributeInferenceError, StopIteration) as exc: 

843 raise InferenceError(node=inferred) from exc 

844 if not isinstance(enter, bases.BoundMethod): 

845 raise InferenceError(node=enter) 

846 yield from enter.infer_call_result(self, context) 

847 else: 

848 raise InferenceError(node=mgr) 

849 

850 

851@decorators.raise_if_nothing_inferred 

852def with_assigned_stmts( 

853 self: nodes.With, 

854 node: node_classes.AssignedStmtsPossibleNode = None, 

855 context: InferenceContext | None = None, 

856 assign_path: list[int] | None = None, 

857) -> Any: 

858 """Infer names and other nodes from a *with* statement. 

859 

860 This enables only inference for name binding in a *with* statement. 

861 For instance, in the following code, inferring `func` will return 

862 the `ContextManager` class, not whatever ``__enter__`` returns. 

863 We are doing this intentionally, because we consider that the context 

864 manager result is whatever __enter__ returns and what it is binded 

865 using the ``as`` keyword. 

866 

867 class ContextManager(object): 

868 def __enter__(self): 

869 return 42 

870 with ContextManager() as f: 

871 pass 

872 

873 # ContextManager().infer() will return ContextManager 

874 # f.infer() will return 42. 

875 

876 Arguments: 

877 self: nodes.With 

878 node: The target of the assignment, `as (a, b)` in `with foo as (a, b)`. 

879 context: Inference context used for caching already inferred objects 

880 assign_path: 

881 A list of indices, where each index specifies what item to fetch from 

882 the inference results. 

883 """ 

884 try: 

885 mgr = next(mgr for (mgr, vars) in self.items if vars == node) 

886 except StopIteration: 

887 return None 

888 if assign_path is None: 

889 yield from _infer_context_manager(self, mgr, context) 

890 else: 

891 for result in _infer_context_manager(self, mgr, context): 

892 # Walk the assign_path and get the item at the final index. 

893 obj = result 

894 for index in assign_path: 

895 if not hasattr(obj, "elts"): 

896 raise InferenceError( 

897 "Wrong type ({targets!r}) for {node!r} assignment", 

898 node=self, 

899 targets=node, 

900 assign_path=assign_path, 

901 context=context, 

902 ) 

903 try: 

904 obj = obj.elts[index] 

905 except IndexError as exc: 

906 raise InferenceError( 

907 "Tried to infer a nonexistent target with index {index} " 

908 "in {node!r}.", 

909 node=self, 

910 targets=node, 

911 assign_path=assign_path, 

912 context=context, 

913 ) from exc 

914 except TypeError as exc: 

915 raise InferenceError( 

916 "Tried to unpack a non-iterable value in {node!r}.", 

917 node=self, 

918 targets=node, 

919 assign_path=assign_path, 

920 context=context, 

921 ) from exc 

922 yield obj 

923 return { 

924 "node": self, 

925 "unknown": node, 

926 "assign_path": assign_path, 

927 "context": context, 

928 } 

929 

930 

931@decorators.raise_if_nothing_inferred 

932def named_expr_assigned_stmts( 

933 self: nodes.NamedExpr, 

934 node: node_classes.AssignedStmtsPossibleNode, 

935 context: InferenceContext | None = None, 

936 assign_path: list[int] | None = None, 

937) -> Any: 

938 """Infer names and other nodes from an assignment expression.""" 

939 if self.target == node: 

940 yield from self.value.infer(context=context) 

941 else: 

942 raise InferenceError( 

943 "Cannot infer NamedExpr node {node!r}", 

944 node=self, 

945 assign_path=assign_path, 

946 context=context, 

947 ) 

948 

949 

950@decorators.yes_if_nothing_inferred 

951def starred_assigned_stmts( # noqa: C901 

952 self: nodes.Starred, 

953 node: node_classes.AssignedStmtsPossibleNode = None, 

954 context: InferenceContext | None = None, 

955 assign_path: list[int] | None = None, 

956) -> Any: 

957 """ 

958 Arguments: 

959 self: nodes.Starred 

960 node: a node related to the current underlying Node. 

961 context: Inference context used for caching already inferred objects 

962 assign_path: 

963 A list of indices, where each index specifies what item to fetch from 

964 the inference results. 

965 """ 

966 

967 # pylint: disable = too-many-locals, too-many-statements, too-many-branches 

968 

969 def _determine_starred_iteration_lookups( 

970 starred: nodes.Starred, target: nodes.Tuple, lookups: list[tuple[int, int]] 

971 ) -> None: 

972 # Determine the lookups for the rhs of the iteration 

973 itered = target.itered() 

974 for index, element in enumerate(itered): 

975 if isinstance(element, nodes.Starred) and element is starred: 

976 lookups.append((index, len(itered))) 

977 break 

978 if isinstance(element, nodes.Tuple): 

979 lookups.append((index, len(element.itered()))) 

980 _determine_starred_iteration_lookups(starred, element, lookups) 

981 

982 stmt = self.statement() 

983 if not isinstance(stmt, (nodes.Assign, nodes.For)): 

984 raise InferenceError( 

985 "Statement {stmt!r} enclosing {node!r} must be an Assign or For node.", 

986 node=self, 

987 stmt=stmt, 

988 unknown=node, 

989 context=context, 

990 ) 

991 

992 if context is None: 

993 context = InferenceContext() 

994 

995 if isinstance(stmt, nodes.Assign): 

996 value = stmt.value 

997 lhs = stmt.targets[0] 

998 if not isinstance(lhs, nodes.BaseContainer): 

999 yield util.Uninferable 

1000 return 

1001 

1002 if sum(1 for _ in lhs.nodes_of_class(nodes.Starred)) > 1: 

1003 raise InferenceError( 

1004 "Too many starred arguments in the assignment targets {lhs!r}.", 

1005 node=self, 

1006 targets=lhs, 

1007 unknown=node, 

1008 context=context, 

1009 ) 

1010 

1011 try: 

1012 rhs = next(value.infer(context)) 

1013 except (InferenceError, StopIteration): 

1014 yield util.Uninferable 

1015 return 

1016 if isinstance(rhs, util.UninferableBase) or not hasattr(rhs, "itered"): 

1017 yield util.Uninferable 

1018 return 

1019 

1020 try: 

1021 elts = collections.deque(rhs.itered()) # type: ignore[union-attr] 

1022 except TypeError: 

1023 yield util.Uninferable 

1024 return 

1025 

1026 # Unpack iteratively the values from the rhs of the assignment, 

1027 # until the find the starred node. What will remain will 

1028 # be the list of values which the Starred node will represent 

1029 # This is done in two steps, from left to right to remove 

1030 # anything before the starred node and from right to left 

1031 # to remove anything after the starred node. 

1032 

1033 for index, left_node in enumerate(lhs.elts): 

1034 if not isinstance(left_node, nodes.Starred): 

1035 if not elts: 

1036 break 

1037 elts.popleft() 

1038 continue 

1039 lhs_elts = collections.deque(reversed(lhs.elts[index:])) 

1040 for right_node in lhs_elts: 

1041 if not isinstance(right_node, nodes.Starred): 

1042 if not elts: 

1043 break 

1044 elts.pop() 

1045 continue 

1046 

1047 # We're done unpacking. 

1048 packed = nodes.List( 

1049 ctx=Context.Store, 

1050 parent=self, 

1051 lineno=lhs.lineno, 

1052 col_offset=lhs.col_offset, 

1053 ) 

1054 packed.postinit(elts=list(elts)) 

1055 yield packed 

1056 break 

1057 

1058 if isinstance(stmt, nodes.For): 

1059 try: 

1060 inferred_iterable = next(stmt.iter.infer(context=context)) 

1061 except (InferenceError, StopIteration): 

1062 yield util.Uninferable 

1063 return 

1064 if isinstance(inferred_iterable, util.UninferableBase) or not hasattr( 

1065 inferred_iterable, "itered" 

1066 ): 

1067 yield util.Uninferable 

1068 return 

1069 try: 

1070 itered = inferred_iterable.itered() # type: ignore[union-attr] 

1071 except TypeError: 

1072 yield util.Uninferable 

1073 return 

1074 

1075 target = stmt.target 

1076 

1077 if not isinstance(target, nodes.Tuple): 

1078 raise InferenceError( 

1079 f"Could not make sense of this, the target must be a tuple, not {type(target)!r}", 

1080 context=context, 

1081 ) 

1082 

1083 lookups: list[tuple[int, int]] = [] 

1084 _determine_starred_iteration_lookups(self, target, lookups) 

1085 if not lookups: 

1086 raise InferenceError( 

1087 "Could not make sense of this, needs at least a lookup", context=context 

1088 ) 

1089 

1090 # Make the last lookup a slice, since that what we want for a Starred node 

1091 last_element_index, last_element_length = lookups[-1] 

1092 is_starred_last = last_element_index == (last_element_length - 1) 

1093 

1094 # The elements after the starred one are counted back from the end of the 

1095 # iterable, whose length is unrelated to the target's. 

1096 lookup_slice = slice( 

1097 last_element_index, 

1098 ( 

1099 None 

1100 if is_starred_last 

1101 else -(last_element_length - last_element_index - 1) 

1102 ), 

1103 ) 

1104 last_lookup = lookup_slice 

1105 

1106 for element in itered: 

1107 # We probably want to infer the potential values *for each* element in an 

1108 # iterable, but we can't infer a list of all values, when only a list of 

1109 # step values are expected: 

1110 # 

1111 # for a, *b in [...]: 

1112 # b 

1113 # 

1114 # *b* should now point to just the elements at that particular iteration step, 

1115 # which astroid can't know about. 

1116 

1117 found_element = None 

1118 for index, lookup in enumerate(lookups): 

1119 if not hasattr(element, "itered"): 

1120 break 

1121 if index + 1 is len(lookups): 

1122 cur_lookup: slice | int = last_lookup 

1123 else: 

1124 # Grab just the index, not the whole length 

1125 cur_lookup = lookup[0] 

1126 try: 

1127 itered_inner_element = element.itered() 

1128 element = itered_inner_element[cur_lookup] 

1129 except IndexError: 

1130 break 

1131 except TypeError: 

1132 # Most likely the itered() call failed, cannot make sense of this 

1133 yield util.Uninferable 

1134 return 

1135 else: 

1136 found_element = element 

1137 

1138 # Only a lookup chain applied to completion ends with the slice 

1139 # lookup, which extracts a list. Breaking out of the loop early 

1140 # leaves the last intermediate element instead (or nothing, when 

1141 # the first lookup fails), which says nothing about the starred 

1142 # values. 

1143 if not isinstance(found_element, list): 

1144 yield util.Uninferable 

1145 return 

1146 

1147 unpacked = nodes.List( 

1148 ctx=Context.Store, 

1149 parent=self, 

1150 lineno=self.lineno, 

1151 col_offset=self.col_offset, 

1152 ) 

1153 unpacked.postinit(elts=found_element) 

1154 yield unpacked 

1155 return 

1156 

1157 yield util.Uninferable 

1158 

1159 

1160@decorators.yes_if_nothing_inferred 

1161def match_mapping_assigned_stmts( 

1162 self: nodes.MatchMapping, 

1163 node: nodes.AssignName, 

1164 context: InferenceContext | None = None, 

1165 assign_path: None = None, 

1166) -> Generator[nodes.NodeNG]: 

1167 """Return empty generator (return -> raises StopIteration) so inferred value 

1168 is Uninferable. 

1169 """ 

1170 return 

1171 yield 

1172 

1173 

1174@decorators.yes_if_nothing_inferred 

1175def match_star_assigned_stmts( 

1176 self: nodes.MatchStar, 

1177 node: nodes.AssignName, 

1178 context: InferenceContext | None = None, 

1179 assign_path: None = None, 

1180) -> Generator[nodes.NodeNG]: 

1181 """Return empty generator (return -> raises StopIteration) so inferred value 

1182 is Uninferable. 

1183 """ 

1184 return 

1185 yield 

1186 

1187 

1188@decorators.yes_if_nothing_inferred 

1189def match_as_assigned_stmts( 

1190 self: nodes.MatchAs, 

1191 node: nodes.AssignName, 

1192 context: InferenceContext | None = None, 

1193 assign_path: None = None, 

1194) -> Generator[nodes.NodeNG]: 

1195 """Infer MatchAs as the Match subject if it's the only MatchCase pattern 

1196 else raise StopIteration to yield Uninferable. 

1197 """ 

1198 if ( 

1199 isinstance(self.parent, nodes.MatchCase) 

1200 and isinstance(self.parent.parent, nodes.Match) 

1201 and self.pattern is None 

1202 ): 

1203 yield self.parent.parent.subject 

1204 

1205 

1206@decorators.yes_if_nothing_inferred 

1207def generic_type_assigned_stmts( 

1208 self: nodes.TypeVar | nodes.TypeVarTuple | nodes.ParamSpec, 

1209 node: nodes.AssignName, 

1210 context: InferenceContext | None = None, 

1211 assign_path: None = None, 

1212) -> Generator[nodes.NodeNG]: 

1213 """Return the type parameter node itself so inference doesn't fail 

1214 when evaluating __class_getitem__ and so that the node's type is 

1215 preserved for downstream checks (e.g. TypeVarTuple starred handling). 

1216 """ 

1217 yield self