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"""
6This module contains the classes for "scoped" node, i.e. which are opening a
7new local scope in the language definition : Module, ClassDef, FunctionDef (and
8Lambda, GeneratorExp, DictComp and SetComp to some extent).
9"""
10
11from __future__ import annotations
12
13import io
14import itertools
15import os
16from collections.abc import Generator, Iterable, Iterator, Sequence
17from functools import cached_property, lru_cache
18from typing import TYPE_CHECKING, ClassVar, Literal, NoReturn, Self
19
20from astroid import bases, protocols, util
21from astroid.context import (
22 CallContext,
23 InferenceContext,
24 bind_context_to_node,
25 copy_context,
26)
27from astroid.exceptions import (
28 AstroidBuildingError,
29 AstroidTypeError,
30 AttributeInferenceError,
31 DuplicateBasesError,
32 InconsistentMroError,
33 InferenceError,
34 MroError,
35 ParentMissingError,
36 StatementMissing,
37 TooManyLevelsError,
38)
39from astroid.interpreter.dunder_lookup import lookup
40from astroid.interpreter.objectmodel import ClassModel, FunctionModel, ModuleModel
41from astroid.manager import AstroidManager
42from astroid.nodes import _base_nodes, node_classes
43from astroid.nodes.scoped_nodes.mixin import ComprehensionScope, LocalsDictNodeNG
44from astroid.nodes.scoped_nodes.utils import builtin_lookup
45from astroid.nodes.utils import Position
46from astroid.typing import (
47 InferBinaryOp,
48 InferenceErrorInfo,
49 InferenceResult,
50 SuccessfulInferenceResult,
51)
52
53if TYPE_CHECKING:
54 from astroid import nodes, objects
55 from astroid.nodes import Arguments, Const, NodeNG
56 from astroid.nodes._base_nodes import LookupMixIn
57
58
59ITER_METHODS = ("__iter__", "__getitem__")
60EXCEPTION_BASE_CLASSES = frozenset({"Exception", "BaseException"})
61BUILTIN_DESCRIPTORS = frozenset(
62 {"classmethod", "staticmethod", "builtins.classmethod", "builtins.staticmethod"}
63)
64
65
66def _c3_merge(sequences, cls, context):
67 """Merges MROs in *sequences* to a single MRO using the C3 algorithm.
68
69 Adapted from http://www.python.org/download/releases/2.3/mro/.
70
71 """
72 result = []
73 while True:
74 sequences = [s for s in sequences if s] # purge empty sequences
75 if not sequences:
76 return result
77 for s1 in sequences: # find merge candidates among seq heads
78 candidate = s1[0]
79 for s2 in sequences:
80 if candidate in s2[1:]:
81 candidate = None
82 break # reject the current head, it appears later
83 else:
84 break
85 if not candidate:
86 # Show all the remaining bases, which were considered as
87 # candidates for the next mro sequence.
88 raise InconsistentMroError(
89 message="Cannot create a consistent method resolution order "
90 "for MROs {mros} of class {cls!r}.",
91 mros=sequences,
92 cls=cls,
93 context=context,
94 )
95
96 result.append(candidate)
97 # remove the chosen candidate
98 for seq in sequences:
99 if seq[0] == candidate:
100 del seq[0]
101 return None
102
103
104def clean_typing_generic_mro(sequences: list[list[ClassDef]]) -> None:
105 """A class can inherit from typing.Generic directly, as base,
106 and as base of bases. The merged MRO must however only contain the last entry.
107 To prepare for _c3_merge, remove some typing.Generic entries from
108 sequences if multiple are present.
109
110 This method will check if Generic is in inferred_bases and also
111 part of bases_mro. If true, remove it from inferred_bases
112 as well as its entry the bases_mro.
113
114 Format sequences: [[self]] + bases_mro + [inferred_bases]
115 """
116 bases_mro = sequences[1:-1]
117 inferred_bases = sequences[-1]
118 # Check if Generic is part of inferred_bases
119 for i, base in enumerate(inferred_bases):
120 if base.qname() == "typing.Generic":
121 position_in_inferred_bases = i
122 break
123 else:
124 return
125 # Check if also part of bases_mro
126 # Ignore entry for typing.Generic
127 for i, seq in enumerate(bases_mro):
128 if i == position_in_inferred_bases:
129 continue
130 if any(base.qname() == "typing.Generic" for base in seq):
131 break
132 else:
133 return
134 # Found multiple Generics in mro, remove entry from inferred_bases
135 # and the corresponding one from bases_mro
136 inferred_bases.pop(position_in_inferred_bases)
137 bases_mro.pop(position_in_inferred_bases)
138
139
140def clean_duplicates_mro(
141 sequences: list[list[ClassDef]],
142 cls: ClassDef,
143 context: InferenceContext | None,
144) -> list[list[ClassDef]]:
145 for sequence in sequences:
146 seen = set()
147 for node in sequence:
148 lineno_and_qname = (node.lineno, node.qname())
149 if lineno_and_qname in seen:
150 raise DuplicateBasesError(
151 message="Duplicates found in MROs {mros} for {cls!r}.",
152 mros=sequences,
153 cls=cls,
154 context=context,
155 )
156 seen.add(lineno_and_qname)
157 return sequences
158
159
160def function_to_method(n, klass):
161 if isinstance(n, FunctionDef):
162 if n.type == "classmethod":
163 return bases.BoundMethod(n, klass)
164 if n.type == "property":
165 return n
166 if n.type != "staticmethod":
167 return bases.UnboundMethod(n)
168 return n
169
170
171def _infer_last(
172 arg: SuccessfulInferenceResult, context: InferenceContext
173) -> InferenceResult:
174 res = util.Uninferable
175 for b in arg.infer(context=context.clone()):
176 res = b
177 return res
178
179
180class Module(LocalsDictNodeNG):
181 """Class representing an :class:`ast.Module` node.
182
183 >>> import astroid
184 >>> node = astroid.extract_node('import astroid')
185 >>> node
186 <Import l.1 at 0x...>
187 >>> node.parent
188 <Module l.0 at 0x...>
189 """
190
191 _astroid_fields = ("doc_node", "body")
192
193 doc_node: Const | None
194 """The doc node associated with this node."""
195
196 # attributes below are set by the builder module or by raw factories
197
198 file_bytes: str | bytes | None = None
199 """The string/bytes that this ast was built from."""
200
201 file_encoding: str | None = None
202 """The encoding of the source file."""
203
204 special_attributes = ModuleModel()
205 """The names of special attributes that this module has."""
206
207 # names of module attributes available through the global scope
208 scope_attrs: ClassVar[set[str]] = {
209 "__name__",
210 "__doc__",
211 "__file__",
212 "__path__",
213 "__package__",
214 }
215 """The names of module attributes available through the global scope."""
216
217 _other_fields = (
218 "name",
219 "file",
220 "path",
221 "package",
222 "pure_python",
223 "future_imports",
224 "is_stub",
225 )
226 _other_other_fields = ("locals", "globals")
227
228 def __init__(
229 self,
230 name: str,
231 file: str | None = None,
232 path: Sequence[str] | None = None,
233 package: bool = False,
234 pure_python: bool = True,
235 is_stub: bool | None = False,
236 ) -> None:
237 self.name = name
238 """The name of the module."""
239
240 self.file = file
241 """The path to the file that this ast has been extracted from.
242
243 This will be ``None`` when the representation has been built from a
244 built-in module.
245 """
246
247 self.path = path
248
249 self.package = package
250 """Whether the node represents a package or a module."""
251
252 self.pure_python = pure_python
253 """Whether the ast was built from source."""
254
255 self.is_stub = bool(is_stub)
256 """Whether the module was loaded from a ``.pyi`` stub file."""
257
258 self.globals: dict[str, list[InferenceResult]]
259 """A map of the name of a global variable to the node defining the global."""
260
261 self.locals = self.globals = {}
262 """A map of the name of a local variable to the node defining the local."""
263
264 self.body: list[node_classes.NodeNG] = []
265 """The contents of the module."""
266
267 self.future_imports: set[str] = set()
268 """The imports from ``__future__``."""
269
270 super().__init__(
271 lineno=0, parent=None, col_offset=0, end_lineno=None, end_col_offset=None
272 )
273
274 # pylint: enable=redefined-builtin
275
276 def postinit(
277 self, body: list[node_classes.NodeNG], *, doc_node: Const | None = None
278 ):
279 self.body = body
280 self.doc_node = doc_node
281
282 def _get_stream(self) -> io.BytesIO | io.BufferedReader | None:
283 if self.file_bytes is not None:
284 return io.BytesIO(self.file_bytes)
285 if self.file is not None:
286 # pylint: disable=consider-using-with
287 stream = open(self.file, "rb")
288 return stream
289 return None
290
291 def stream(self) -> io.BytesIO | io.BufferedReader | None:
292 """Get a stream to the underlying file or bytes."""
293 return self._get_stream()
294
295 def block_range(self, lineno: int) -> tuple[int, int]:
296 """Get a range from where this node starts to where this node ends.
297
298 :param lineno: Unused.
299
300 :returns: The range of line numbers that this node belongs to.
301 """
302 return self.fromlineno, self.tolineno
303
304 def scope_lookup(
305 self, node: LookupMixIn, name: str, offset: int = 0
306 ) -> tuple[LocalsDictNodeNG, list[node_classes.NodeNG]]:
307 """Lookup where the given variable is assigned.
308
309 :param node: The node to look for assignments up to.
310 Any assignments after the given node are ignored.
311
312 :param name: The name of the variable to find assignments for.
313
314 :param offset: The line offset to filter statements up to.
315
316 :returns: This scope node and the list of assignments associated to the
317 given name according to the scope where it has been found (locals,
318 globals or builtin).
319 """
320 if name in self.scope_attrs and name not in self.locals:
321 try:
322 return self, self.getattr(name)
323 except AttributeInferenceError:
324 return self, []
325 return self._scope_lookup(node, name, offset)
326
327 def pytype(self) -> Literal["builtins.module"]:
328 """Get the name of the type that this node represents.
329
330 :returns: The name of the type.
331 """
332 return "builtins.module"
333
334 def display_type(self) -> str:
335 """A human readable type of this node.
336
337 :returns: The type of this node.
338 """
339 return "Module"
340
341 def getattr(
342 self, name, context: InferenceContext | None = None, ignore_locals=False
343 ):
344 if not name:
345 raise AttributeInferenceError(target=self, attribute=name, context=context)
346
347 result = []
348 name_in_locals = name in self.locals
349
350 if name in self.special_attributes and not ignore_locals and not name_in_locals:
351 result = [self.special_attributes.lookup(name)]
352 if name == "__name__":
353 main_const = node_classes.const_factory("__main__")
354 main_const.parent = AstroidManager().builtins_module
355 result.append(main_const)
356 elif not ignore_locals and name_in_locals:
357 result = self.locals[name]
358 elif self.package:
359 try:
360 result = [self.import_module(name, relative_only=True)]
361 except (AstroidBuildingError, SyntaxError) as exc:
362 raise AttributeInferenceError(
363 target=self, attribute=name, context=context
364 ) from exc
365 result = [n for n in result if not isinstance(n, node_classes.DelName)]
366 if result:
367 return result
368 raise AttributeInferenceError(target=self, attribute=name, context=context)
369
370 def igetattr(
371 self, name: str, context: InferenceContext | None = None
372 ) -> Iterator[InferenceResult]:
373 """Infer the possible values of the given variable.
374
375 :param name: The name of the variable to infer.
376
377 :returns: The inferred possible values.
378 """
379 # set lookup name since this is necessary to infer on import nodes for
380 # instance
381 context = copy_context(context)
382 context.lookupname = name
383 try:
384 return bases._infer_stmts(self.getattr(name, context), context, frame=self)
385 except AttributeInferenceError as error:
386 raise InferenceError(
387 str(error), target=self, attribute=name, context=context
388 ) from error
389
390 def fully_defined(self) -> bool:
391 """Check if this module has been build from a .py file.
392
393 If so, the module contains a complete representation,
394 including the code.
395
396 :returns: Whether the module has been built from a .py file.
397 """
398 return self.file is not None and self.file.endswith(".py")
399
400 def statement(self) -> NoReturn:
401 """The first parent node, including self, marked as statement node.
402
403 When called on a :class:`Module` this raises a StatementMissing.
404 """
405 raise StatementMissing(target=self)
406
407 def previous_sibling(self) -> None:
408 """The previous sibling statement.
409
410 A :class:`Module` has no sibling, so this is always ``None``.
411 """
412
413 def next_sibling(self) -> None:
414 """The next sibling statement node.
415
416 A :class:`Module` has no sibling, so this is always ``None``.
417 """
418
419 _absolute_import_activated = True
420
421 def absolute_import_activated(self) -> bool:
422 """Whether :pep:`328` absolute import behaviour has been enabled.
423
424 :returns: Whether :pep:`328` has been enabled.
425 """
426 return self._absolute_import_activated
427
428 def import_module(
429 self,
430 modname: str,
431 relative_only: bool = False,
432 level: int | None = None,
433 use_cache: bool = True,
434 ) -> Module:
435 """Get the ast for a given module as if imported from this module.
436
437 :param modname: The name of the module to "import".
438
439 :param relative_only: Whether to only consider relative imports.
440
441 :param level: The level of relative import.
442
443 :param use_cache: Whether to use the astroid_cache of modules.
444
445 :returns: The imported module ast.
446 """
447 if relative_only and level is None:
448 level = 0
449 absmodname = self.relative_to_absolute_name(modname, level)
450
451 try:
452 return AstroidManager().ast_from_module_name(
453 absmodname, use_cache=use_cache
454 )
455 except AstroidBuildingError:
456 # we only want to import a sub module or package of this module,
457 # skip here
458 if relative_only:
459 raise
460 # Don't repeat the same operation, e.g. for missing modules
461 # like "_winapi" or "nt" on POSIX systems.
462 if modname == absmodname:
463 raise
464 return AstroidManager().ast_from_module_name(modname, use_cache=use_cache)
465
466 def relative_to_absolute_name(self, modname: str, level: int | None) -> str:
467 """Get the absolute module name for a relative import.
468
469 The relative import can be implicit or explicit.
470
471 :param modname: The module name to convert.
472
473 :param level: The level of relative import.
474
475 :returns: The absolute module name.
476
477 :raises TooManyLevelsError: When the relative import refers to a
478 module too far above this one.
479 """
480 # XXX this returns non sens when called on an absolute import
481 # like 'pylint.checkers.astroid.utils'
482 # XXX doesn't return absolute name if self.name isn't absolute name
483 if self.absolute_import_activated() and level is None:
484 return modname
485 if level:
486 if self.package:
487 level = level - 1
488 package_name = self.name.rsplit(".", level)[0]
489 elif (
490 self.path
491 and not os.path.exists(os.path.dirname(self.path[0]) + "/__init__.py")
492 and os.path.exists(
493 os.path.dirname(self.path[0]) + "/" + modname.split(".")[0]
494 )
495 ):
496 level = level - 1
497 package_name = ""
498 else:
499 package_name = self.name.rsplit(".", level)[0]
500 if level and self.name.count(".") < level:
501 raise TooManyLevelsError(level=level, name=self.name)
502
503 elif self.package:
504 package_name = self.name
505 else:
506 package_name = self.name.rsplit(".", 1)[0]
507
508 if package_name:
509 if not modname:
510 return package_name
511 return f"{package_name}.{modname}"
512 return modname
513
514 def wildcard_import_names(self) -> list[str]:
515 """The list of imported names when this module is 'wildcard imported'.
516
517 It doesn't include the '__builtins__' name which is added by the
518 current CPython implementation of wildcard imports.
519
520 :returns: The list of imported names.
521 """
522 # We separate the different steps of lookup in try/excepts
523 # to avoid catching too many Exceptions
524 default = [name for name in self.keys() if not name.startswith("_")]
525 try:
526 all_values = self["__all__"]
527 except KeyError:
528 return default
529
530 try:
531 explicit = next(all_values.assigned_stmts())
532 except (InferenceError, StopIteration):
533 return default
534 except AttributeError:
535 # not an assignment node
536 # XXX infer?
537 return default
538
539 # Try our best to detect the exported name.
540 inferred = []
541 try:
542 explicit = next(explicit.infer())
543 except (InferenceError, StopIteration):
544 return default
545 if not isinstance(explicit, (node_classes.Tuple, node_classes.List)):
546 return default
547
548 def str_const(node) -> bool:
549 return isinstance(node, node_classes.Const) and isinstance(node.value, str)
550
551 for node in explicit.elts:
552 if str_const(node):
553 inferred.append(node.value)
554 else:
555 try:
556 inferred_node = next(node.infer())
557 except (InferenceError, StopIteration):
558 continue
559 if str_const(inferred_node):
560 inferred.append(inferred_node.value)
561 return inferred
562
563 def public_names(self) -> list[str]:
564 """The list of the names that are publicly available in this module.
565
566 :returns: The list of public names.
567 """
568 return [name for name in self.keys() if not name.startswith("_")]
569
570 def bool_value(self, context: InferenceContext | None = None) -> bool:
571 """Determine the boolean value of this node.
572
573 :returns: The boolean value of this node.
574 For a :class:`Module` this is always ``True``.
575 """
576 return True
577
578 def get_children(self):
579 yield from self.body
580
581 def frame(self, *, future: Literal[None, True] = None) -> Self:
582 """The node's frame node.
583
584 A frame node is a :class:`Module`, :class:`FunctionDef`,
585 :class:`ClassDef` or :class:`Lambda`.
586
587 :returns: The node itself.
588 """
589 return self
590
591 def _infer(self, context: InferenceContext | None = None) -> Generator[Module]:
592 yield self
593
594
595class __SyntheticRoot(Module):
596 def __init__(self):
597 super().__init__("__astroid_synthetic", pure_python=False)
598
599
600SYNTHETIC_ROOT = __SyntheticRoot()
601
602
603class GeneratorExp(ComprehensionScope):
604 """Class representing an :class:`ast.GeneratorExp` node.
605
606 >>> import astroid
607 >>> node = astroid.extract_node('(thing for thing in things if thing)')
608 >>> node
609 <GeneratorExp.<genexpr> l.1 at 0x...>
610 """
611
612 _astroid_fields = ("elt", "generators")
613 _other_other_fields = ("locals",)
614 name = "<genexpr>"
615 elt: NodeNG
616 """The element that forms the output of the expression."""
617
618 def __init__(
619 self,
620 lineno: int,
621 col_offset: int,
622 parent: NodeNG,
623 *,
624 end_lineno: int | None,
625 end_col_offset: int | None,
626 ) -> None:
627 self.locals = {}
628 """A map of the name of a local variable to the node defining the local."""
629
630 self.generators: list[nodes.Comprehension] = []
631 """The generators that are looped through."""
632
633 super().__init__(
634 lineno=lineno,
635 col_offset=col_offset,
636 end_lineno=end_lineno,
637 end_col_offset=end_col_offset,
638 parent=parent,
639 )
640
641 def postinit(self, elt: NodeNG, generators: list[nodes.Comprehension]) -> None:
642 self.elt = elt
643 self.generators = generators
644
645 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
646 """Determine the boolean value of this node.
647
648 :returns: The boolean value of this node.
649 For a :class:`GeneratorExp` this is always ``True``.
650 """
651 return True
652
653 def get_children(self):
654 yield self.elt
655
656 yield from self.generators
657
658
659class DictComp(ComprehensionScope):
660 """Class representing an :class:`ast.DictComp` node.
661
662 >>> import astroid
663 >>> node = astroid.extract_node('{k:v for k, v in things if k > v}')
664 >>> node
665 <DictComp.<dictcomp> l.1 at 0x...>
666 """
667
668 _astroid_fields = ("key", "value", "generators")
669 _other_other_fields = ("locals",)
670 name = "<dictcomp>"
671 key: NodeNG
672 """What produces the keys."""
673
674 value: NodeNG
675 """What produces the values."""
676
677 def __init__(
678 self,
679 lineno: int,
680 col_offset: int,
681 parent: NodeNG,
682 *,
683 end_lineno: int | None,
684 end_col_offset: int | None,
685 ) -> None:
686 self.locals = {}
687 """A map of the name of a local variable to the node defining the local."""
688
689 super().__init__(
690 lineno=lineno,
691 col_offset=col_offset,
692 end_lineno=end_lineno,
693 end_col_offset=end_col_offset,
694 parent=parent,
695 )
696
697 def postinit(
698 self, key: NodeNG, value: NodeNG, generators: list[nodes.Comprehension]
699 ) -> None:
700 self.key = key
701 self.value = value
702 self.generators = generators
703
704 def bool_value(
705 self, context: InferenceContext | None = None
706 ) -> util.UninferableBase:
707 """Determine the boolean value of this node.
708
709 :returns: The boolean value of this node.
710 For a :class:`DictComp` this is always :obj:`~astroid.Uninferable`.
711 """
712 return util.Uninferable
713
714 def get_children(self):
715 yield self.key
716 yield self.value
717
718 yield from self.generators
719
720
721class SetComp(ComprehensionScope):
722 """Class representing an :class:`ast.SetComp` node.
723
724 >>> import astroid
725 >>> node = astroid.extract_node('{thing for thing in things if thing}')
726 >>> node
727 <SetComp.<setcomp> l.1 at 0x...>
728 """
729
730 _astroid_fields = ("elt", "generators")
731 _other_other_fields = ("locals",)
732 name = "<setcomp>"
733 elt: NodeNG
734 """The element that forms the output of the expression."""
735
736 def __init__(
737 self,
738 lineno: int,
739 col_offset: int,
740 parent: NodeNG,
741 *,
742 end_lineno: int | None,
743 end_col_offset: int | None,
744 ) -> None:
745 self.locals = {}
746 """A map of the name of a local variable to the node defining the local."""
747
748 self.generators: list[nodes.Comprehension] = []
749 """The generators that are looped through."""
750
751 super().__init__(
752 lineno=lineno,
753 col_offset=col_offset,
754 end_lineno=end_lineno,
755 end_col_offset=end_col_offset,
756 parent=parent,
757 )
758
759 def postinit(self, elt: NodeNG, generators: list[nodes.Comprehension]) -> None:
760 self.elt = elt
761 self.generators = generators
762
763 def bool_value(
764 self, context: InferenceContext | None = None
765 ) -> util.UninferableBase:
766 """Determine the boolean value of this node.
767
768 :returns: The boolean value of this node.
769 For a :class:`SetComp` this is always :obj:`~astroid.Uninferable`.
770 """
771 return util.Uninferable
772
773 def get_children(self):
774 yield self.elt
775
776 yield from self.generators
777
778
779class ListComp(ComprehensionScope):
780 """Class representing an :class:`ast.ListComp` node.
781
782 >>> import astroid
783 >>> node = astroid.extract_node('[thing for thing in things if thing]')
784 >>> node
785 <ListComp.<listcomp> l.1 at 0x...>
786 """
787
788 _astroid_fields = ("elt", "generators")
789 _other_other_fields = ("locals",)
790 name = "<listcomp>"
791
792 elt: NodeNG
793 """The element that forms the output of the expression."""
794
795 def __init__(
796 self,
797 lineno: int,
798 col_offset: int,
799 parent: NodeNG,
800 *,
801 end_lineno: int | None,
802 end_col_offset: int | None,
803 ) -> None:
804 self.locals = {}
805 """A map of the name of a local variable to the node defining it."""
806
807 self.generators: list[nodes.Comprehension] = []
808 """The generators that are looped through."""
809
810 super().__init__(
811 lineno=lineno,
812 col_offset=col_offset,
813 end_lineno=end_lineno,
814 end_col_offset=end_col_offset,
815 parent=parent,
816 )
817
818 def postinit(self, elt: NodeNG, generators: list[nodes.Comprehension]):
819 self.elt = elt
820 self.generators = generators
821
822 def bool_value(
823 self, context: InferenceContext | None = None
824 ) -> util.UninferableBase:
825 """Determine the boolean value of this node.
826
827 :returns: The boolean value of this node.
828 For a :class:`ListComp` this is always :obj:`~astroid.Uninferable`.
829 """
830 return util.Uninferable
831
832 def get_children(self):
833 yield self.elt
834
835 yield from self.generators
836
837
838def _infer_decorator_callchain(node):
839 """Detect decorator call chaining and see if the end result is a
840 static or a classmethod.
841 """
842 if not isinstance(node, FunctionDef):
843 return None
844 if not node.parent:
845 return None
846 try:
847 result = next(node.infer_call_result(node.parent), None)
848 except InferenceError:
849 return None
850 if isinstance(result, bases.Instance):
851 result = result._proxied
852 if isinstance(result, ClassDef):
853 if result.is_subtype_of("builtins.classmethod"):
854 return "classmethod"
855 if result.is_subtype_of("builtins.staticmethod"):
856 return "staticmethod"
857 if isinstance(result, FunctionDef):
858 if not result.decorators:
859 return None
860 # Determine if this function is decorated with one of the builtin descriptors we want.
861 for decorator in result.decorators.nodes:
862 if isinstance(decorator, node_classes.Name):
863 if decorator.name in BUILTIN_DESCRIPTORS:
864 return decorator.name
865 if (
866 isinstance(decorator, node_classes.Attribute)
867 and isinstance(decorator.expr, node_classes.Name)
868 and decorator.expr.name == "builtins"
869 and decorator.attrname in BUILTIN_DESCRIPTORS
870 ):
871 return decorator.attrname
872 return None
873
874
875class Lambda(_base_nodes.FilterStmtsBaseNode, LocalsDictNodeNG):
876 """Class representing an :class:`ast.Lambda` node.
877
878 >>> import astroid
879 >>> node = astroid.extract_node('lambda arg: arg + 1')
880 >>> node
881 <Lambda.<lambda> l.1 at 0x...>
882 """
883
884 _astroid_fields: ClassVar[tuple[str, ...]] = ("args", "body")
885 _other_other_fields: ClassVar[tuple[str, ...]] = ("locals",)
886 name = "<lambda>"
887 is_lambda = True
888 special_attributes = FunctionModel()
889 """The names of special attributes that this function has."""
890
891 args: Arguments
892 """The arguments that the function takes."""
893
894 body: NodeNG
895 """The contents of the function body."""
896
897 def implicit_parameters(self) -> Literal[0]:
898 return 0
899
900 @property
901 def type(self) -> Literal["method", "function"]:
902 """Whether this is a method or function.
903
904 :returns: 'method' if this is a method, 'function' otherwise.
905 """
906 if self.args.arguments and self.args.arguments[0].name == "self":
907 if self.parent and isinstance(self.parent.scope(), ClassDef):
908 return "method"
909 return "function"
910
911 def __init__(
912 self,
913 lineno: int,
914 col_offset: int,
915 parent: NodeNG,
916 *,
917 end_lineno: int | None,
918 end_col_offset: int | None,
919 ):
920 self.locals = {}
921 """A map of the name of a local variable to the node defining it."""
922
923 self.instance_attrs: dict[str, list[InferenceResult]] = {}
924
925 super().__init__(
926 lineno=lineno,
927 col_offset=col_offset,
928 end_lineno=end_lineno,
929 end_col_offset=end_col_offset,
930 parent=parent,
931 )
932
933 def postinit(self, args: Arguments, body: NodeNG) -> None:
934 self.args = args
935 self.body = body
936
937 def pytype(self) -> Literal["builtins.instancemethod", "builtins.function"]:
938 """Get the name of the type that this node represents.
939
940 :returns: The name of the type.
941 """
942 if "method" in self.type:
943 return "builtins.instancemethod"
944 return "builtins.function"
945
946 def display_type(self) -> str:
947 """A human readable type of this node.
948
949 :returns: The type of this node.
950 """
951 if "method" in self.type:
952 return "Method"
953 return "Function"
954
955 def callable(self) -> Literal[True]:
956 """Whether this node defines something that is callable.
957
958 :returns: Whether this defines something that is callable
959 For a :class:`Lambda` this is always ``True``.
960 """
961 return True
962
963 def argnames(self) -> list[str]:
964 """Get the names of each of the arguments, including that
965 of the collections of variable-length arguments ("args", "kwargs",
966 etc.), as well as positional-only and keyword-only arguments.
967
968 :returns: The names of the arguments.
969 """
970 if self.args.arguments: # maybe None with builtin functions
971 names = [elt.name for elt in self.args.arguments]
972 else:
973 names = []
974
975 return names
976
977 def infer_call_result(
978 self,
979 caller: SuccessfulInferenceResult | None,
980 context: InferenceContext | None = None,
981 ) -> Iterator[InferenceResult]:
982 """Infer what the function returns when called."""
983 return self.body.infer(context)
984
985 def scope_lookup(
986 self, node: LookupMixIn, name: str, offset: int = 0
987 ) -> tuple[LocalsDictNodeNG, list[NodeNG]]:
988 """Lookup where the given names is assigned.
989
990 :param node: The node to look for assignments up to.
991 Any assignments after the given node are ignored.
992
993 :param name: The name to find assignments for.
994
995 :param offset: The line offset to filter statements up to.
996
997 :returns: This scope node and the list of assignments associated to the
998 given name according to the scope where it has been found (locals,
999 globals or builtin).
1000 """
1001 if (self.args.defaults and node in self.args.defaults) or (
1002 self.args.kw_defaults and node in self.args.kw_defaults
1003 ):
1004 if not self.parent:
1005 raise ParentMissingError(target=self)
1006 frame = self.parent.frame()
1007 # line offset to avoid that def func(f=func) resolve the default
1008 # value to the defined function
1009 offset = -1
1010 else:
1011 # check this is not used in function decorators
1012 frame = self
1013 return frame._scope_lookup(node, name, offset)
1014
1015 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
1016 """Determine the boolean value of this node.
1017
1018 :returns: The boolean value of this node.
1019 For a :class:`Lambda` this is always ``True``.
1020 """
1021 return True
1022
1023 def get_children(self):
1024 yield self.args
1025 yield self.body
1026
1027 def frame(self, *, future: Literal[None, True] = None) -> Self:
1028 """The node's frame node.
1029
1030 A frame node is a :class:`Module`, :class:`FunctionDef`,
1031 :class:`ClassDef` or :class:`Lambda`.
1032
1033 :returns: The node itself.
1034 """
1035 return self
1036
1037 def getattr(
1038 self, name: str, context: InferenceContext | None = None
1039 ) -> list[InferenceResult]:
1040 if not name:
1041 raise AttributeInferenceError(target=self, attribute=name, context=context)
1042
1043 # Copy, so that adding the special attribute does not modify instance_attrs
1044 found_attrs = list(self.instance_attrs.get(name, []))
1045 if name in self.special_attributes:
1046 found_attrs.append(self.special_attributes.lookup(name))
1047 if found_attrs:
1048 return found_attrs
1049 raise AttributeInferenceError(target=self, attribute=name)
1050
1051 def _infer(self, context: InferenceContext | None = None) -> Generator[Lambda]:
1052 yield self
1053
1054 def _get_yield_nodes_skip_functions(self):
1055 """A Lambda node can contain a Yield node in the body."""
1056 yield from self.body._get_yield_nodes_skip_functions()
1057
1058
1059class FunctionDef(
1060 _base_nodes.MultiLineBlockNode,
1061 _base_nodes.FilterStmtsBaseNode,
1062 _base_nodes.Statement,
1063 LocalsDictNodeNG,
1064):
1065 """Class representing an :class:`ast.FunctionDef`.
1066
1067 >>> import astroid
1068 >>> node = astroid.extract_node('''
1069 ... def my_func(arg):
1070 ... return arg + 1
1071 ... ''')
1072 >>> node
1073 <FunctionDef.my_func l.2 at 0x...>
1074 """
1075
1076 _astroid_fields = (
1077 "decorators",
1078 "args",
1079 "returns",
1080 "type_params",
1081 "doc_node",
1082 "body",
1083 )
1084 _multi_line_block_fields = ("body",)
1085 returns = None
1086
1087 decorators: node_classes.Decorators | None
1088 """The decorators that are applied to this method or function."""
1089
1090 doc_node: Const | None
1091 """The doc node associated with this node."""
1092
1093 args: Arguments
1094 """The arguments that the function takes."""
1095
1096 is_function: ClassVar[bool] = True
1097 """Whether this node indicates a function.
1098
1099 For a :class:`FunctionDef` this is always ``True``.
1100 """
1101 type_annotation: NodeNG | None = None
1102 """If present, this will contain the type annotation passed by a type comment"""
1103 type_comment_args = None
1104 """
1105 If present, this will contain the type annotation for arguments
1106 passed by a type comment
1107 """
1108 type_comment_returns = None
1109 """If present, this will contain the return type annotation, passed by a type comment"""
1110 # attributes below are set by the builder module or by raw factories
1111 _other_fields = ("name", "position")
1112 _other_other_fields = (
1113 "locals",
1114 "_type",
1115 "type_comment_returns",
1116 "type_comment_args",
1117 )
1118 _type = None
1119
1120 name = "<functiondef>"
1121
1122 special_attributes = FunctionModel()
1123 """The names of special attributes that this function has."""
1124
1125 def __init__(
1126 self,
1127 name: str,
1128 lineno: int,
1129 col_offset: int,
1130 parent: NodeNG,
1131 *,
1132 end_lineno: int | None,
1133 end_col_offset: int | None,
1134 ) -> None:
1135 self.name = name
1136 """The name of the function."""
1137
1138 self.locals = {}
1139 """A map of the name of a local variable to the node defining it."""
1140
1141 self.body: list[NodeNG] = []
1142 """The contents of the function body."""
1143
1144 self.type_params: list[nodes.TypeVar | nodes.ParamSpec | nodes.TypeVarTuple] = (
1145 []
1146 )
1147 """The type parameters introduced by :pep:`695`, new in Python 3.12.
1148
1149 For example, the ``T`` in ``def func[T]() -> T: ...``.
1150 """
1151
1152 self.instance_attrs: dict[str, list[InferenceResult]] = {}
1153
1154 super().__init__(
1155 lineno=lineno,
1156 col_offset=col_offset,
1157 end_lineno=end_lineno,
1158 end_col_offset=end_col_offset,
1159 parent=parent,
1160 )
1161
1162 def postinit(
1163 self,
1164 args: Arguments,
1165 body: list[NodeNG],
1166 decorators: node_classes.Decorators | None = None,
1167 returns=None,
1168 type_comment_returns=None,
1169 type_comment_args=None,
1170 *,
1171 position: Position | None = None,
1172 doc_node: Const | None = None,
1173 type_params: (
1174 list[nodes.TypeVar | nodes.ParamSpec | nodes.TypeVarTuple] | None
1175 ) = None,
1176 ):
1177 """Do some setup after initialisation.
1178
1179 :param args: The arguments that the function takes.
1180
1181 :param body: The contents of the function body.
1182
1183 :param decorators: The decorators that are applied to this
1184 method or function.
1185 :params type_comment_returns:
1186 The return type annotation passed via a type comment.
1187 :params type_comment_args:
1188 The args type annotation passed via a type comment.
1189 :params position:
1190 Position of function keyword(s) and name.
1191 :param doc_node:
1192 The doc node associated with this node.
1193 :param type_params:
1194 The type_params associated with this node.
1195 """
1196 self.args = args
1197 self.body = body
1198 self.decorators = decorators
1199 self.returns = returns
1200 self.type_comment_returns = type_comment_returns
1201 self.type_comment_args = type_comment_args
1202 self.position = position
1203 self.doc_node = doc_node
1204 self.type_params = type_params or []
1205
1206 @cached_property
1207 def extra_decorators(self) -> list[node_classes.Call]:
1208 """The extra decorators that this function can have.
1209
1210 Additional decorators are considered when they are used as
1211 assignments, as in ``method = staticmethod(method)``.
1212 The property will return all the callables that are used for
1213 decoration.
1214 """
1215 if not (self.parent and isinstance(frame := self.parent.frame(), ClassDef)):
1216 return []
1217
1218 decorators: list[node_classes.Call] = []
1219 for assign in frame._assign_nodes_in_scope:
1220 if isinstance(assign.value, node_classes.Call) and isinstance(
1221 assign.value.func, node_classes.Name
1222 ):
1223 for assign_node in assign.targets:
1224 if not isinstance(assign_node, node_classes.AssignName):
1225 # Support only `name = callable(name)`
1226 continue
1227
1228 if assign_node.name != self.name:
1229 # Interested only in the assignment nodes that
1230 # decorates the current method.
1231 continue
1232 try:
1233 meth = frame[self.name]
1234 except KeyError:
1235 continue
1236 else:
1237 # Must be a function and in the same frame as the
1238 # original method.
1239 if (
1240 isinstance(meth, FunctionDef)
1241 and assign_node.frame() == frame
1242 ):
1243 decorators.append(assign.value)
1244 return decorators
1245
1246 def pytype(self) -> Literal["builtins.instancemethod", "builtins.function"]:
1247 """Get the name of the type that this node represents.
1248
1249 :returns: The name of the type.
1250 """
1251 if "method" in self.type:
1252 return "builtins.instancemethod"
1253 return "builtins.function"
1254
1255 def display_type(self) -> str:
1256 """A human readable type of this node.
1257
1258 :returns: The type of this node.
1259 """
1260 if "method" in self.type:
1261 return "Method"
1262 return "Function"
1263
1264 def callable(self) -> Literal[True]:
1265 return True
1266
1267 def argnames(self) -> list[str]:
1268 """Get the names of each of the arguments, including that
1269 of the collections of variable-length arguments ("args", "kwargs",
1270 etc.), as well as positional-only and keyword-only arguments.
1271
1272 :returns: The names of the arguments.
1273 """
1274 if self.args.arguments: # maybe None with builtin functions
1275 names = [elt.name for elt in self.args.arguments]
1276 else:
1277 names = []
1278
1279 return names
1280
1281 def getattr(
1282 self, name: str, context: InferenceContext | None = None
1283 ) -> list[InferenceResult]:
1284 if not name:
1285 raise AttributeInferenceError(target=self, attribute=name, context=context)
1286
1287 # Copy, so that adding the special attribute does not modify instance_attrs
1288 found_attrs = list(self.instance_attrs.get(name, []))
1289 if name in self.special_attributes:
1290 found_attrs.append(self.special_attributes.lookup(name))
1291 if found_attrs:
1292 return found_attrs
1293 raise AttributeInferenceError(target=self, attribute=name)
1294
1295 @cached_property
1296 def type(self) -> str: # pylint: disable=too-many-return-statements # noqa: C901
1297 """The function type for this node.
1298
1299 Possible values are: method, function, staticmethod, classmethod.
1300 """
1301 for decorator in self.extra_decorators:
1302 if decorator.func.name in BUILTIN_DESCRIPTORS:
1303 return decorator.func.name
1304
1305 if not self.parent:
1306 raise ParentMissingError(target=self)
1307
1308 frame = self.parent.frame()
1309 type_name = "function"
1310 if isinstance(frame, ClassDef):
1311 if self.name == "__new__":
1312 return "classmethod"
1313 if self.name == "__init_subclass__":
1314 return "classmethod"
1315 if self.name == "__class_getitem__":
1316 return "classmethod"
1317
1318 type_name = "method"
1319
1320 if not self.decorators:
1321 return type_name
1322
1323 for node in self.decorators.nodes:
1324 if isinstance(node, node_classes.Name):
1325 if node.name in BUILTIN_DESCRIPTORS:
1326 return node.name
1327 if (
1328 isinstance(node, node_classes.Attribute)
1329 and isinstance(node.expr, node_classes.Name)
1330 and node.expr.name == "builtins"
1331 and node.attrname in BUILTIN_DESCRIPTORS
1332 ):
1333 return node.attrname
1334
1335 if isinstance(node, node_classes.Call):
1336 # Handle the following case:
1337 # @some_decorator(arg1, arg2)
1338 # def func(...)
1339 #
1340 try:
1341 current = next(node.func.infer())
1342 except (InferenceError, StopIteration):
1343 continue
1344 _type = _infer_decorator_callchain(current)
1345 if _type is not None:
1346 return _type
1347
1348 try:
1349 for inferred in node.infer():
1350 # Check to see if this returns a static or a class method.
1351 _type = _infer_decorator_callchain(inferred)
1352 if _type is not None:
1353 return _type
1354
1355 if not isinstance(inferred, ClassDef):
1356 continue
1357 for ancestor in inferred.ancestors():
1358 if not isinstance(ancestor, ClassDef):
1359 continue
1360 if ancestor.is_subtype_of("builtins.classmethod"):
1361 return "classmethod"
1362 if ancestor.is_subtype_of("builtins.staticmethod"):
1363 return "staticmethod"
1364 except InferenceError:
1365 pass
1366 return type_name
1367
1368 @cached_property
1369 def fromlineno(self) -> int:
1370 """The first line that this node appears on in the source code.
1371
1372 Can also return 0 if the line can not be determined.
1373 """
1374 # lineno is the line number of the first decorator, we want the def
1375 # statement lineno. Similar to 'ClassDef.fromlineno'
1376 lineno = self.lineno or 0
1377 if self.decorators is not None:
1378 lineno += sum(
1379 node.tolineno - (node.lineno or 0) + 1 for node in self.decorators.nodes
1380 )
1381
1382 return lineno or 0
1383
1384 @cached_property
1385 def blockstart_tolineno(self) -> int:
1386 """The line on which the beginning of this block ends."""
1387 if self.returns:
1388 return self.returns.tolineno
1389 return self.args.tolineno
1390
1391 def implicit_parameters(self) -> Literal[0, 1]:
1392 return 1 if self.is_bound() else 0
1393
1394 def block_range(self, lineno: int) -> tuple[int, int]:
1395 """Get a range from the given line number to where this node ends.
1396
1397 :param lineno: Unused.
1398
1399 :returns: The range of line numbers that this node belongs to,
1400 """
1401 return self.fromlineno, self.tolineno
1402
1403 def igetattr(
1404 self, name: str, context: InferenceContext | None = None
1405 ) -> Iterator[InferenceResult]:
1406 """Inferred getattr, which returns an iterator of inferred statements."""
1407 try:
1408 return bases._infer_stmts(self.getattr(name, context), context, frame=self)
1409 except AttributeInferenceError as error:
1410 raise InferenceError(
1411 str(error), target=self, attribute=name, context=context
1412 ) from error
1413
1414 def is_method(self) -> bool:
1415 """Check if this function node represents a method.
1416
1417 :returns: Whether this is a method.
1418 """
1419 # check we are defined in a ClassDef, because this is usually expected
1420 # (e.g. pylint...) when is_method() return True
1421 return (
1422 self.type != "function"
1423 and self.parent is not None
1424 and isinstance(self.parent.frame(), ClassDef)
1425 )
1426
1427 def decoratornames(self, context: InferenceContext | None = None) -> set[str]:
1428 """Get the qualified names of each of the decorators on this function.
1429
1430 :param context:
1431 An inference context that can be passed to inference functions
1432 :returns: The names of the decorators.
1433 """
1434 result = set()
1435 decoratornodes = []
1436 if self.decorators is not None:
1437 decoratornodes += self.decorators.nodes
1438 decoratornodes += self.extra_decorators
1439 for decnode in decoratornodes:
1440 try:
1441 for infnode in decnode.infer(context=context):
1442 result.add(infnode.qname())
1443 except InferenceError:
1444 continue
1445 return result
1446
1447 def is_bound(self) -> bool:
1448 """Check if the function is bound to an instance or class.
1449
1450 :returns: Whether the function is bound to an instance or class.
1451 """
1452 return self.type in {"method", "classmethod"}
1453
1454 def is_abstract(self, pass_is_abstract=True, any_raise_is_abstract=False) -> bool:
1455 """Check if the method is abstract.
1456
1457 A method is considered abstract if any of the following is true:
1458 * The only statement is 'raise NotImplementedError'
1459 * The only statement is 'raise <SomeException>' and any_raise_is_abstract is True
1460 * The only statement is 'pass' and pass_is_abstract is True
1461 * The method is annotated with abc.astractproperty/abc.abstractmethod
1462
1463 :returns: Whether the method is abstract.
1464 """
1465 if self.decorators:
1466 for node in self.decorators.nodes:
1467 try:
1468 inferred = next(node.infer())
1469 except (InferenceError, StopIteration):
1470 continue
1471 if inferred and inferred.qname() in {
1472 "abc.abstractproperty",
1473 "abc.abstractmethod",
1474 }:
1475 return True
1476
1477 for child_node in self.body:
1478 if isinstance(child_node, node_classes.Raise):
1479 if any_raise_is_abstract:
1480 return True
1481 if child_node.raises_not_implemented():
1482 return True
1483 return pass_is_abstract and isinstance(child_node, node_classes.Pass)
1484 # empty function is the same as function with a single "pass" statement
1485 if pass_is_abstract:
1486 return True
1487
1488 return False
1489
1490 def is_generator(self) -> bool:
1491 """Check if this is a generator function.
1492
1493 :returns: Whether this is a generator function.
1494 """
1495 yields_without_lambdas = set(self._get_yield_nodes_skip_lambdas())
1496 yields_without_functions = set(self._get_yield_nodes_skip_functions())
1497 # Want an intersecting member that is neither in a lambda nor a function
1498 return bool(yields_without_lambdas & yields_without_functions)
1499
1500 def _infer(
1501 self, context: InferenceContext | None = None
1502 ) -> Generator[objects.Property | FunctionDef, None, InferenceErrorInfo]:
1503 from astroid import objects # pylint: disable=import-outside-toplevel
1504
1505 if not (self.decorators and bases._is_property(self)):
1506 yield self
1507 return InferenceErrorInfo(node=self, context=context)
1508
1509 if not self.parent:
1510 raise ParentMissingError(target=self)
1511 prop_func = objects.Property(
1512 function=self,
1513 name=self.name,
1514 lineno=self.lineno,
1515 parent=self.parent,
1516 col_offset=self.col_offset,
1517 )
1518 prop_func.postinit(body=[], args=self.args, doc_node=self.doc_node)
1519 yield prop_func
1520 return InferenceErrorInfo(node=self, context=context)
1521
1522 def infer_yield_result(
1523 self, context: InferenceContext | None = None
1524 ) -> Iterator[InferenceResult]:
1525 """Infer what the function yields when called
1526
1527 :returns: What the function yields
1528 """
1529 for yield_ in self.nodes_of_class(node_classes.Yield):
1530 if yield_.value is None:
1531 yield node_classes.Const(None, parent=yield_, lineno=yield_.lineno)
1532 elif yield_.scope() == self:
1533 yield from yield_.value.infer(context=context)
1534
1535 @staticmethod
1536 def _is_stub_placeholder_body(body: list[NodeNG]) -> bool:
1537 """Check if a function body is empty, ``...``, or ``pass``."""
1538 if not body:
1539 return True
1540 if len(body) != 1:
1541 return False
1542 statement = body[0]
1543 return isinstance(statement, node_classes.Pass) or (
1544 isinstance(statement, node_classes.Expr)
1545 and isinstance(statement.value, node_classes.Const)
1546 and statement.value.value is ...
1547 )
1548
1549 def infer_call_result(
1550 self,
1551 caller: SuccessfulInferenceResult | None,
1552 context: InferenceContext | None = None,
1553 ) -> Iterator[InferenceResult]:
1554 """Infer what the function returns when called."""
1555 if context is None:
1556 context = InferenceContext()
1557 if self.is_generator():
1558 if isinstance(self, AsyncFunctionDef):
1559 generator_cls: type[bases.Generator] = bases.AsyncGenerator
1560 else:
1561 generator_cls = bases.Generator
1562 result = generator_cls(self, generator_initial_context=context)
1563 yield result
1564 return
1565 # This is really a gigantic hack to work around metaclass generators
1566 # that return transient class-generating functions. Pylint's AST structure
1567 # cannot handle a base class object that is only used for calling __new__,
1568 # but does not contribute to the inheritance structure itself. We inject
1569 # a fake class into the hierarchy here for several well-known metaclass
1570 # generators, and filter it out later.
1571 if (
1572 self.name == "with_metaclass"
1573 and caller is not None
1574 and self.args.args
1575 and len(self.args.args) == 1
1576 and self.args.vararg is not None
1577 ):
1578 if isinstance(caller.args, node_classes.Arguments):
1579 assert caller.args.args is not None
1580 call_args = caller.args.args
1581 elif isinstance(caller.args, list):
1582 call_args = caller.args
1583 else:
1584 raise TypeError( # pragma: no cover
1585 f"caller.args was neither Arguments nor list; got {type(caller.args)}"
1586 )
1587 if not call_args:
1588 # ``with_metaclass()`` called without a metaclass argument is
1589 # invalid; there is nothing to infer.
1590 raise InferenceError(
1591 "with_metaclass() call has no metaclass argument",
1592 node=self,
1593 context=context,
1594 )
1595 metaclass = next(call_args[0].infer(context), None)
1596 if isinstance(metaclass, ClassDef):
1597 class_bases = [_infer_last(x, context) for x in call_args[1:]]
1598 new_class = ClassDef(
1599 name="temporary_class",
1600 lineno=0,
1601 col_offset=0,
1602 end_lineno=0,
1603 end_col_offset=0,
1604 parent=SYNTHETIC_ROOT,
1605 )
1606 new_class.hide = True
1607 new_class.postinit(
1608 bases=[
1609 base
1610 for base in class_bases
1611 if not isinstance(base, util.UninferableBase)
1612 ],
1613 body=[],
1614 decorators=None,
1615 metaclass=metaclass,
1616 )
1617 yield new_class
1618 return
1619 returns = self._get_return_nodes_skip_functions()
1620
1621 first_return = next(returns, None)
1622 if not first_return:
1623 if protocols._is_stub_node(self) and self._is_stub_placeholder_body(
1624 self.body
1625 ):
1626 if self.returns is not None:
1627 yield from protocols.infer_instance_from_annotation(
1628 self.returns, ctx=context
1629 )
1630 else:
1631 yield util.Uninferable
1632 return
1633
1634 if self.body:
1635 # A body that is only ``...`` is a placeholder, like ``pass``:
1636 # it does not mean the function returns ``None``.
1637 if self._is_stub_placeholder_body(self.body) or self.is_abstract(
1638 pass_is_abstract=True, any_raise_is_abstract=True
1639 ):
1640 yield util.Uninferable
1641 else:
1642 yield node_classes.Const(None)
1643 return
1644
1645 # Builtin dunder methods have empty bodies, return Uninferable.
1646 if (
1647 len(self.body) == 0
1648 and self.name.startswith("__")
1649 and self.name.endswith("__")
1650 and self.root().qname() == "builtins"
1651 ):
1652 yield util.Uninferable
1653 return
1654
1655 raise InferenceError("The function does not have any return statements")
1656
1657 for returnnode in itertools.chain((first_return,), returns):
1658 if returnnode.value is None:
1659 yield node_classes.Const(None)
1660 else:
1661 try:
1662 yield from returnnode.value.infer(context)
1663 except InferenceError:
1664 yield util.Uninferable
1665
1666 def bool_value(self, context: InferenceContext | None = None) -> bool:
1667 """Determine the boolean value of this node.
1668
1669 :returns: The boolean value of this node.
1670 For a :class:`FunctionDef` this is always ``True``.
1671 """
1672 return True
1673
1674 def get_children(self):
1675 if self.decorators is not None:
1676 yield self.decorators
1677
1678 yield self.args
1679
1680 if self.returns is not None:
1681 yield self.returns
1682 yield from self.type_params
1683
1684 yield from self.body
1685
1686 def scope_lookup(
1687 self, node: LookupMixIn, name: str, offset: int = 0
1688 ) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
1689 """Lookup where the given name is assigned."""
1690 if name == "__class__":
1691 # __class__ is an implicit closure reference created by the compiler
1692 # if any methods in a class body refer to either __class__ or super.
1693 # In our case, we want to be able to look it up in the current scope
1694 # when `__class__` is being used.
1695 if self.parent and isinstance(frame := self.parent.frame(), ClassDef):
1696 return self, [frame]
1697
1698 if (self.args.defaults and node in self.args.defaults) or (
1699 self.args.kw_defaults and node in self.args.kw_defaults
1700 ):
1701 if not self.parent:
1702 raise ParentMissingError(target=self)
1703 frame = self.parent.frame()
1704 # line offset to avoid that def func(f=func) resolve the default
1705 # value to the defined function
1706 offset = -1
1707 else:
1708 # check this is not used in function decorators
1709 frame = self
1710 return frame._scope_lookup(node, name, offset)
1711
1712 def frame(self, *, future: Literal[None, True] = None) -> Self:
1713 """The node's frame node.
1714
1715 A frame node is a :class:`Module`, :class:`FunctionDef`,
1716 :class:`ClassDef` or :class:`Lambda`.
1717
1718 :returns: The node itself.
1719 """
1720 return self
1721
1722
1723class AsyncFunctionDef(FunctionDef):
1724 """Class representing an :class:`ast.FunctionDef` node.
1725
1726 A :class:`AsyncFunctionDef` is an asynchronous function
1727 created with the `async` keyword.
1728
1729 >>> import astroid
1730 >>> node = astroid.extract_node('''
1731 ... async def func(things):
1732 ... async for thing in things:
1733 ... print(thing)
1734 ... ''')
1735 >>> node
1736 <AsyncFunctionDef.func l.2 at 0x...>
1737 >>> node.body[0]
1738 <AsyncFor l.3 at 0x...>
1739 """
1740
1741
1742def _is_metaclass(
1743 klass: ClassDef,
1744 seen: set[str] | None = None,
1745 context: InferenceContext | None = None,
1746) -> bool:
1747 """Return if the given class can be
1748 used as a metaclass.
1749 """
1750 if klass.name == "type":
1751 return True
1752 if seen is None:
1753 seen = set()
1754 for base in klass.bases:
1755 try:
1756 for baseobj in base.infer(context=context):
1757 baseobj_name = baseobj.qname()
1758 if baseobj_name in seen:
1759 continue
1760
1761 seen.add(baseobj_name)
1762 if isinstance(baseobj, bases.Instance):
1763 # not abstract
1764 return False
1765 if baseobj is klass:
1766 continue
1767 if not isinstance(baseobj, ClassDef):
1768 continue
1769 if baseobj._type == "metaclass":
1770 return True
1771 if _is_metaclass(baseobj, seen, context=context):
1772 return True
1773 except InferenceError:
1774 continue
1775 return False
1776
1777
1778def _class_type(
1779 klass: ClassDef,
1780 ancestors: set[str] | None = None,
1781 context: InferenceContext | None = None,
1782) -> Literal["class", "exception", "metaclass"]:
1783 """return a ClassDef node type to differ metaclass and exception
1784 from 'regular' classes
1785 """
1786 # XXX we have to store ancestors in case we have an ancestor loop
1787 if klass._type is not None:
1788 return klass._type
1789 if _is_metaclass(klass, context=context):
1790 klass._type = "metaclass"
1791 elif klass.name.endswith("Exception"):
1792 klass._type = "exception"
1793 else:
1794 if ancestors is None:
1795 ancestors = set()
1796 klass_name = klass.qname()
1797 if klass_name in ancestors:
1798 # XXX we are in loop ancestors, and have found no type
1799 klass._type = "class"
1800 return "class"
1801 ancestors.add(klass_name)
1802 for base in klass.ancestors(recurs=False):
1803 name = _class_type(base, ancestors)
1804 if name != "class":
1805 if name == "metaclass" and klass._type != "metaclass":
1806 # don't propagate it if the current class
1807 # can't be a metaclass
1808 continue
1809 klass._type = base.type
1810 break
1811 if klass._type is None:
1812 klass._type = "class"
1813 return klass._type
1814
1815
1816def get_wrapping_class(node: NodeNG) -> ClassDef | None:
1817 """Get the class that wraps the given node.
1818
1819 We consider that a class wraps a node if the class
1820 is a parent for the said node.
1821
1822 :returns: The class that wraps the given node
1823 """
1824
1825 klass = node.frame()
1826 while klass is not None and not isinstance(klass, ClassDef):
1827 if klass.parent is None:
1828 klass = None
1829 else:
1830 klass = klass.parent.frame()
1831 return klass
1832
1833
1834class ClassDef(
1835 _base_nodes.FilterStmtsBaseNode, LocalsDictNodeNG, _base_nodes.Statement
1836):
1837 """Class representing an :class:`ast.ClassDef` node.
1838
1839 >>> import astroid
1840 >>> node = astroid.extract_node('''
1841 ... class Thing:
1842 ... def my_meth(self, arg):
1843 ... return arg + self.offset
1844 ... ''')
1845 >>> node
1846 <ClassDef.Thing l.2 at 0x...>
1847 """
1848
1849 # some of the attributes below are set by the builder module or
1850 # by a raw factories
1851
1852 # a dictionary of class instances attributes
1853 _astroid_fields = (
1854 "decorators",
1855 "bases",
1856 "keywords",
1857 "doc_node",
1858 "body",
1859 "type_params",
1860 ) # name
1861
1862 decorators: node_classes.Decorators | None = None
1863 """The decorators that are applied to this class."""
1864 special_attributes: ClassModel = ClassModel()
1865 """The names of special attributes that this class has."""
1866
1867 _type: Literal["class", "exception", "metaclass"] | None = None
1868 _metaclass: NodeNG | None = None
1869 _metaclass_hack = False
1870 hide = False
1871 type = property(
1872 _class_type,
1873 doc=(
1874 "The class type for this node.\n\n"
1875 "Possible values are: class, metaclass, exception."
1876 ),
1877 )
1878 _other_fields = ("name", "is_dataclass", "position")
1879 _other_other_fields = ("locals",)
1880
1881 def __init__(
1882 self,
1883 name: str,
1884 lineno: int,
1885 col_offset: int,
1886 parent: NodeNG,
1887 *,
1888 end_lineno: int | None,
1889 end_col_offset: int | None,
1890 ) -> None:
1891 self.instance_attrs: dict[str, list[InferenceResult]] = {}
1892 self.locals = {}
1893 """A map of the name of a local variable to the node defining it."""
1894
1895 self.keywords: list[node_classes.Keyword] = []
1896 """The keywords given to the class definition.
1897
1898 This is usually for :pep:`3115` style metaclass declaration.
1899 """
1900
1901 self.bases: list[SuccessfulInferenceResult] = []
1902 """What the class inherits from."""
1903
1904 self.body: list[NodeNG] = []
1905 """The contents of the class body."""
1906
1907 self.name = name
1908 """The name of the class."""
1909
1910 self.decorators = None
1911 """The decorators that are applied to this class."""
1912
1913 self.doc_node: Const | None = None
1914 """The doc node associated with this node."""
1915
1916 self.is_dataclass: bool = False
1917 """Whether this class is a dataclass."""
1918
1919 self.type_params: list[nodes.TypeVar | nodes.ParamSpec | nodes.TypeVarTuple] = (
1920 []
1921 )
1922 """The type parameters introduced by :pep:`695`, new in Python 3.12.
1923
1924 For example, the ``T`` in ``class MyClass[T]: ...``.
1925 """
1926
1927 super().__init__(
1928 lineno=lineno,
1929 col_offset=col_offset,
1930 end_lineno=end_lineno,
1931 end_col_offset=end_col_offset,
1932 parent=parent,
1933 )
1934 for local_name, node in self.implicit_locals():
1935 self.add_local_node(node, local_name)
1936
1937 infer_binary_op: ClassVar[InferBinaryOp[ClassDef]] = (
1938 protocols.instance_class_infer_binary_op
1939 )
1940
1941 def implicit_parameters(self) -> Literal[1]:
1942 return 1
1943
1944 def implicit_locals(self) -> tuple[tuple[str, NodeNG], ...]:
1945 """Get implicitly defined class definition locals.
1946
1947 :returns: the the name and Const pair for each local
1948 """
1949 locals_ = (("__module__", self.special_attributes.attr___module__),)
1950 # __qualname__ is defined in PEP3155
1951 locals_ += (
1952 ("__qualname__", self.special_attributes.attr___qualname__),
1953 ("__annotations__", self.special_attributes.attr___annotations__),
1954 )
1955 return locals_
1956
1957 # pylint: disable=redefined-outer-name
1958 def postinit(
1959 self,
1960 bases: list[SuccessfulInferenceResult],
1961 body: list[NodeNG],
1962 decorators: node_classes.Decorators | None,
1963 newstyle: bool | None = None,
1964 metaclass: NodeNG | None = None,
1965 keywords: list[node_classes.Keyword] | None = None,
1966 *,
1967 position: Position | None = None,
1968 doc_node: Const | None = None,
1969 type_params: (
1970 list[nodes.TypeVar | nodes.ParamSpec | nodes.TypeVarTuple] | None
1971 ) = None,
1972 ) -> None:
1973 if keywords is not None:
1974 self.keywords = keywords
1975 self.bases = bases
1976 self.body = body
1977 self.decorators = decorators
1978 self._metaclass = metaclass
1979 self.position = position
1980 self.doc_node = doc_node
1981 self.type_params = type_params or []
1982
1983 @cached_property
1984 def blockstart_tolineno(self) -> int:
1985 """The line on which the beginning of this block ends."""
1986 if self.bases:
1987 return self.bases[-1].tolineno
1988
1989 return self.fromlineno
1990
1991 def block_range(self, lineno: int) -> tuple[int, int]:
1992 """Get a range from the given line number to where this node ends.
1993
1994 :param lineno: Unused.
1995
1996 :returns: The range of line numbers that this node belongs to,
1997 """
1998 return self.fromlineno, self.tolineno
1999
2000 def pytype(self) -> Literal["builtins.type"]:
2001 """Get the name of the type that this node represents.
2002
2003 :returns: The name of the type.
2004 """
2005 return "builtins.type"
2006
2007 def display_type(self) -> str:
2008 """A human readable type of this node.
2009
2010 :returns: The type of this node.
2011 """
2012 return "Class"
2013
2014 def callable(self) -> bool:
2015 """Whether this node defines something that is callable.
2016
2017 :returns: Whether this defines something that is callable.
2018 For a :class:`ClassDef` this is always ``True``.
2019 """
2020 return True
2021
2022 def is_subtype_of(
2023 self, type_name: str, context: InferenceContext | None = None
2024 ) -> bool:
2025 """Whether this class is a subtype of the given type.
2026
2027 :param type_name: The name of the type of check against.
2028
2029 :returns: Whether this class is a subtype of the given type.
2030 """
2031 if self.qname() == type_name:
2032 return True
2033
2034 return any(
2035 ancestor.qname() == type_name
2036 for ancestor in self.ancestors(context=context)
2037 )
2038
2039 def _infer_type_call(self, caller, context):
2040 try:
2041 name_node = next(caller.args[0].infer(context))
2042 except StopIteration as e:
2043 raise InferenceError(node=caller.args[0], context=context) from e
2044 if isinstance(name_node, node_classes.Const) and isinstance(
2045 name_node.value, str
2046 ):
2047 name = name_node.value
2048 else:
2049 return util.Uninferable
2050
2051 result = ClassDef(
2052 name,
2053 lineno=0,
2054 col_offset=0,
2055 end_lineno=0,
2056 end_col_offset=0,
2057 parent=caller.parent,
2058 )
2059
2060 # Get the bases of the class.
2061 try:
2062 class_bases = next(caller.args[1].infer(context))
2063 except StopIteration as e:
2064 raise InferenceError(node=caller.args[1], context=context) from e
2065 if isinstance(class_bases, (node_classes.Tuple, node_classes.List)):
2066 bases = []
2067 for base in class_bases.itered():
2068 inferred = next(base.infer(context=context), None)
2069 if inferred:
2070 bases.append(
2071 node_classes.EvaluatedObject(original=base, value=inferred)
2072 )
2073 result.bases = bases
2074 else:
2075 # There is currently no AST node that can represent an 'unknown'
2076 # node (Uninferable is not an AST node), therefore we simply return Uninferable here
2077 # although we know at least the name of the class.
2078 return util.Uninferable
2079
2080 # Get the members of the class
2081 try:
2082 members = next(caller.args[2].infer(context))
2083 except (InferenceError, StopIteration):
2084 members = None
2085
2086 if members and isinstance(members, node_classes.Dict):
2087 for attr, value in members.items:
2088 if isinstance(attr, node_classes.Const) and isinstance(attr.value, str):
2089 result.locals[attr.value] = [value]
2090
2091 return result
2092
2093 def infer_call_result(
2094 self,
2095 caller: SuccessfulInferenceResult | None,
2096 context: InferenceContext | None = None,
2097 ) -> Iterator[InferenceResult]:
2098 """infer what a class is returning when called"""
2099 if (
2100 caller is not None
2101 and self.is_subtype_of("builtins.type", context)
2102 and len(caller.args) == 3
2103 ):
2104 result = self._infer_type_call(caller, context)
2105 yield result
2106 return
2107
2108 dunder_call = None
2109 try:
2110 metaclass = self.metaclass(context=context)
2111 if metaclass is not None:
2112 # Only get __call__ if it's defined locally for the metaclass.
2113 # Otherwise we will find ObjectModel.__call__ which will
2114 # return an instance of the metaclass. Instantiating the class is
2115 # handled later.
2116 if "__call__" in metaclass.locals:
2117 dunder_call = next(metaclass.igetattr("__call__", context))
2118 except (AttributeInferenceError, StopIteration):
2119 pass
2120
2121 if dunder_call and dunder_call.qname() != "builtins.type.__call__":
2122 # Call type.__call__ if not set metaclass
2123 # (since type is the default metaclass)
2124 context = bind_context_to_node(context, self)
2125 # ``infer_call_result`` may be called through the public API without
2126 # a call context (it defaults to None); only annotate the callee
2127 # when there is a call context to annotate.
2128 if context.callcontext:
2129 context.callcontext.callee = dunder_call
2130 yield from dunder_call.infer_call_result(caller, context)
2131 else:
2132 yield self.instantiate_class()
2133
2134 def scope_lookup(
2135 self, node: LookupMixIn, name: str, offset: int = 0
2136 ) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
2137 """Lookup where the given name is assigned.
2138
2139 :param node: The node to look for assignments up to.
2140 Any assignments after the given node are ignored.
2141
2142 :param name: The name to find assignments for.
2143
2144 :param offset: The line offset to filter statements up to.
2145
2146 :returns: This scope node and the list of assignments associated to the
2147 given name according to the scope where it has been found (locals,
2148 globals or builtin).
2149 """
2150 # If the name looks like a builtin name, just try to look
2151 # into the upper scope of this class. We might have a
2152 # decorator that it's poorly named after a builtin object
2153 # inside this class.
2154 lookup_upper_frame = (
2155 isinstance(node.parent, node_classes.Decorators)
2156 and name in AstroidManager().builtins_module
2157 )
2158 if (
2159 any(
2160 node == base or (base.parent_of(node) and not self.type_params)
2161 for base in self.bases
2162 )
2163 or lookup_upper_frame
2164 ):
2165 # Handle the case where we have either a name
2166 # in the bases of a class, which exists before
2167 # the actual definition or the case where we have
2168 # a Getattr node, with that name.
2169 #
2170 # name = ...
2171 # class A(name):
2172 # def name(self): ...
2173 #
2174 # import name
2175 # class A(name.Name):
2176 # def name(self): ...
2177 if not self.parent:
2178 raise ParentMissingError(target=self)
2179 frame = self.parent.frame()
2180 # line offset to avoid that class A(A) resolve the ancestor to
2181 # the defined class
2182 offset = -1
2183 else:
2184 frame = self
2185 return frame._scope_lookup(node, name, offset)
2186
2187 @property
2188 def basenames(self) -> list[str]:
2189 """The names of the parent classes
2190
2191 Names are given in the order they appear in the class definition.
2192 """
2193 return [bnode.as_string() for bnode in self.bases]
2194
2195 def ancestors(
2196 self, recurs: bool = True, context: InferenceContext | None = None
2197 ) -> Generator[ClassDef]:
2198 """Iterate over the base classes in prefixed depth first order.
2199
2200 :param recurs: Whether to recurse or return direct ancestors only.
2201
2202 :returns: The base classes
2203 """
2204 # FIXME: should be possible to choose the resolution order
2205 # FIXME: inference make infinite loops possible here
2206 yielded = {self}
2207 if context is None:
2208 context = InferenceContext()
2209 if not self.bases and self.qname() != "builtins.object":
2210 # This should always be a ClassDef (which we don't assert for)
2211 yield builtin_lookup("object")[1][0] # type: ignore[misc]
2212 return
2213
2214 for stmt in self.bases:
2215 with context.restore_path():
2216 try:
2217 for baseobj in stmt.infer(context):
2218 if not isinstance(baseobj, ClassDef):
2219 if isinstance(baseobj, bases.Instance):
2220 baseobj = baseobj._proxied
2221 else:
2222 continue
2223 if not baseobj.hide:
2224 if baseobj in yielded:
2225 continue
2226 yielded.add(baseobj)
2227 yield baseobj
2228 if not recurs:
2229 continue
2230 for grandpa in baseobj.ancestors(recurs=True, context=context):
2231 if grandpa is self:
2232 # This class is the ancestor of itself.
2233 break
2234 if grandpa in yielded:
2235 continue
2236 yielded.add(grandpa)
2237 yield grandpa
2238 except InferenceError:
2239 continue
2240
2241 def local_attr_ancestors(
2242 self, name: str, context: InferenceContext | None = None
2243 ) -> Generator[ClassDef]:
2244 """Iterate over the parents that define the given name.
2245
2246 :param name: The name to find definitions for.
2247
2248 :returns: The parents that define the given name.
2249 """
2250 # Look up in the mro if we can. This will result in the
2251 # attribute being looked up just as Python does it.
2252 try:
2253 ancestors: Iterable[ClassDef] = self.mro(context)[1:]
2254 except MroError:
2255 # Fallback to use ancestors, we can't determine
2256 # a sane MRO.
2257 ancestors = self.ancestors(context=context)
2258 for astroid in ancestors:
2259 if name in astroid:
2260 yield astroid
2261
2262 def instance_attr_ancestors(
2263 self, name: str, context: InferenceContext | None = None
2264 ) -> Generator[ClassDef]:
2265 """Iterate over the parents that define the given name as an attribute.
2266
2267 :param name: The name to find definitions for.
2268
2269 :returns: The parents that define the given name as
2270 an instance attribute.
2271 """
2272 for astroid in self.ancestors(context=context):
2273 if name in astroid.instance_attrs:
2274 yield astroid
2275
2276 def has_base(self, node: NodeNG) -> bool:
2277 """Whether this class directly inherits from the given node.
2278
2279 :param node: The node to check for.
2280
2281 :returns: Whether this class directly inherits from the given node.
2282 """
2283 return node in self.bases
2284
2285 def local_attr(
2286 self, name: str, context: InferenceContext | None = None
2287 ) -> list[InferenceResult]:
2288 """Get the list of assign nodes associated to the given name.
2289
2290 Assignments are looked for in both this class and in parents.
2291
2292 :returns: The list of assignments to the given name.
2293
2294 :raises AttributeInferenceError: If no attribute with this name
2295 can be found in this class or parent classes.
2296 """
2297 result = []
2298 if name in self.locals:
2299 result = self.locals[name]
2300 else:
2301 class_node = next(self.local_attr_ancestors(name, context), None)
2302 if class_node:
2303 result = class_node.locals[name]
2304 result = [n for n in result if not isinstance(n, node_classes.DelAttr)]
2305 if result:
2306 return result
2307 raise AttributeInferenceError(target=self, attribute=name, context=context)
2308
2309 def instance_attr(
2310 self, name: str, context: InferenceContext | None = None
2311 ) -> list[InferenceResult]:
2312 """Get the list of nodes associated to the given attribute name.
2313
2314 Assignments are looked for in both this class and in parents.
2315
2316 :returns: The list of assignments to the given name.
2317
2318 :raises AttributeInferenceError: If no attribute with this name
2319 can be found in this class or parent classes.
2320 """
2321 # Return a copy, so we don't modify self.instance_attrs,
2322 # which could lead to infinite loop.
2323 values = list(self.instance_attrs.get(name, []))
2324 # get all values from parents
2325 for class_node in self.instance_attr_ancestors(name, context):
2326 values += class_node.instance_attrs[name]
2327 values = [n for n in values if not isinstance(n, node_classes.DelAttr)]
2328 if values:
2329 return values
2330 raise AttributeInferenceError(target=self, attribute=name, context=context)
2331
2332 def instantiate_class(self) -> bases.Instance:
2333 """Get an :class:`~astroid.Instance` of the :class:`ClassDef` node.
2334
2335 :returns: An :class:`~astroid.Instance` of the :class:`ClassDef` node
2336 """
2337 from astroid import objects # pylint: disable=import-outside-toplevel
2338
2339 try:
2340 if any(cls.name in EXCEPTION_BASE_CLASSES for cls in self.mro()):
2341 # Subclasses of exceptions can be exception instances
2342 return objects.ExceptionInstance(self)
2343 except MroError:
2344 pass
2345 return bases.Instance(self)
2346
2347 def getattr(
2348 self,
2349 name: str,
2350 context: InferenceContext | None = None,
2351 class_context: bool = True,
2352 ) -> list[InferenceResult]:
2353 """Get an attribute from this class, using Python's attribute semantic.
2354
2355 This method doesn't look in the ``instance_attrs`` dictionary
2356 since it is done by an :class:`~astroid.Instance` proxy at inference time.
2357 It may return an :obj:`~astroid.Uninferable` object if
2358 the attribute has not been
2359 found, but a ``__getattr__`` or ``__getattribute__`` method is defined.
2360 If ``class_context`` is given, then it is considered that the
2361 attribute is accessed from a class context,
2362 e.g. ClassDef.attribute, otherwise it might have been accessed
2363 from an instance as well. If ``class_context`` is used in that
2364 case, then a lookup in the implicit metaclass and the explicit
2365 metaclass will be done.
2366
2367 :param name: The attribute to look for.
2368
2369 :param class_context: Whether the attribute can be accessed statically.
2370
2371 :returns: The attribute.
2372
2373 :raises AttributeInferenceError: If the attribute cannot be inferred.
2374 """
2375 if not name:
2376 raise AttributeInferenceError(target=self, attribute=name, context=context)
2377
2378 # don't modify the list in self.locals!
2379 values: list[InferenceResult] = list(self.locals.get(name, []))
2380 for classnode in self.ancestors(recurs=True, context=context):
2381 values += classnode.locals.get(name, [])
2382
2383 if name in self.special_attributes and class_context and not values:
2384 special_attr = self.special_attributes.lookup(name)
2385 if not isinstance(special_attr, node_classes.Unknown):
2386 result = [special_attr]
2387 return result
2388
2389 if class_context:
2390 values += self._metaclass_lookup_attribute(name, context)
2391
2392 result: list[InferenceResult] = []
2393 for value in values:
2394 if isinstance(value, node_classes.AssignName):
2395 stmt = value.statement()
2396 if (
2397 isinstance(stmt, node_classes.AnnAssign)
2398 and stmt.value is None
2399 and not protocols._is_stub_node(stmt)
2400 ):
2401 continue
2402 result.append(value)
2403
2404 if not result:
2405 raise AttributeInferenceError(target=self, attribute=name, context=context)
2406
2407 return result
2408
2409 @lru_cache(maxsize=1024) # noqa
2410 def _metaclass_lookup_attribute(self, name, context):
2411 """Search the given name in the implicit and the explicit metaclass."""
2412 attrs = set()
2413 implicit_meta = self.implicit_metaclass()
2414 context = copy_context(context)
2415 metaclass = self.metaclass(context=context)
2416 for cls in (implicit_meta, metaclass):
2417 if cls and cls != self and isinstance(cls, ClassDef):
2418 cls_attributes = self._get_attribute_from_metaclass(cls, name, context)
2419 attrs.update(cls_attributes)
2420 return attrs
2421
2422 def _get_attribute_from_metaclass(self, cls, name, context):
2423 from astroid import objects # pylint: disable=import-outside-toplevel
2424
2425 try:
2426 attrs = cls.getattr(name, context=context, class_context=True)
2427 except AttributeInferenceError:
2428 return
2429
2430 for attr in bases._infer_stmts(attrs, context, frame=cls):
2431 if not isinstance(attr, FunctionDef):
2432 yield attr
2433 continue
2434
2435 if isinstance(attr, objects.Property):
2436 yield attr
2437 continue
2438 if attr.type == "classmethod":
2439 # If the method is a classmethod, then it will
2440 # be bound to the metaclass, not to the class
2441 # from where the attribute is retrieved.
2442 # get_wrapping_class could return None, so just
2443 # default to the current class.
2444 frame = get_wrapping_class(attr) or self
2445 yield bases.BoundMethod(attr, frame)
2446 elif attr.type == "staticmethod":
2447 yield attr
2448 else:
2449 yield bases.BoundMethod(attr, self)
2450
2451 def igetattr(
2452 self,
2453 name: str,
2454 context: InferenceContext | None = None,
2455 class_context: bool = True,
2456 ) -> Iterator[InferenceResult]:
2457 """Infer the possible values of the given variable.
2458
2459 :param name: The name of the variable to infer.
2460
2461 :returns: The inferred possible values.
2462 """
2463 from astroid import objects # pylint: disable=import-outside-toplevel
2464
2465 # set lookup name since this is necessary to infer on import nodes for
2466 # instance
2467 context = copy_context(context)
2468 context.lookupname = name
2469
2470 metaclass = self.metaclass(context=context)
2471 try:
2472 attributes = self.getattr(name, context, class_context=class_context)
2473 # If we have more than one attribute, make sure that those starting from
2474 # the second one are bound on the class owning the first one, in its module,
2475 # such as ``cls.attr = value`` in one of its methods. This is to account for
2476 # modifications to the attribute happening *after* the attribute's
2477 # definition (e.g. AugAssigns on lists), while the attributes of the
2478 # ancestors stay shadowed. Values bound from another module are left out,
2479 # since they would depend on the order in which the modules are built.
2480 if len(attributes) > 1:
2481 first_attr, attributes = attributes[0], attributes[1:]
2482 owner = next(
2483 (
2484 klass
2485 for klass in itertools.chain(
2486 (self,), self.ancestors(recurs=True, context=context)
2487 )
2488 if first_attr in klass.locals.get(name, ())
2489 ),
2490 None,
2491 )
2492 if owner is None:
2493 # The values come from the metaclass: keep those of the same scope.
2494 first_scope = first_attr.parent.scope()
2495 attributes = [first_attr] + [
2496 attr
2497 for attr in attributes
2498 if attr.parent and attr.parent.scope() == first_scope
2499 ]
2500 else:
2501 owner_root = owner.root()
2502 attributes = [first_attr] + [
2503 attr
2504 for attr in attributes
2505 if attr in owner.locals[name] and attr.root() is owner_root
2506 ]
2507 functions = [attr for attr in attributes if isinstance(attr, FunctionDef)]
2508 setter = None
2509 for function in functions:
2510 dec_names = function.decoratornames(context=context)
2511 for dec_name in dec_names:
2512 if dec_name is util.Uninferable:
2513 continue
2514 if dec_name.split(".")[-1] == "setter":
2515 setter = function
2516 if setter:
2517 break
2518 if functions:
2519 # Prefer only the last function, unless a property is involved.
2520 last_function = functions[-1]
2521 attributes = [
2522 a
2523 for a in attributes
2524 if a not in functions or a is last_function or bases._is_property(a)
2525 ]
2526
2527 for inferred in bases._infer_stmts(attributes, context, frame=self):
2528 # yield Uninferable object instead of descriptors when necessary
2529 if not isinstance(inferred, node_classes.Const) and isinstance(
2530 inferred, bases.Instance
2531 ):
2532 try:
2533 inferred._proxied.getattr("__get__", context)
2534 except AttributeInferenceError:
2535 yield inferred
2536 else:
2537 yield util.Uninferable
2538 elif isinstance(inferred, objects.Property):
2539 function = inferred.function
2540 if not class_context:
2541 if not context.callcontext and not setter:
2542 context.callcontext = CallContext(
2543 args=function.args.arguments, callee=function
2544 )
2545 # Through an instance so we can solve the property
2546 yield from function.infer_call_result(
2547 caller=self, context=context
2548 )
2549 # If we're in a class context, we need to determine if the property
2550 # was defined in the metaclass (a derived class must be a subclass of
2551 # the metaclass of all its bases), in which case we can resolve the
2552 # property. If not, i.e. the property is defined in some base class
2553 # instead, then we return the property object
2554 elif metaclass and function.parent.scope() is metaclass:
2555 # Resolve a property as long as it is not accessed through
2556 # the class itself.
2557 yield from function.infer_call_result(
2558 caller=self, context=context
2559 )
2560 else:
2561 yield inferred
2562 else:
2563 yield function_to_method(inferred, self)
2564 except AttributeInferenceError as error:
2565 if not name.startswith("__") and self.has_dynamic_getattr(context):
2566 # class handle some dynamic attributes, return a Uninferable object
2567 yield util.Uninferable
2568 else:
2569 raise InferenceError(
2570 str(error), target=self, attribute=name, context=context
2571 ) from error
2572
2573 def has_dynamic_getattr(self, context: InferenceContext | None = None) -> bool:
2574 """Check if the class has a custom __getattr__ or __getattribute__.
2575
2576 If any such method is found and it is not from
2577 builtins, nor from an extension module, then the function
2578 will return True.
2579
2580 :returns: Whether the class has a custom __getattr__ or __getattribute__.
2581 """
2582
2583 def _valid_getattr(node):
2584 root = node.root()
2585 # An uninferable __getattr__ has an Uninferable root.
2586 return (
2587 isinstance(root, Module)
2588 and root.name != "builtins"
2589 and root.pure_python
2590 )
2591
2592 try:
2593 return _valid_getattr(self.getattr("__getattr__", context)[0])
2594 except AttributeInferenceError:
2595 try:
2596 getattribute = self.getattr("__getattribute__", context)[0]
2597 return _valid_getattr(getattribute)
2598 except AttributeInferenceError:
2599 pass
2600 return False
2601
2602 def getitem(
2603 self, index: SuccessfulInferenceResult, context: InferenceContext | None = None
2604 ) -> InferenceResult:
2605 """Return the inference of a subscript.
2606
2607 This is basically looking up the method in the metaclass and calling it.
2608
2609 :returns: The inferred value of a subscript to this class.
2610
2611 :raises AstroidTypeError: If this class does not define a
2612 ``__getitem__`` method.
2613 """
2614 try:
2615 methods = lookup(self, "__getitem__", context=context)
2616 except AttributeInferenceError as exc:
2617 if isinstance(self, ClassDef):
2618 # subscripting a class definition may be
2619 # achieved thanks to __class_getitem__ method
2620 # which is a classmethod defined in the class
2621 # that supports subscript and not in the metaclass
2622 try:
2623 methods = self.getattr("__class_getitem__")
2624 # Here it is assumed that the __class_getitem__ node is
2625 # a FunctionDef. One possible improvement would be to deal
2626 # with more generic inference.
2627 except AttributeInferenceError:
2628 raise AstroidTypeError(node=self, context=context) from exc
2629 else:
2630 raise AstroidTypeError(node=self, context=context) from exc
2631
2632 method = methods[0]
2633
2634 if isinstance(method, util.UninferableBase):
2635 return util.Uninferable
2636
2637 # Create a new callcontext for providing index as an argument.
2638 new_context = bind_context_to_node(context, self)
2639 new_context.callcontext = CallContext(args=[index], callee=method)
2640
2641 try:
2642 return next(method.infer_call_result(self, new_context), util.Uninferable)
2643 except AttributeError as exc:
2644 # Starting with python3.9, builtin types list, dict etc...
2645 # are subscriptable thanks to __class_getitem___ classmethod.
2646 # However in such case the method is bound to an EmptyNode and
2647 # EmptyNode doesn't have infer_call_result method yielding to
2648 # AttributeError
2649 if (
2650 isinstance(method, node_classes.EmptyNode)
2651 and self.pytype() == "builtins.type"
2652 ):
2653 return self
2654 # ``__class_getitem__`` may resolve to a non-callable node (e.g. an
2655 # ``AssignName`` or an ``Import``), which has no
2656 # ``infer_call_result`` method.
2657 if not method.callable():
2658 raise AstroidTypeError(node=self, context=context) from exc
2659 raise
2660 except InferenceError:
2661 return util.Uninferable
2662
2663 def methods(self) -> Iterator[FunctionDef]:
2664 """Iterate over all of the method defined in this class and its parents.
2665
2666 :returns: The methods defined on the class.
2667 """
2668 done = {}
2669 for astroid in itertools.chain(iter((self,)), self.ancestors()):
2670 for meth in astroid.mymethods():
2671 if meth.name in done:
2672 continue
2673 done[meth.name] = None
2674 yield meth
2675
2676 def mymethods(self) -> Iterator[FunctionDef]:
2677 """Iterate over all of the method defined in this class only.
2678
2679 :returns: The methods defined on the class.
2680 """
2681 for member in self.values():
2682 if isinstance(member, FunctionDef):
2683 yield member
2684
2685 def implicit_metaclass(self) -> NodeNG:
2686 """Get the implicit metaclass of the current class.
2687
2688 This will return an instance of builtins.type.
2689
2690 :returns: The metaclass.
2691 """
2692 return builtin_lookup("type")[1][0]
2693
2694 def declared_metaclass(
2695 self, context: InferenceContext | None = None
2696 ) -> SuccessfulInferenceResult | None:
2697 """Return the explicit declared metaclass for the current class.
2698
2699 An explicit declared metaclass is defined by passing the
2700 ``metaclass`` keyword argument in the class definition line.
2701
2702 :returns: The metaclass of this class,
2703 or None if one could not be found.
2704 """
2705 for base in self.bases:
2706 try:
2707 for baseobj in base.infer(context=context):
2708 if isinstance(baseobj, ClassDef) and baseobj.hide:
2709 self._metaclass = baseobj._metaclass
2710 self._metaclass_hack = True
2711 break
2712 except InferenceError:
2713 pass
2714
2715 if self._metaclass:
2716 try:
2717 return next(
2718 node
2719 for node in self._metaclass.infer(context=context)
2720 if not isinstance(node, util.UninferableBase)
2721 )
2722 except (InferenceError, StopIteration):
2723 return None
2724
2725 return None
2726
2727 def _find_metaclass(
2728 self, seen: set[ClassDef] | None = None, context: InferenceContext | None = None
2729 ) -> SuccessfulInferenceResult | None:
2730 if seen is None:
2731 seen = set()
2732 seen.add(self)
2733
2734 klass = self.declared_metaclass(context=context)
2735 if klass is None:
2736 for parent in self.ancestors(context=context):
2737 if parent not in seen:
2738 klass = parent._find_metaclass(seen)
2739 if klass is not None:
2740 break
2741 return klass
2742
2743 def metaclass(
2744 self, context: InferenceContext | None = None
2745 ) -> SuccessfulInferenceResult | None:
2746 """Get the metaclass of this class.
2747
2748 If this class does not define explicitly a metaclass,
2749 then the first defined metaclass in ancestors will be used
2750 instead.
2751
2752 :returns: The metaclass of this class.
2753 """
2754 return self._find_metaclass(context=context)
2755
2756 def has_metaclass_hack(self) -> bool:
2757 return self._metaclass_hack
2758
2759 def _islots(self):
2760 """Return an iterator with the inferred slots."""
2761 if "__slots__" not in self.locals:
2762 return None
2763 try:
2764 slots_attributes = list(self.igetattr("__slots__"))
2765 except InferenceError:
2766 # ``__slots__`` is present in ``locals`` but cannot be inferred,
2767 # e.g. an annotation-only ``__slots__: ...`` with no assigned value.
2768 return None
2769 for slots in slots_attributes:
2770 # check if __slots__ is a valid type
2771 if not hasattr(slots, "getattr"):
2772 continue
2773 for meth in ITER_METHODS:
2774 try:
2775 slots.getattr(meth)
2776 break
2777 except AttributeInferenceError:
2778 continue
2779 else:
2780 continue
2781
2782 if isinstance(slots, node_classes.Const):
2783 # a string. Ignore the following checks,
2784 # but yield the node, only if it has a value
2785 if slots.value:
2786 yield slots
2787 continue
2788 if not hasattr(slots, "itered"):
2789 # we can't obtain the values, maybe a .deque?
2790 continue
2791
2792 if isinstance(slots, node_classes.Dict):
2793 values = [item[0] for item in slots.items]
2794 else:
2795 values = slots.itered()
2796 if isinstance(values, util.UninferableBase):
2797 continue
2798 if not values:
2799 # Stop the iteration, because the class
2800 # has an empty list of slots.
2801 return values
2802
2803 for elt in values:
2804 try:
2805 for inferred in elt.infer():
2806 if not (
2807 isinstance(inferred, node_classes.Const)
2808 and isinstance(inferred.value, str)
2809 ):
2810 continue
2811 if not inferred.value:
2812 continue
2813 yield inferred
2814 except InferenceError:
2815 continue
2816
2817 return None
2818
2819 def _slots(self):
2820
2821 slots = self._islots()
2822 try:
2823 first = next(slots)
2824 except StopIteration as exc:
2825 # The class doesn't have a __slots__ definition or empty slots.
2826 if exc.args and exc.args[0] not in ("", None):
2827 return exc.args[0]
2828 return None
2829 return [first, *slots]
2830
2831 # Cached, because inferring them all the time is expensive
2832 @cached_property
2833 def _all_slots(self) -> list[node_classes.Const] | None:
2834 """Get all the slots for this node.
2835
2836 :returns: The names of slots for this class.
2837 If the class doesn't define any slot, through the ``__slots__``
2838 variable, then this function will return a None.
2839 Also, it will return None in the case the slots were not inferred.
2840 """
2841
2842 def grouped_slots(
2843 mro: list[ClassDef],
2844 ) -> Iterator[node_classes.NodeNG | None]:
2845 for cls in mro:
2846 # Not interested in object, since it can't have slots.
2847 if cls.qname() == "builtins.object":
2848 continue
2849 try:
2850 cls_slots = cls._slots()
2851 except NotImplementedError:
2852 continue
2853 if cls_slots is not None:
2854 yield from cls_slots
2855 else:
2856 yield None
2857
2858 try:
2859 mro = self.mro()
2860 except MroError as e:
2861 raise NotImplementedError(
2862 "Cannot get slots while parsing mro fails."
2863 ) from e
2864
2865 slots = list(grouped_slots(mro))
2866 if not all(slot is not None for slot in slots):
2867 return None
2868
2869 return sorted(set(slots), key=lambda item: item.value)
2870
2871 def slots(self):
2872 return self._all_slots
2873
2874 def _inferred_bases(
2875 self,
2876 context: InferenceContext | None = None,
2877 *,
2878 base_classes: frozenset[ClassDef] = frozenset(),
2879 ):
2880 # Similar with .ancestors, but the difference is when one base is inferred,
2881 # only the first object is wanted. That's because
2882 # we aren't interested in superclasses, as in the following
2883 # example:
2884 #
2885 # class SomeSuperClass(object): pass
2886 # class SomeClass(SomeSuperClass): pass
2887 # class Test(SomeClass): pass
2888 #
2889 # Inferring SomeClass from the Test's bases will give
2890 # us both SomeClass and SomeSuperClass, but we are interested
2891 # only in SomeClass.
2892
2893 if context is None:
2894 context = InferenceContext()
2895 if not self.bases and self.qname() != "builtins.object":
2896 yield builtin_lookup("object")[1][0]
2897 return
2898
2899 for stmt in self.bases:
2900 try:
2901 baseobj = _infer_last(stmt, context)
2902 except InferenceError:
2903 continue
2904 if isinstance(baseobj, bases.Instance):
2905 baseobj = baseobj._proxied
2906 if not isinstance(baseobj, ClassDef):
2907 continue
2908 if baseobj is self or baseobj in base_classes:
2909 # Circular base due to name rebinding (e.g. pdb.Pdb = CustomPdb
2910 # where CustomPdb inherits from pdb.Pdb). Fall back to the
2911 # first non-circular inferred value from the base expression.
2912 baseobj = self._resolve_circular_base(stmt, context)
2913 if baseobj is None:
2914 continue
2915 if not baseobj.hide:
2916 yield baseobj
2917 else:
2918 yield from baseobj.bases
2919
2920 def _resolve_circular_base(
2921 self,
2922 stmt: nodes.NodeNG,
2923 context: InferenceContext | None,
2924 ) -> ClassDef | None:
2925 """Resolve a circular base reference by finding the original class.
2926
2927 When a name is rebound to a subclass (e.g. ``pdb.Pdb = CustomPdb``),
2928 ``_infer_last`` follows the rebinding and returns the subclass itself.
2929 This method iterates through all inferred values to find the first
2930 non-circular ClassDef.
2931 """
2932 inf_context = copy_context(context)
2933 try:
2934 for inferred in stmt.infer(context=inf_context):
2935 if isinstance(inferred, bases.Instance):
2936 inferred = inferred._proxied
2937 if isinstance(inferred, ClassDef) and inferred is not self:
2938 return inferred
2939 except InferenceError:
2940 pass
2941 return None
2942
2943 def _compute_mro(
2944 self,
2945 context: InferenceContext,
2946 *,
2947 base_chain: frozenset[ClassDef] = frozenset(),
2948 ):
2949 if self.qname() == "builtins.object":
2950 return [self]
2951
2952 inferred_bases = list(
2953 self._inferred_bases(context=context, base_classes=base_chain)
2954 )
2955 bases_mro = []
2956 base_chain |= {self}
2957 for base in inferred_bases:
2958 if base in base_chain:
2959 continue
2960
2961 mro = base._compute_mro(context=context, base_chain=base_chain)
2962 bases_mro.append(mro)
2963
2964 unmerged_mro: list[list[ClassDef]] = [[self], *bases_mro, inferred_bases]
2965 unmerged_mro = clean_duplicates_mro(unmerged_mro, self, context)
2966 clean_typing_generic_mro(unmerged_mro)
2967 return _c3_merge(unmerged_mro, self, context)
2968
2969 def mro(self, context: InferenceContext | None = None) -> list[ClassDef]:
2970 """Get the method resolution order, using C3 linearization.
2971
2972 :returns: The list of ancestors, sorted by the mro.
2973 :raises DuplicateBasesError: Duplicate bases in the same class base
2974 :raises InconsistentMroError: A class' MRO is inconsistent
2975 """
2976 return self._compute_mro(context=context)
2977
2978 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
2979 """Determine the boolean value of this node.
2980
2981 :returns: The boolean value of this node.
2982 For a :class:`ClassDef` this is always ``True``.
2983 """
2984 return True
2985
2986 def get_children(self):
2987 if self.decorators is not None:
2988 yield self.decorators
2989
2990 yield from self.bases
2991 if self.keywords is not None:
2992 yield from self.keywords
2993 yield from self.type_params
2994
2995 yield from self.body
2996
2997 @cached_property
2998 def _assign_nodes_in_scope(self):
2999 children_assign_nodes = (
3000 child_node._assign_nodes_in_scope for child_node in self.body
3001 )
3002 return list(itertools.chain.from_iterable(children_assign_nodes))
3003
3004 def frame(self, *, future: Literal[None, True] = None) -> Self:
3005 """The node's frame node.
3006
3007 A frame node is a :class:`Module`, :class:`FunctionDef`,
3008 :class:`ClassDef` or :class:`Lambda`.
3009
3010 :returns: The node itself.
3011 """
3012 return self
3013
3014 def _infer(self, context: InferenceContext | None = None) -> Generator[ClassDef]:
3015 yield self