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 l.1 at 0x...>
610 """
611
612 _astroid_fields = ("elt", "generators")
613 _other_other_fields = ("locals",)
614 elt: NodeNG
615 """The element that forms the output of the expression."""
616
617 def __init__(
618 self,
619 lineno: int,
620 col_offset: int,
621 parent: NodeNG,
622 *,
623 end_lineno: int | None,
624 end_col_offset: int | None,
625 ) -> None:
626 self.locals = {}
627 """A map of the name of a local variable to the node defining the local."""
628
629 self.generators: list[nodes.Comprehension] = []
630 """The generators that are looped through."""
631
632 super().__init__(
633 lineno=lineno,
634 col_offset=col_offset,
635 end_lineno=end_lineno,
636 end_col_offset=end_col_offset,
637 parent=parent,
638 )
639
640 def postinit(self, elt: NodeNG, generators: list[nodes.Comprehension]) -> None:
641 self.elt = elt
642 self.generators = generators
643
644 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
645 """Determine the boolean value of this node.
646
647 :returns: The boolean value of this node.
648 For a :class:`GeneratorExp` this is always ``True``.
649 """
650 return True
651
652 def get_children(self):
653 yield self.elt
654
655 yield from self.generators
656
657
658class DictComp(ComprehensionScope):
659 """Class representing an :class:`ast.DictComp` node.
660
661 >>> import astroid
662 >>> node = astroid.extract_node('{k:v for k, v in things if k > v}')
663 >>> node
664 <DictComp l.1 at 0x...>
665 """
666
667 _astroid_fields = ("key", "value", "generators")
668 _other_other_fields = ("locals",)
669 key: NodeNG
670 """What produces the keys."""
671
672 value: NodeNG
673 """What produces the values."""
674
675 def __init__(
676 self,
677 lineno: int,
678 col_offset: int,
679 parent: NodeNG,
680 *,
681 end_lineno: int | None,
682 end_col_offset: int | None,
683 ) -> None:
684 self.locals = {}
685 """A map of the name of a local variable to the node defining the local."""
686
687 super().__init__(
688 lineno=lineno,
689 col_offset=col_offset,
690 end_lineno=end_lineno,
691 end_col_offset=end_col_offset,
692 parent=parent,
693 )
694
695 def postinit(
696 self, key: NodeNG, value: NodeNG, generators: list[nodes.Comprehension]
697 ) -> None:
698 self.key = key
699 self.value = value
700 self.generators = generators
701
702 def bool_value(
703 self, context: InferenceContext | None = None
704 ) -> util.UninferableBase:
705 """Determine the boolean value of this node.
706
707 :returns: The boolean value of this node.
708 For a :class:`DictComp` this is always :obj:`~astroid.Uninferable`.
709 """
710 return util.Uninferable
711
712 def get_children(self):
713 yield self.key
714 yield self.value
715
716 yield from self.generators
717
718
719class SetComp(ComprehensionScope):
720 """Class representing an :class:`ast.SetComp` node.
721
722 >>> import astroid
723 >>> node = astroid.extract_node('{thing for thing in things if thing}')
724 >>> node
725 <SetComp l.1 at 0x...>
726 """
727
728 _astroid_fields = ("elt", "generators")
729 _other_other_fields = ("locals",)
730 elt: NodeNG
731 """The element that forms the output of the expression."""
732
733 def __init__(
734 self,
735 lineno: int,
736 col_offset: int,
737 parent: NodeNG,
738 *,
739 end_lineno: int | None,
740 end_col_offset: int | None,
741 ) -> None:
742 self.locals = {}
743 """A map of the name of a local variable to the node defining the local."""
744
745 self.generators: list[nodes.Comprehension] = []
746 """The generators that are looped through."""
747
748 super().__init__(
749 lineno=lineno,
750 col_offset=col_offset,
751 end_lineno=end_lineno,
752 end_col_offset=end_col_offset,
753 parent=parent,
754 )
755
756 def postinit(self, elt: NodeNG, generators: list[nodes.Comprehension]) -> None:
757 self.elt = elt
758 self.generators = generators
759
760 def bool_value(
761 self, context: InferenceContext | None = None
762 ) -> util.UninferableBase:
763 """Determine the boolean value of this node.
764
765 :returns: The boolean value of this node.
766 For a :class:`SetComp` this is always :obj:`~astroid.Uninferable`.
767 """
768 return util.Uninferable
769
770 def get_children(self):
771 yield self.elt
772
773 yield from self.generators
774
775
776class ListComp(ComprehensionScope):
777 """Class representing an :class:`ast.ListComp` node.
778
779 >>> import astroid
780 >>> node = astroid.extract_node('[thing for thing in things if thing]')
781 >>> node
782 <ListComp l.1 at 0x...>
783 """
784
785 _astroid_fields = ("elt", "generators")
786 _other_other_fields = ("locals",)
787
788 elt: NodeNG
789 """The element that forms the output of the expression."""
790
791 def __init__(
792 self,
793 lineno: int,
794 col_offset: int,
795 parent: NodeNG,
796 *,
797 end_lineno: int | None,
798 end_col_offset: int | None,
799 ) -> None:
800 self.locals = {}
801 """A map of the name of a local variable to the node defining it."""
802
803 self.generators: list[nodes.Comprehension] = []
804 """The generators that are looped through."""
805
806 super().__init__(
807 lineno=lineno,
808 col_offset=col_offset,
809 end_lineno=end_lineno,
810 end_col_offset=end_col_offset,
811 parent=parent,
812 )
813
814 def postinit(self, elt: NodeNG, generators: list[nodes.Comprehension]):
815 self.elt = elt
816 self.generators = generators
817
818 def bool_value(
819 self, context: InferenceContext | None = None
820 ) -> util.UninferableBase:
821 """Determine the boolean value of this node.
822
823 :returns: The boolean value of this node.
824 For a :class:`ListComp` this is always :obj:`~astroid.Uninferable`.
825 """
826 return util.Uninferable
827
828 def get_children(self):
829 yield self.elt
830
831 yield from self.generators
832
833
834def _infer_decorator_callchain(node):
835 """Detect decorator call chaining and see if the end result is a
836 static or a classmethod.
837 """
838 if not isinstance(node, FunctionDef):
839 return None
840 if not node.parent:
841 return None
842 try:
843 result = next(node.infer_call_result(node.parent), None)
844 except InferenceError:
845 return None
846 if isinstance(result, bases.Instance):
847 result = result._proxied
848 if isinstance(result, ClassDef):
849 if result.is_subtype_of("builtins.classmethod"):
850 return "classmethod"
851 if result.is_subtype_of("builtins.staticmethod"):
852 return "staticmethod"
853 if isinstance(result, FunctionDef):
854 if not result.decorators:
855 return None
856 # Determine if this function is decorated with one of the builtin descriptors we want.
857 for decorator in result.decorators.nodes:
858 if isinstance(decorator, node_classes.Name):
859 if decorator.name in BUILTIN_DESCRIPTORS:
860 return decorator.name
861 if (
862 isinstance(decorator, node_classes.Attribute)
863 and isinstance(decorator.expr, node_classes.Name)
864 and decorator.expr.name == "builtins"
865 and decorator.attrname in BUILTIN_DESCRIPTORS
866 ):
867 return decorator.attrname
868 return None
869
870
871class Lambda(_base_nodes.FilterStmtsBaseNode, LocalsDictNodeNG):
872 """Class representing an :class:`ast.Lambda` node.
873
874 >>> import astroid
875 >>> node = astroid.extract_node('lambda arg: arg + 1')
876 >>> node
877 <Lambda.<lambda> l.1 at 0x...>
878 """
879
880 _astroid_fields: ClassVar[tuple[str, ...]] = ("args", "body")
881 _other_other_fields: ClassVar[tuple[str, ...]] = ("locals",)
882 name = "<lambda>"
883 is_lambda = True
884 special_attributes = FunctionModel()
885 """The names of special attributes that this function has."""
886
887 args: Arguments
888 """The arguments that the function takes."""
889
890 body: NodeNG
891 """The contents of the function body."""
892
893 def implicit_parameters(self) -> Literal[0]:
894 return 0
895
896 @property
897 def type(self) -> Literal["method", "function"]:
898 """Whether this is a method or function.
899
900 :returns: 'method' if this is a method, 'function' otherwise.
901 """
902 if self.args.arguments and self.args.arguments[0].name == "self":
903 if self.parent and isinstance(self.parent.scope(), ClassDef):
904 return "method"
905 return "function"
906
907 def __init__(
908 self,
909 lineno: int,
910 col_offset: int,
911 parent: NodeNG,
912 *,
913 end_lineno: int | None,
914 end_col_offset: int | None,
915 ):
916 self.locals = {}
917 """A map of the name of a local variable to the node defining it."""
918
919 self.instance_attrs: dict[str, list[InferenceResult]] = {}
920
921 super().__init__(
922 lineno=lineno,
923 col_offset=col_offset,
924 end_lineno=end_lineno,
925 end_col_offset=end_col_offset,
926 parent=parent,
927 )
928
929 def postinit(self, args: Arguments, body: NodeNG) -> None:
930 self.args = args
931 self.body = body
932
933 def pytype(self) -> Literal["builtins.instancemethod", "builtins.function"]:
934 """Get the name of the type that this node represents.
935
936 :returns: The name of the type.
937 """
938 if "method" in self.type:
939 return "builtins.instancemethod"
940 return "builtins.function"
941
942 def display_type(self) -> str:
943 """A human readable type of this node.
944
945 :returns: The type of this node.
946 """
947 if "method" in self.type:
948 return "Method"
949 return "Function"
950
951 def callable(self) -> Literal[True]:
952 """Whether this node defines something that is callable.
953
954 :returns: Whether this defines something that is callable
955 For a :class:`Lambda` this is always ``True``.
956 """
957 return True
958
959 def argnames(self) -> list[str]:
960 """Get the names of each of the arguments, including that
961 of the collections of variable-length arguments ("args", "kwargs",
962 etc.), as well as positional-only and keyword-only arguments.
963
964 :returns: The names of the arguments.
965 """
966 if self.args.arguments: # maybe None with builtin functions
967 names = [elt.name for elt in self.args.arguments]
968 else:
969 names = []
970
971 return names
972
973 def infer_call_result(
974 self,
975 caller: SuccessfulInferenceResult | None,
976 context: InferenceContext | None = None,
977 ) -> Iterator[InferenceResult]:
978 """Infer what the function returns when called."""
979 return self.body.infer(context)
980
981 def scope_lookup(
982 self, node: LookupMixIn, name: str, offset: int = 0
983 ) -> tuple[LocalsDictNodeNG, list[NodeNG]]:
984 """Lookup where the given names is assigned.
985
986 :param node: The node to look for assignments up to.
987 Any assignments after the given node are ignored.
988
989 :param name: The name to find assignments for.
990
991 :param offset: The line offset to filter statements up to.
992
993 :returns: This scope node and the list of assignments associated to the
994 given name according to the scope where it has been found (locals,
995 globals or builtin).
996 """
997 if (self.args.defaults and node in self.args.defaults) or (
998 self.args.kw_defaults and node in self.args.kw_defaults
999 ):
1000 if not self.parent:
1001 raise ParentMissingError(target=self)
1002 frame = self.parent.frame()
1003 # line offset to avoid that def func(f=func) resolve the default
1004 # value to the defined function
1005 offset = -1
1006 else:
1007 # check this is not used in function decorators
1008 frame = self
1009 return frame._scope_lookup(node, name, offset)
1010
1011 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
1012 """Determine the boolean value of this node.
1013
1014 :returns: The boolean value of this node.
1015 For a :class:`Lambda` this is always ``True``.
1016 """
1017 return True
1018
1019 def get_children(self):
1020 yield self.args
1021 yield self.body
1022
1023 def frame(self, *, future: Literal[None, True] = None) -> Self:
1024 """The node's frame node.
1025
1026 A frame node is a :class:`Module`, :class:`FunctionDef`,
1027 :class:`ClassDef` or :class:`Lambda`.
1028
1029 :returns: The node itself.
1030 """
1031 return self
1032
1033 def getattr(
1034 self, name: str, context: InferenceContext | None = None
1035 ) -> list[InferenceResult]:
1036 if not name:
1037 raise AttributeInferenceError(target=self, attribute=name, context=context)
1038
1039 # Copy, so that adding the special attribute does not modify instance_attrs
1040 found_attrs = list(self.instance_attrs.get(name, []))
1041 if name in self.special_attributes:
1042 found_attrs.append(self.special_attributes.lookup(name))
1043 if found_attrs:
1044 return found_attrs
1045 raise AttributeInferenceError(target=self, attribute=name)
1046
1047 def _infer(self, context: InferenceContext | None = None) -> Generator[Lambda]:
1048 yield self
1049
1050 def _get_yield_nodes_skip_functions(self):
1051 """A Lambda node can contain a Yield node in the body."""
1052 yield from self.body._get_yield_nodes_skip_functions()
1053
1054
1055class FunctionDef(
1056 _base_nodes.MultiLineBlockNode,
1057 _base_nodes.FilterStmtsBaseNode,
1058 _base_nodes.Statement,
1059 LocalsDictNodeNG,
1060):
1061 """Class representing an :class:`ast.FunctionDef`.
1062
1063 >>> import astroid
1064 >>> node = astroid.extract_node('''
1065 ... def my_func(arg):
1066 ... return arg + 1
1067 ... ''')
1068 >>> node
1069 <FunctionDef.my_func l.2 at 0x...>
1070 """
1071
1072 _astroid_fields = (
1073 "decorators",
1074 "args",
1075 "returns",
1076 "type_params",
1077 "doc_node",
1078 "body",
1079 )
1080 _multi_line_block_fields = ("body",)
1081 returns = None
1082
1083 decorators: node_classes.Decorators | None
1084 """The decorators that are applied to this method or function."""
1085
1086 doc_node: Const | None
1087 """The doc node associated with this node."""
1088
1089 args: Arguments
1090 """The arguments that the function takes."""
1091
1092 is_function: ClassVar[bool] = True
1093 """Whether this node indicates a function.
1094
1095 For a :class:`FunctionDef` this is always ``True``.
1096 """
1097 type_annotation: NodeNG | None = None
1098 """If present, this will contain the type annotation passed by a type comment"""
1099 type_comment_args = None
1100 """
1101 If present, this will contain the type annotation for arguments
1102 passed by a type comment
1103 """
1104 type_comment_returns = None
1105 """If present, this will contain the return type annotation, passed by a type comment"""
1106 # attributes below are set by the builder module or by raw factories
1107 _other_fields = ("name", "position")
1108 _other_other_fields = (
1109 "locals",
1110 "_type",
1111 "type_comment_returns",
1112 "type_comment_args",
1113 )
1114 _type = None
1115
1116 name = "<functiondef>"
1117
1118 special_attributes = FunctionModel()
1119 """The names of special attributes that this function has."""
1120
1121 def __init__(
1122 self,
1123 name: str,
1124 lineno: int,
1125 col_offset: int,
1126 parent: NodeNG,
1127 *,
1128 end_lineno: int | None,
1129 end_col_offset: int | None,
1130 ) -> None:
1131 self.name = name
1132 """The name of the function."""
1133
1134 self.locals = {}
1135 """A map of the name of a local variable to the node defining it."""
1136
1137 self.body: list[NodeNG] = []
1138 """The contents of the function body."""
1139
1140 self.type_params: list[nodes.TypeVar | nodes.ParamSpec | nodes.TypeVarTuple] = (
1141 []
1142 )
1143 """The type parameters introduced by :pep:`695`, new in Python 3.12.
1144
1145 For example, the ``T`` in ``def func[T]() -> T: ...``.
1146 """
1147
1148 self.instance_attrs: dict[str, list[InferenceResult]] = {}
1149
1150 super().__init__(
1151 lineno=lineno,
1152 col_offset=col_offset,
1153 end_lineno=end_lineno,
1154 end_col_offset=end_col_offset,
1155 parent=parent,
1156 )
1157
1158 def postinit(
1159 self,
1160 args: Arguments,
1161 body: list[NodeNG],
1162 decorators: node_classes.Decorators | None = None,
1163 returns=None,
1164 type_comment_returns=None,
1165 type_comment_args=None,
1166 *,
1167 position: Position | None = None,
1168 doc_node: Const | None = None,
1169 type_params: (
1170 list[nodes.TypeVar | nodes.ParamSpec | nodes.TypeVarTuple] | None
1171 ) = None,
1172 ):
1173 """Do some setup after initialisation.
1174
1175 :param args: The arguments that the function takes.
1176
1177 :param body: The contents of the function body.
1178
1179 :param decorators: The decorators that are applied to this
1180 method or function.
1181 :params type_comment_returns:
1182 The return type annotation passed via a type comment.
1183 :params type_comment_args:
1184 The args type annotation passed via a type comment.
1185 :params position:
1186 Position of function keyword(s) and name.
1187 :param doc_node:
1188 The doc node associated with this node.
1189 :param type_params:
1190 The type_params associated with this node.
1191 """
1192 self.args = args
1193 self.body = body
1194 self.decorators = decorators
1195 self.returns = returns
1196 self.type_comment_returns = type_comment_returns
1197 self.type_comment_args = type_comment_args
1198 self.position = position
1199 self.doc_node = doc_node
1200 self.type_params = type_params or []
1201
1202 @cached_property
1203 def extra_decorators(self) -> list[node_classes.Call]:
1204 """The extra decorators that this function can have.
1205
1206 Additional decorators are considered when they are used as
1207 assignments, as in ``method = staticmethod(method)``.
1208 The property will return all the callables that are used for
1209 decoration.
1210 """
1211 if not (self.parent and isinstance(frame := self.parent.frame(), ClassDef)):
1212 return []
1213
1214 decorators: list[node_classes.Call] = []
1215 for assign in frame._assign_nodes_in_scope:
1216 if isinstance(assign.value, node_classes.Call) and isinstance(
1217 assign.value.func, node_classes.Name
1218 ):
1219 for assign_node in assign.targets:
1220 if not isinstance(assign_node, node_classes.AssignName):
1221 # Support only `name = callable(name)`
1222 continue
1223
1224 if assign_node.name != self.name:
1225 # Interested only in the assignment nodes that
1226 # decorates the current method.
1227 continue
1228 try:
1229 meth = frame[self.name]
1230 except KeyError:
1231 continue
1232 else:
1233 # Must be a function and in the same frame as the
1234 # original method.
1235 if (
1236 isinstance(meth, FunctionDef)
1237 and assign_node.frame() == frame
1238 ):
1239 decorators.append(assign.value)
1240 return decorators
1241
1242 def pytype(self) -> Literal["builtins.instancemethod", "builtins.function"]:
1243 """Get the name of the type that this node represents.
1244
1245 :returns: The name of the type.
1246 """
1247 if "method" in self.type:
1248 return "builtins.instancemethod"
1249 return "builtins.function"
1250
1251 def display_type(self) -> str:
1252 """A human readable type of this node.
1253
1254 :returns: The type of this node.
1255 """
1256 if "method" in self.type:
1257 return "Method"
1258 return "Function"
1259
1260 def callable(self) -> Literal[True]:
1261 return True
1262
1263 def argnames(self) -> list[str]:
1264 """Get the names of each of the arguments, including that
1265 of the collections of variable-length arguments ("args", "kwargs",
1266 etc.), as well as positional-only and keyword-only arguments.
1267
1268 :returns: The names of the arguments.
1269 """
1270 if self.args.arguments: # maybe None with builtin functions
1271 names = [elt.name for elt in self.args.arguments]
1272 else:
1273 names = []
1274
1275 return names
1276
1277 def getattr(
1278 self, name: str, context: InferenceContext | None = None
1279 ) -> list[InferenceResult]:
1280 if not name:
1281 raise AttributeInferenceError(target=self, attribute=name, context=context)
1282
1283 # Copy, so that adding the special attribute does not modify instance_attrs
1284 found_attrs = list(self.instance_attrs.get(name, []))
1285 if name in self.special_attributes:
1286 found_attrs.append(self.special_attributes.lookup(name))
1287 if found_attrs:
1288 return found_attrs
1289 raise AttributeInferenceError(target=self, attribute=name)
1290
1291 @cached_property
1292 def type(self) -> str: # pylint: disable=too-many-return-statements # noqa: C901
1293 """The function type for this node.
1294
1295 Possible values are: method, function, staticmethod, classmethod.
1296 """
1297 for decorator in self.extra_decorators:
1298 if decorator.func.name in BUILTIN_DESCRIPTORS:
1299 return decorator.func.name
1300
1301 if not self.parent:
1302 raise ParentMissingError(target=self)
1303
1304 frame = self.parent.frame()
1305 type_name = "function"
1306 if isinstance(frame, ClassDef):
1307 if self.name == "__new__":
1308 return "classmethod"
1309 if self.name == "__init_subclass__":
1310 return "classmethod"
1311 if self.name == "__class_getitem__":
1312 return "classmethod"
1313
1314 type_name = "method"
1315
1316 if not self.decorators:
1317 return type_name
1318
1319 for node in self.decorators.nodes:
1320 if isinstance(node, node_classes.Name):
1321 if node.name in BUILTIN_DESCRIPTORS:
1322 return node.name
1323 if (
1324 isinstance(node, node_classes.Attribute)
1325 and isinstance(node.expr, node_classes.Name)
1326 and node.expr.name == "builtins"
1327 and node.attrname in BUILTIN_DESCRIPTORS
1328 ):
1329 return node.attrname
1330
1331 if isinstance(node, node_classes.Call):
1332 # Handle the following case:
1333 # @some_decorator(arg1, arg2)
1334 # def func(...)
1335 #
1336 try:
1337 current = next(node.func.infer())
1338 except (InferenceError, StopIteration):
1339 continue
1340 _type = _infer_decorator_callchain(current)
1341 if _type is not None:
1342 return _type
1343
1344 try:
1345 for inferred in node.infer():
1346 # Check to see if this returns a static or a class method.
1347 _type = _infer_decorator_callchain(inferred)
1348 if _type is not None:
1349 return _type
1350
1351 if not isinstance(inferred, ClassDef):
1352 continue
1353 for ancestor in inferred.ancestors():
1354 if not isinstance(ancestor, ClassDef):
1355 continue
1356 if ancestor.is_subtype_of("builtins.classmethod"):
1357 return "classmethod"
1358 if ancestor.is_subtype_of("builtins.staticmethod"):
1359 return "staticmethod"
1360 except InferenceError:
1361 pass
1362 return type_name
1363
1364 @cached_property
1365 def fromlineno(self) -> int:
1366 """The first line that this node appears on in the source code.
1367
1368 Can also return 0 if the line can not be determined.
1369 """
1370 # lineno is the line number of the first decorator, we want the def
1371 # statement lineno. Similar to 'ClassDef.fromlineno'
1372 lineno = self.lineno or 0
1373 if self.decorators is not None:
1374 lineno += sum(
1375 node.tolineno - (node.lineno or 0) + 1 for node in self.decorators.nodes
1376 )
1377
1378 return lineno or 0
1379
1380 @cached_property
1381 def blockstart_tolineno(self) -> int:
1382 """The line on which the beginning of this block ends."""
1383 if self.returns:
1384 return self.returns.tolineno
1385 return self.args.tolineno
1386
1387 def implicit_parameters(self) -> Literal[0, 1]:
1388 return 1 if self.is_bound() else 0
1389
1390 def block_range(self, lineno: int) -> tuple[int, int]:
1391 """Get a range from the given line number to where this node ends.
1392
1393 :param lineno: Unused.
1394
1395 :returns: The range of line numbers that this node belongs to,
1396 """
1397 return self.fromlineno, self.tolineno
1398
1399 def igetattr(
1400 self, name: str, context: InferenceContext | None = None
1401 ) -> Iterator[InferenceResult]:
1402 """Inferred getattr, which returns an iterator of inferred statements."""
1403 try:
1404 return bases._infer_stmts(self.getattr(name, context), context, frame=self)
1405 except AttributeInferenceError as error:
1406 raise InferenceError(
1407 str(error), target=self, attribute=name, context=context
1408 ) from error
1409
1410 def is_method(self) -> bool:
1411 """Check if this function node represents a method.
1412
1413 :returns: Whether this is a method.
1414 """
1415 # check we are defined in a ClassDef, because this is usually expected
1416 # (e.g. pylint...) when is_method() return True
1417 return (
1418 self.type != "function"
1419 and self.parent is not None
1420 and isinstance(self.parent.frame(), ClassDef)
1421 )
1422
1423 def decoratornames(self, context: InferenceContext | None = None) -> set[str]:
1424 """Get the qualified names of each of the decorators on this function.
1425
1426 :param context:
1427 An inference context that can be passed to inference functions
1428 :returns: The names of the decorators.
1429 """
1430 result = set()
1431 decoratornodes = []
1432 if self.decorators is not None:
1433 decoratornodes += self.decorators.nodes
1434 decoratornodes += self.extra_decorators
1435 for decnode in decoratornodes:
1436 try:
1437 for infnode in decnode.infer(context=context):
1438 result.add(infnode.qname())
1439 except InferenceError:
1440 continue
1441 return result
1442
1443 def is_bound(self) -> bool:
1444 """Check if the function is bound to an instance or class.
1445
1446 :returns: Whether the function is bound to an instance or class.
1447 """
1448 return self.type in {"method", "classmethod"}
1449
1450 def is_abstract(self, pass_is_abstract=True, any_raise_is_abstract=False) -> bool:
1451 """Check if the method is abstract.
1452
1453 A method is considered abstract if any of the following is true:
1454 * The only statement is 'raise NotImplementedError'
1455 * The only statement is 'raise <SomeException>' and any_raise_is_abstract is True
1456 * The only statement is 'pass' and pass_is_abstract is True
1457 * The method is annotated with abc.astractproperty/abc.abstractmethod
1458
1459 :returns: Whether the method is abstract.
1460 """
1461 if self.decorators:
1462 for node in self.decorators.nodes:
1463 try:
1464 inferred = next(node.infer())
1465 except (InferenceError, StopIteration):
1466 continue
1467 if inferred and inferred.qname() in {
1468 "abc.abstractproperty",
1469 "abc.abstractmethod",
1470 }:
1471 return True
1472
1473 for child_node in self.body:
1474 if isinstance(child_node, node_classes.Raise):
1475 if any_raise_is_abstract:
1476 return True
1477 if child_node.raises_not_implemented():
1478 return True
1479 return pass_is_abstract and isinstance(child_node, node_classes.Pass)
1480 # empty function is the same as function with a single "pass" statement
1481 if pass_is_abstract:
1482 return True
1483
1484 return False
1485
1486 def is_generator(self) -> bool:
1487 """Check if this is a generator function.
1488
1489 :returns: Whether this is a generator function.
1490 """
1491 yields_without_lambdas = set(self._get_yield_nodes_skip_lambdas())
1492 yields_without_functions = set(self._get_yield_nodes_skip_functions())
1493 # Want an intersecting member that is neither in a lambda nor a function
1494 return bool(yields_without_lambdas & yields_without_functions)
1495
1496 def _infer(
1497 self, context: InferenceContext | None = None
1498 ) -> Generator[objects.Property | FunctionDef, None, InferenceErrorInfo]:
1499 from astroid import objects # pylint: disable=import-outside-toplevel
1500
1501 if not (self.decorators and bases._is_property(self)):
1502 yield self
1503 return InferenceErrorInfo(node=self, context=context)
1504
1505 if not self.parent:
1506 raise ParentMissingError(target=self)
1507 prop_func = objects.Property(
1508 function=self,
1509 name=self.name,
1510 lineno=self.lineno,
1511 parent=self.parent,
1512 col_offset=self.col_offset,
1513 )
1514 prop_func.postinit(body=[], args=self.args, doc_node=self.doc_node)
1515 yield prop_func
1516 return InferenceErrorInfo(node=self, context=context)
1517
1518 def infer_yield_result(
1519 self, context: InferenceContext | None = None
1520 ) -> Iterator[InferenceResult]:
1521 """Infer what the function yields when called
1522
1523 :returns: What the function yields
1524 """
1525 for yield_ in self.nodes_of_class(node_classes.Yield):
1526 if yield_.value is None:
1527 yield node_classes.Const(None, parent=yield_, lineno=yield_.lineno)
1528 elif yield_.scope() == self:
1529 yield from yield_.value.infer(context=context)
1530
1531 @staticmethod
1532 def _is_stub_placeholder_body(body: list[NodeNG]) -> bool:
1533 """Check if a function body is empty, ``...``, or ``pass``."""
1534 if not body:
1535 return True
1536 if len(body) != 1:
1537 return False
1538 statement = body[0]
1539 return isinstance(statement, node_classes.Pass) or (
1540 isinstance(statement, node_classes.Expr)
1541 and isinstance(statement.value, node_classes.Const)
1542 and statement.value.value is ...
1543 )
1544
1545 def infer_call_result(
1546 self,
1547 caller: SuccessfulInferenceResult | None,
1548 context: InferenceContext | None = None,
1549 ) -> Iterator[InferenceResult]:
1550 """Infer what the function returns when called."""
1551 if context is None:
1552 context = InferenceContext()
1553 if self.is_generator():
1554 if isinstance(self, AsyncFunctionDef):
1555 generator_cls: type[bases.Generator] = bases.AsyncGenerator
1556 else:
1557 generator_cls = bases.Generator
1558 result = generator_cls(self, generator_initial_context=context)
1559 yield result
1560 return
1561 # This is really a gigantic hack to work around metaclass generators
1562 # that return transient class-generating functions. Pylint's AST structure
1563 # cannot handle a base class object that is only used for calling __new__,
1564 # but does not contribute to the inheritance structure itself. We inject
1565 # a fake class into the hierarchy here for several well-known metaclass
1566 # generators, and filter it out later.
1567 if (
1568 self.name == "with_metaclass"
1569 and caller is not None
1570 and self.args.args
1571 and len(self.args.args) == 1
1572 and self.args.vararg is not None
1573 ):
1574 if isinstance(caller.args, node_classes.Arguments):
1575 assert caller.args.args is not None
1576 call_args = caller.args.args
1577 elif isinstance(caller.args, list):
1578 call_args = caller.args
1579 else:
1580 raise TypeError( # pragma: no cover
1581 f"caller.args was neither Arguments nor list; got {type(caller.args)}"
1582 )
1583 if not call_args:
1584 # ``with_metaclass()`` called without a metaclass argument is
1585 # invalid; there is nothing to infer.
1586 raise InferenceError(
1587 "with_metaclass() call has no metaclass argument",
1588 node=self,
1589 context=context,
1590 )
1591 metaclass = next(call_args[0].infer(context), None)
1592 if isinstance(metaclass, ClassDef):
1593 class_bases = [_infer_last(x, context) for x in call_args[1:]]
1594 new_class = ClassDef(
1595 name="temporary_class",
1596 lineno=0,
1597 col_offset=0,
1598 end_lineno=0,
1599 end_col_offset=0,
1600 parent=SYNTHETIC_ROOT,
1601 )
1602 new_class.hide = True
1603 new_class.postinit(
1604 bases=[
1605 base
1606 for base in class_bases
1607 if not isinstance(base, util.UninferableBase)
1608 ],
1609 body=[],
1610 decorators=None,
1611 metaclass=metaclass,
1612 )
1613 yield new_class
1614 return
1615 returns = self._get_return_nodes_skip_functions()
1616
1617 first_return = next(returns, None)
1618 if not first_return:
1619 if protocols._is_stub_node(self) and self._is_stub_placeholder_body(
1620 self.body
1621 ):
1622 if self.returns is not None:
1623 yield from protocols.infer_instance_from_annotation(
1624 self.returns, ctx=context
1625 )
1626 else:
1627 yield util.Uninferable
1628 return
1629
1630 if self.body:
1631 # A body that is only ``...`` is a placeholder, like ``pass``:
1632 # it does not mean the function returns ``None``.
1633 if self._is_stub_placeholder_body(self.body) or self.is_abstract(
1634 pass_is_abstract=True, any_raise_is_abstract=True
1635 ):
1636 yield util.Uninferable
1637 else:
1638 yield node_classes.Const(None)
1639 return
1640
1641 # Builtin dunder methods have empty bodies, return Uninferable.
1642 if (
1643 len(self.body) == 0
1644 and self.name.startswith("__")
1645 and self.name.endswith("__")
1646 and self.root().qname() == "builtins"
1647 ):
1648 yield util.Uninferable
1649 return
1650
1651 raise InferenceError("The function does not have any return statements")
1652
1653 for returnnode in itertools.chain((first_return,), returns):
1654 if returnnode.value is None:
1655 yield node_classes.Const(None)
1656 else:
1657 try:
1658 yield from returnnode.value.infer(context)
1659 except InferenceError:
1660 yield util.Uninferable
1661
1662 def bool_value(self, context: InferenceContext | None = None) -> bool:
1663 """Determine the boolean value of this node.
1664
1665 :returns: The boolean value of this node.
1666 For a :class:`FunctionDef` this is always ``True``.
1667 """
1668 return True
1669
1670 def get_children(self):
1671 if self.decorators is not None:
1672 yield self.decorators
1673
1674 yield self.args
1675
1676 if self.returns is not None:
1677 yield self.returns
1678 yield from self.type_params
1679
1680 yield from self.body
1681
1682 def scope_lookup(
1683 self, node: LookupMixIn, name: str, offset: int = 0
1684 ) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
1685 """Lookup where the given name is assigned."""
1686 if name == "__class__":
1687 # __class__ is an implicit closure reference created by the compiler
1688 # if any methods in a class body refer to either __class__ or super.
1689 # In our case, we want to be able to look it up in the current scope
1690 # when `__class__` is being used.
1691 if self.parent and isinstance(frame := self.parent.frame(), ClassDef):
1692 return self, [frame]
1693
1694 if (self.args.defaults and node in self.args.defaults) or (
1695 self.args.kw_defaults and node in self.args.kw_defaults
1696 ):
1697 if not self.parent:
1698 raise ParentMissingError(target=self)
1699 frame = self.parent.frame()
1700 # line offset to avoid that def func(f=func) resolve the default
1701 # value to the defined function
1702 offset = -1
1703 else:
1704 # check this is not used in function decorators
1705 frame = self
1706 return frame._scope_lookup(node, name, offset)
1707
1708 def frame(self, *, future: Literal[None, True] = None) -> Self:
1709 """The node's frame node.
1710
1711 A frame node is a :class:`Module`, :class:`FunctionDef`,
1712 :class:`ClassDef` or :class:`Lambda`.
1713
1714 :returns: The node itself.
1715 """
1716 return self
1717
1718
1719class AsyncFunctionDef(FunctionDef):
1720 """Class representing an :class:`ast.FunctionDef` node.
1721
1722 A :class:`AsyncFunctionDef` is an asynchronous function
1723 created with the `async` keyword.
1724
1725 >>> import astroid
1726 >>> node = astroid.extract_node('''
1727 ... async def func(things):
1728 ... async for thing in things:
1729 ... print(thing)
1730 ... ''')
1731 >>> node
1732 <AsyncFunctionDef.func l.2 at 0x...>
1733 >>> node.body[0]
1734 <AsyncFor l.3 at 0x...>
1735 """
1736
1737
1738def _is_metaclass(
1739 klass: ClassDef,
1740 seen: set[str] | None = None,
1741 context: InferenceContext | None = None,
1742) -> bool:
1743 """Return if the given class can be
1744 used as a metaclass.
1745 """
1746 if klass.name == "type":
1747 return True
1748 if seen is None:
1749 seen = set()
1750 for base in klass.bases:
1751 try:
1752 for baseobj in base.infer(context=context):
1753 baseobj_name = baseobj.qname()
1754 if baseobj_name in seen:
1755 continue
1756
1757 seen.add(baseobj_name)
1758 if isinstance(baseobj, bases.Instance):
1759 # not abstract
1760 return False
1761 if baseobj is klass:
1762 continue
1763 if not isinstance(baseobj, ClassDef):
1764 continue
1765 if baseobj._type == "metaclass":
1766 return True
1767 if _is_metaclass(baseobj, seen, context=context):
1768 return True
1769 except InferenceError:
1770 continue
1771 return False
1772
1773
1774def _class_type(
1775 klass: ClassDef,
1776 ancestors: set[str] | None = None,
1777 context: InferenceContext | None = None,
1778) -> Literal["class", "exception", "metaclass"]:
1779 """return a ClassDef node type to differ metaclass and exception
1780 from 'regular' classes
1781 """
1782 # XXX we have to store ancestors in case we have an ancestor loop
1783 if klass._type is not None:
1784 return klass._type
1785 if _is_metaclass(klass, context=context):
1786 klass._type = "metaclass"
1787 elif klass.name.endswith("Exception"):
1788 klass._type = "exception"
1789 else:
1790 if ancestors is None:
1791 ancestors = set()
1792 klass_name = klass.qname()
1793 if klass_name in ancestors:
1794 # XXX we are in loop ancestors, and have found no type
1795 klass._type = "class"
1796 return "class"
1797 ancestors.add(klass_name)
1798 for base in klass.ancestors(recurs=False):
1799 name = _class_type(base, ancestors)
1800 if name != "class":
1801 if name == "metaclass" and klass._type != "metaclass":
1802 # don't propagate it if the current class
1803 # can't be a metaclass
1804 continue
1805 klass._type = base.type
1806 break
1807 if klass._type is None:
1808 klass._type = "class"
1809 return klass._type
1810
1811
1812def get_wrapping_class(node: NodeNG) -> ClassDef | None:
1813 """Get the class that wraps the given node.
1814
1815 We consider that a class wraps a node if the class
1816 is a parent for the said node.
1817
1818 :returns: The class that wraps the given node
1819 """
1820
1821 klass = node.frame()
1822 while klass is not None and not isinstance(klass, ClassDef):
1823 if klass.parent is None:
1824 klass = None
1825 else:
1826 klass = klass.parent.frame()
1827 return klass
1828
1829
1830class ClassDef(
1831 _base_nodes.FilterStmtsBaseNode, LocalsDictNodeNG, _base_nodes.Statement
1832):
1833 """Class representing an :class:`ast.ClassDef` node.
1834
1835 >>> import astroid
1836 >>> node = astroid.extract_node('''
1837 ... class Thing:
1838 ... def my_meth(self, arg):
1839 ... return arg + self.offset
1840 ... ''')
1841 >>> node
1842 <ClassDef.Thing l.2 at 0x...>
1843 """
1844
1845 # some of the attributes below are set by the builder module or
1846 # by a raw factories
1847
1848 # a dictionary of class instances attributes
1849 _astroid_fields = (
1850 "decorators",
1851 "bases",
1852 "keywords",
1853 "doc_node",
1854 "body",
1855 "type_params",
1856 ) # name
1857
1858 decorators: node_classes.Decorators | None = None
1859 """The decorators that are applied to this class."""
1860 special_attributes: ClassModel = ClassModel()
1861 """The names of special attributes that this class has."""
1862
1863 _type: Literal["class", "exception", "metaclass"] | None = None
1864 _metaclass: NodeNG | None = None
1865 _metaclass_hack = False
1866 hide = False
1867 type = property(
1868 _class_type,
1869 doc=(
1870 "The class type for this node.\n\n"
1871 "Possible values are: class, metaclass, exception."
1872 ),
1873 )
1874 _other_fields = ("name", "is_dataclass", "position")
1875 _other_other_fields = ("locals",)
1876
1877 def __init__(
1878 self,
1879 name: str,
1880 lineno: int,
1881 col_offset: int,
1882 parent: NodeNG,
1883 *,
1884 end_lineno: int | None,
1885 end_col_offset: int | None,
1886 ) -> None:
1887 self.instance_attrs: dict[str, list[InferenceResult]] = {}
1888 self.locals = {}
1889 """A map of the name of a local variable to the node defining it."""
1890
1891 self.keywords: list[node_classes.Keyword] = []
1892 """The keywords given to the class definition.
1893
1894 This is usually for :pep:`3115` style metaclass declaration.
1895 """
1896
1897 self.bases: list[SuccessfulInferenceResult] = []
1898 """What the class inherits from."""
1899
1900 self.body: list[NodeNG] = []
1901 """The contents of the class body."""
1902
1903 self.name = name
1904 """The name of the class."""
1905
1906 self.decorators = None
1907 """The decorators that are applied to this class."""
1908
1909 self.doc_node: Const | None = None
1910 """The doc node associated with this node."""
1911
1912 self.is_dataclass: bool = False
1913 """Whether this class is a dataclass."""
1914
1915 self.type_params: list[nodes.TypeVar | nodes.ParamSpec | nodes.TypeVarTuple] = (
1916 []
1917 )
1918 """The type parameters introduced by :pep:`695`, new in Python 3.12.
1919
1920 For example, the ``T`` in ``class MyClass[T]: ...``.
1921 """
1922
1923 super().__init__(
1924 lineno=lineno,
1925 col_offset=col_offset,
1926 end_lineno=end_lineno,
1927 end_col_offset=end_col_offset,
1928 parent=parent,
1929 )
1930 for local_name, node in self.implicit_locals():
1931 self.add_local_node(node, local_name)
1932
1933 infer_binary_op: ClassVar[InferBinaryOp[ClassDef]] = (
1934 protocols.instance_class_infer_binary_op
1935 )
1936
1937 def implicit_parameters(self) -> Literal[1]:
1938 return 1
1939
1940 def implicit_locals(self) -> tuple[tuple[str, NodeNG], ...]:
1941 """Get implicitly defined class definition locals.
1942
1943 :returns: the the name and Const pair for each local
1944 """
1945 locals_ = (("__module__", self.special_attributes.attr___module__),)
1946 # __qualname__ is defined in PEP3155
1947 locals_ += (
1948 ("__qualname__", self.special_attributes.attr___qualname__),
1949 ("__annotations__", self.special_attributes.attr___annotations__),
1950 )
1951 return locals_
1952
1953 # pylint: disable=redefined-outer-name
1954 def postinit(
1955 self,
1956 bases: list[SuccessfulInferenceResult],
1957 body: list[NodeNG],
1958 decorators: node_classes.Decorators | None,
1959 newstyle: bool | None = None,
1960 metaclass: NodeNG | None = None,
1961 keywords: list[node_classes.Keyword] | None = None,
1962 *,
1963 position: Position | None = None,
1964 doc_node: Const | None = None,
1965 type_params: (
1966 list[nodes.TypeVar | nodes.ParamSpec | nodes.TypeVarTuple] | None
1967 ) = None,
1968 ) -> None:
1969 if keywords is not None:
1970 self.keywords = keywords
1971 self.bases = bases
1972 self.body = body
1973 self.decorators = decorators
1974 self._metaclass = metaclass
1975 self.position = position
1976 self.doc_node = doc_node
1977 self.type_params = type_params or []
1978
1979 @cached_property
1980 def blockstart_tolineno(self) -> int:
1981 """The line on which the beginning of this block ends."""
1982 if self.bases:
1983 return self.bases[-1].tolineno
1984
1985 return self.fromlineno
1986
1987 def block_range(self, lineno: int) -> tuple[int, int]:
1988 """Get a range from the given line number to where this node ends.
1989
1990 :param lineno: Unused.
1991
1992 :returns: The range of line numbers that this node belongs to,
1993 """
1994 return self.fromlineno, self.tolineno
1995
1996 def pytype(self) -> Literal["builtins.type"]:
1997 """Get the name of the type that this node represents.
1998
1999 :returns: The name of the type.
2000 """
2001 return "builtins.type"
2002
2003 def display_type(self) -> str:
2004 """A human readable type of this node.
2005
2006 :returns: The type of this node.
2007 """
2008 return "Class"
2009
2010 def callable(self) -> bool:
2011 """Whether this node defines something that is callable.
2012
2013 :returns: Whether this defines something that is callable.
2014 For a :class:`ClassDef` this is always ``True``.
2015 """
2016 return True
2017
2018 def is_subtype_of(
2019 self, type_name: str, context: InferenceContext | None = None
2020 ) -> bool:
2021 """Whether this class is a subtype of the given type.
2022
2023 :param type_name: The name of the type of check against.
2024
2025 :returns: Whether this class is a subtype of the given type.
2026 """
2027 if self.qname() == type_name:
2028 return True
2029
2030 return any(anc.qname() == type_name for anc in self.ancestors(context=context))
2031
2032 def _infer_type_call(self, caller, context):
2033 try:
2034 name_node = next(caller.args[0].infer(context))
2035 except StopIteration as e:
2036 raise InferenceError(node=caller.args[0], context=context) from e
2037 if isinstance(name_node, node_classes.Const) and isinstance(
2038 name_node.value, str
2039 ):
2040 name = name_node.value
2041 else:
2042 return util.Uninferable
2043
2044 result = ClassDef(
2045 name,
2046 lineno=0,
2047 col_offset=0,
2048 end_lineno=0,
2049 end_col_offset=0,
2050 parent=caller.parent,
2051 )
2052
2053 # Get the bases of the class.
2054 try:
2055 class_bases = next(caller.args[1].infer(context))
2056 except StopIteration as e:
2057 raise InferenceError(node=caller.args[1], context=context) from e
2058 if isinstance(class_bases, (node_classes.Tuple, node_classes.List)):
2059 bases = []
2060 for base in class_bases.itered():
2061 inferred = next(base.infer(context=context), None)
2062 if inferred:
2063 bases.append(
2064 node_classes.EvaluatedObject(original=base, value=inferred)
2065 )
2066 result.bases = bases
2067 else:
2068 # There is currently no AST node that can represent an 'unknown'
2069 # node (Uninferable is not an AST node), therefore we simply return Uninferable here
2070 # although we know at least the name of the class.
2071 return util.Uninferable
2072
2073 # Get the members of the class
2074 try:
2075 members = next(caller.args[2].infer(context))
2076 except (InferenceError, StopIteration):
2077 members = None
2078
2079 if members and isinstance(members, node_classes.Dict):
2080 for attr, value in members.items:
2081 if isinstance(attr, node_classes.Const) and isinstance(attr.value, str):
2082 result.locals[attr.value] = [value]
2083
2084 return result
2085
2086 def infer_call_result(
2087 self,
2088 caller: SuccessfulInferenceResult | None,
2089 context: InferenceContext | None = None,
2090 ) -> Iterator[InferenceResult]:
2091 """infer what a class is returning when called"""
2092 if self.is_subtype_of("builtins.type", context) and len(caller.args) == 3:
2093 result = self._infer_type_call(caller, context)
2094 yield result
2095 return
2096
2097 dunder_call = None
2098 try:
2099 metaclass = self.metaclass(context=context)
2100 if metaclass is not None:
2101 # Only get __call__ if it's defined locally for the metaclass.
2102 # Otherwise we will find ObjectModel.__call__ which will
2103 # return an instance of the metaclass. Instantiating the class is
2104 # handled later.
2105 if "__call__" in metaclass.locals:
2106 dunder_call = next(metaclass.igetattr("__call__", context))
2107 except (AttributeInferenceError, StopIteration):
2108 pass
2109
2110 if dunder_call and dunder_call.qname() != "builtins.type.__call__":
2111 # Call type.__call__ if not set metaclass
2112 # (since type is the default metaclass)
2113 context = bind_context_to_node(context, self)
2114 # ``infer_call_result`` may be called through the public API without
2115 # a call context (it defaults to None); only annotate the callee
2116 # when there is a call context to annotate.
2117 if context.callcontext:
2118 context.callcontext.callee = dunder_call
2119 yield from dunder_call.infer_call_result(caller, context)
2120 else:
2121 yield self.instantiate_class()
2122
2123 def scope_lookup(
2124 self, node: LookupMixIn, name: str, offset: int = 0
2125 ) -> tuple[LocalsDictNodeNG, list[nodes.NodeNG]]:
2126 """Lookup where the given name is assigned.
2127
2128 :param node: The node to look for assignments up to.
2129 Any assignments after the given node are ignored.
2130
2131 :param name: The name to find assignments for.
2132
2133 :param offset: The line offset to filter statements up to.
2134
2135 :returns: This scope node and the list of assignments associated to the
2136 given name according to the scope where it has been found (locals,
2137 globals or builtin).
2138 """
2139 # If the name looks like a builtin name, just try to look
2140 # into the upper scope of this class. We might have a
2141 # decorator that it's poorly named after a builtin object
2142 # inside this class.
2143 lookup_upper_frame = (
2144 isinstance(node.parent, node_classes.Decorators)
2145 and name in AstroidManager().builtins_module
2146 )
2147 if (
2148 any(
2149 node == base or (base.parent_of(node) and not self.type_params)
2150 for base in self.bases
2151 )
2152 or lookup_upper_frame
2153 ):
2154 # Handle the case where we have either a name
2155 # in the bases of a class, which exists before
2156 # the actual definition or the case where we have
2157 # a Getattr node, with that name.
2158 #
2159 # name = ...
2160 # class A(name):
2161 # def name(self): ...
2162 #
2163 # import name
2164 # class A(name.Name):
2165 # def name(self): ...
2166 if not self.parent:
2167 raise ParentMissingError(target=self)
2168 frame = self.parent.frame()
2169 # line offset to avoid that class A(A) resolve the ancestor to
2170 # the defined class
2171 offset = -1
2172 else:
2173 frame = self
2174 return frame._scope_lookup(node, name, offset)
2175
2176 @property
2177 def basenames(self) -> list[str]:
2178 """The names of the parent classes
2179
2180 Names are given in the order they appear in the class definition.
2181 """
2182 return [bnode.as_string() for bnode in self.bases]
2183
2184 def ancestors(
2185 self, recurs: bool = True, context: InferenceContext | None = None
2186 ) -> Generator[ClassDef]:
2187 """Iterate over the base classes in prefixed depth first order.
2188
2189 :param recurs: Whether to recurse or return direct ancestors only.
2190
2191 :returns: The base classes
2192 """
2193 # FIXME: should be possible to choose the resolution order
2194 # FIXME: inference make infinite loops possible here
2195 yielded = {self}
2196 if context is None:
2197 context = InferenceContext()
2198 if not self.bases and self.qname() != "builtins.object":
2199 # This should always be a ClassDef (which we don't assert for)
2200 yield builtin_lookup("object")[1][0] # type: ignore[misc]
2201 return
2202
2203 for stmt in self.bases:
2204 with context.restore_path():
2205 try:
2206 for baseobj in stmt.infer(context):
2207 if not isinstance(baseobj, ClassDef):
2208 if isinstance(baseobj, bases.Instance):
2209 baseobj = baseobj._proxied
2210 else:
2211 continue
2212 if not baseobj.hide:
2213 if baseobj in yielded:
2214 continue
2215 yielded.add(baseobj)
2216 yield baseobj
2217 if not recurs:
2218 continue
2219 for grandpa in baseobj.ancestors(recurs=True, context=context):
2220 if grandpa is self:
2221 # This class is the ancestor of itself.
2222 break
2223 if grandpa in yielded:
2224 continue
2225 yielded.add(grandpa)
2226 yield grandpa
2227 except InferenceError:
2228 continue
2229
2230 def local_attr_ancestors(
2231 self, name: str, context: InferenceContext | None = None
2232 ) -> Generator[ClassDef]:
2233 """Iterate over the parents that define the given name.
2234
2235 :param name: The name to find definitions for.
2236
2237 :returns: The parents that define the given name.
2238 """
2239 # Look up in the mro if we can. This will result in the
2240 # attribute being looked up just as Python does it.
2241 try:
2242 ancestors: Iterable[ClassDef] = self.mro(context)[1:]
2243 except MroError:
2244 # Fallback to use ancestors, we can't determine
2245 # a sane MRO.
2246 ancestors = self.ancestors(context=context)
2247 for astroid in ancestors:
2248 if name in astroid:
2249 yield astroid
2250
2251 def instance_attr_ancestors(
2252 self, name: str, context: InferenceContext | None = None
2253 ) -> Generator[ClassDef]:
2254 """Iterate over the parents that define the given name as an attribute.
2255
2256 :param name: The name to find definitions for.
2257
2258 :returns: The parents that define the given name as
2259 an instance attribute.
2260 """
2261 for astroid in self.ancestors(context=context):
2262 if name in astroid.instance_attrs:
2263 yield astroid
2264
2265 def has_base(self, node: NodeNG) -> bool:
2266 """Whether this class directly inherits from the given node.
2267
2268 :param node: The node to check for.
2269
2270 :returns: Whether this class directly inherits from the given node.
2271 """
2272 return node in self.bases
2273
2274 def local_attr(
2275 self, name: str, context: InferenceContext | None = None
2276 ) -> list[InferenceResult]:
2277 """Get the list of assign nodes associated to the given name.
2278
2279 Assignments are looked for in both this class and in parents.
2280
2281 :returns: The list of assignments to the given name.
2282
2283 :raises AttributeInferenceError: If no attribute with this name
2284 can be found in this class or parent classes.
2285 """
2286 result = []
2287 if name in self.locals:
2288 result = self.locals[name]
2289 else:
2290 class_node = next(self.local_attr_ancestors(name, context), None)
2291 if class_node:
2292 result = class_node.locals[name]
2293 result = [n for n in result if not isinstance(n, node_classes.DelAttr)]
2294 if result:
2295 return result
2296 raise AttributeInferenceError(target=self, attribute=name, context=context)
2297
2298 def instance_attr(
2299 self, name: str, context: InferenceContext | None = None
2300 ) -> list[InferenceResult]:
2301 """Get the list of nodes associated to the given attribute name.
2302
2303 Assignments are looked for in both this class and in parents.
2304
2305 :returns: The list of assignments to the given name.
2306
2307 :raises AttributeInferenceError: If no attribute with this name
2308 can be found in this class or parent classes.
2309 """
2310 # Return a copy, so we don't modify self.instance_attrs,
2311 # which could lead to infinite loop.
2312 values = list(self.instance_attrs.get(name, []))
2313 # get all values from parents
2314 for class_node in self.instance_attr_ancestors(name, context):
2315 values += class_node.instance_attrs[name]
2316 values = [n for n in values if not isinstance(n, node_classes.DelAttr)]
2317 if values:
2318 return values
2319 raise AttributeInferenceError(target=self, attribute=name, context=context)
2320
2321 def instantiate_class(self) -> bases.Instance:
2322 """Get an :class:`~astroid.Instance` of the :class:`ClassDef` node.
2323
2324 :returns: An :class:`~astroid.Instance` of the :class:`ClassDef` node
2325 """
2326 from astroid import objects # pylint: disable=import-outside-toplevel
2327
2328 try:
2329 if any(cls.name in EXCEPTION_BASE_CLASSES for cls in self.mro()):
2330 # Subclasses of exceptions can be exception instances
2331 return objects.ExceptionInstance(self)
2332 except MroError:
2333 pass
2334 return bases.Instance(self)
2335
2336 def getattr(
2337 self,
2338 name: str,
2339 context: InferenceContext | None = None,
2340 class_context: bool = True,
2341 ) -> list[InferenceResult]:
2342 """Get an attribute from this class, using Python's attribute semantic.
2343
2344 This method doesn't look in the ``instance_attrs`` dictionary
2345 since it is done by an :class:`~astroid.Instance` proxy at inference time.
2346 It may return an :obj:`~astroid.Uninferable` object if
2347 the attribute has not been
2348 found, but a ``__getattr__`` or ``__getattribute__`` method is defined.
2349 If ``class_context`` is given, then it is considered that the
2350 attribute is accessed from a class context,
2351 e.g. ClassDef.attribute, otherwise it might have been accessed
2352 from an instance as well. If ``class_context`` is used in that
2353 case, then a lookup in the implicit metaclass and the explicit
2354 metaclass will be done.
2355
2356 :param name: The attribute to look for.
2357
2358 :param class_context: Whether the attribute can be accessed statically.
2359
2360 :returns: The attribute.
2361
2362 :raises AttributeInferenceError: If the attribute cannot be inferred.
2363 """
2364 if not name:
2365 raise AttributeInferenceError(target=self, attribute=name, context=context)
2366
2367 # don't modify the list in self.locals!
2368 values: list[InferenceResult] = list(self.locals.get(name, []))
2369 for classnode in self.ancestors(recurs=True, context=context):
2370 values += classnode.locals.get(name, [])
2371
2372 if name in self.special_attributes and class_context and not values:
2373 special_attr = self.special_attributes.lookup(name)
2374 if not isinstance(special_attr, node_classes.Unknown):
2375 result = [special_attr]
2376 return result
2377
2378 if class_context:
2379 values += self._metaclass_lookup_attribute(name, context)
2380
2381 result: list[InferenceResult] = []
2382 for value in values:
2383 if isinstance(value, node_classes.AssignName):
2384 stmt = value.statement()
2385 if (
2386 isinstance(stmt, node_classes.AnnAssign)
2387 and stmt.value is None
2388 and not protocols._is_stub_node(stmt)
2389 ):
2390 continue
2391 result.append(value)
2392
2393 if not result:
2394 raise AttributeInferenceError(target=self, attribute=name, context=context)
2395
2396 return result
2397
2398 @lru_cache(maxsize=1024) # noqa
2399 def _metaclass_lookup_attribute(self, name, context):
2400 """Search the given name in the implicit and the explicit metaclass."""
2401 attrs = set()
2402 implicit_meta = self.implicit_metaclass()
2403 context = copy_context(context)
2404 metaclass = self.metaclass(context=context)
2405 for cls in (implicit_meta, metaclass):
2406 if cls and cls != self and isinstance(cls, ClassDef):
2407 cls_attributes = self._get_attribute_from_metaclass(cls, name, context)
2408 attrs.update(cls_attributes)
2409 return attrs
2410
2411 def _get_attribute_from_metaclass(self, cls, name, context):
2412 from astroid import objects # pylint: disable=import-outside-toplevel
2413
2414 try:
2415 attrs = cls.getattr(name, context=context, class_context=True)
2416 except AttributeInferenceError:
2417 return
2418
2419 for attr in bases._infer_stmts(attrs, context, frame=cls):
2420 if not isinstance(attr, FunctionDef):
2421 yield attr
2422 continue
2423
2424 if isinstance(attr, objects.Property):
2425 yield attr
2426 continue
2427 if attr.type == "classmethod":
2428 # If the method is a classmethod, then it will
2429 # be bound to the metaclass, not to the class
2430 # from where the attribute is retrieved.
2431 # get_wrapping_class could return None, so just
2432 # default to the current class.
2433 frame = get_wrapping_class(attr) or self
2434 yield bases.BoundMethod(attr, frame)
2435 elif attr.type == "staticmethod":
2436 yield attr
2437 else:
2438 yield bases.BoundMethod(attr, self)
2439
2440 def igetattr(
2441 self,
2442 name: str,
2443 context: InferenceContext | None = None,
2444 class_context: bool = True,
2445 ) -> Iterator[InferenceResult]:
2446 """Infer the possible values of the given variable.
2447
2448 :param name: The name of the variable to infer.
2449
2450 :returns: The inferred possible values.
2451 """
2452 from astroid import objects # pylint: disable=import-outside-toplevel
2453
2454 # set lookup name since this is necessary to infer on import nodes for
2455 # instance
2456 context = copy_context(context)
2457 context.lookupname = name
2458
2459 metaclass = self.metaclass(context=context)
2460 try:
2461 attributes = self.getattr(name, context, class_context=class_context)
2462 # If we have more than one attribute, make sure that those starting from
2463 # the second one are from the same scope. This is to account for modifications
2464 # to the attribute happening *after* the attribute's definition (e.g. AugAssigns on lists)
2465 if len(attributes) > 1:
2466 first_attr, attributes = attributes[0], attributes[1:]
2467 first_scope = first_attr.parent.scope()
2468 attributes = [first_attr] + [
2469 attr
2470 for attr in attributes
2471 if attr.parent and attr.parent.scope() == first_scope
2472 ]
2473 functions = [attr for attr in attributes if isinstance(attr, FunctionDef)]
2474 setter = None
2475 for function in functions:
2476 dec_names = function.decoratornames(context=context)
2477 for dec_name in dec_names:
2478 if dec_name is util.Uninferable:
2479 continue
2480 if dec_name.split(".")[-1] == "setter":
2481 setter = function
2482 if setter:
2483 break
2484 if functions:
2485 # Prefer only the last function, unless a property is involved.
2486 last_function = functions[-1]
2487 attributes = [
2488 a
2489 for a in attributes
2490 if a not in functions or a is last_function or bases._is_property(a)
2491 ]
2492
2493 for inferred in bases._infer_stmts(attributes, context, frame=self):
2494 # yield Uninferable object instead of descriptors when necessary
2495 if not isinstance(inferred, node_classes.Const) and isinstance(
2496 inferred, bases.Instance
2497 ):
2498 try:
2499 inferred._proxied.getattr("__get__", context)
2500 except AttributeInferenceError:
2501 yield inferred
2502 else:
2503 yield util.Uninferable
2504 elif isinstance(inferred, objects.Property):
2505 function = inferred.function
2506 if not class_context:
2507 if not context.callcontext and not setter:
2508 context.callcontext = CallContext(
2509 args=function.args.arguments, callee=function
2510 )
2511 # Through an instance so we can solve the property
2512 yield from function.infer_call_result(
2513 caller=self, context=context
2514 )
2515 # If we're in a class context, we need to determine if the property
2516 # was defined in the metaclass (a derived class must be a subclass of
2517 # the metaclass of all its bases), in which case we can resolve the
2518 # property. If not, i.e. the property is defined in some base class
2519 # instead, then we return the property object
2520 elif metaclass and function.parent.scope() is metaclass:
2521 # Resolve a property as long as it is not accessed through
2522 # the class itself.
2523 yield from function.infer_call_result(
2524 caller=self, context=context
2525 )
2526 else:
2527 yield inferred
2528 else:
2529 yield function_to_method(inferred, self)
2530 except AttributeInferenceError as error:
2531 if not name.startswith("__") and self.has_dynamic_getattr(context):
2532 # class handle some dynamic attributes, return a Uninferable object
2533 yield util.Uninferable
2534 else:
2535 raise InferenceError(
2536 str(error), target=self, attribute=name, context=context
2537 ) from error
2538
2539 def has_dynamic_getattr(self, context: InferenceContext | None = None) -> bool:
2540 """Check if the class has a custom __getattr__ or __getattribute__.
2541
2542 If any such method is found and it is not from
2543 builtins, nor from an extension module, then the function
2544 will return True.
2545
2546 :returns: Whether the class has a custom __getattr__ or __getattribute__.
2547 """
2548
2549 def _valid_getattr(node):
2550 root = node.root()
2551 return root.name != "builtins" and getattr(root, "pure_python", None)
2552
2553 try:
2554 return _valid_getattr(self.getattr("__getattr__", context)[0])
2555 except AttributeInferenceError:
2556 try:
2557 getattribute = self.getattr("__getattribute__", context)[0]
2558 return _valid_getattr(getattribute)
2559 except AttributeInferenceError:
2560 pass
2561 return False
2562
2563 def getitem(
2564 self, index: SuccessfulInferenceResult, context: InferenceContext | None = None
2565 ) -> InferenceResult:
2566 """Return the inference of a subscript.
2567
2568 This is basically looking up the method in the metaclass and calling it.
2569
2570 :returns: The inferred value of a subscript to this class.
2571
2572 :raises AstroidTypeError: If this class does not define a
2573 ``__getitem__`` method.
2574 """
2575 try:
2576 methods = lookup(self, "__getitem__", context=context)
2577 except AttributeInferenceError as exc:
2578 if isinstance(self, ClassDef):
2579 # subscripting a class definition may be
2580 # achieved thanks to __class_getitem__ method
2581 # which is a classmethod defined in the class
2582 # that supports subscript and not in the metaclass
2583 try:
2584 methods = self.getattr("__class_getitem__")
2585 # Here it is assumed that the __class_getitem__ node is
2586 # a FunctionDef. One possible improvement would be to deal
2587 # with more generic inference.
2588 except AttributeInferenceError:
2589 raise AstroidTypeError(node=self, context=context) from exc
2590 else:
2591 raise AstroidTypeError(node=self, context=context) from exc
2592
2593 method = methods[0]
2594
2595 if isinstance(method, util.UninferableBase):
2596 return util.Uninferable
2597
2598 # Create a new callcontext for providing index as an argument.
2599 new_context = bind_context_to_node(context, self)
2600 new_context.callcontext = CallContext(args=[index], callee=method)
2601
2602 try:
2603 return next(method.infer_call_result(self, new_context), util.Uninferable)
2604 except AttributeError as exc:
2605 # Starting with python3.9, builtin types list, dict etc...
2606 # are subscriptable thanks to __class_getitem___ classmethod.
2607 # However in such case the method is bound to an EmptyNode and
2608 # EmptyNode doesn't have infer_call_result method yielding to
2609 # AttributeError
2610 if (
2611 isinstance(method, node_classes.EmptyNode)
2612 and self.pytype() == "builtins.type"
2613 ):
2614 return self
2615 # ``__class_getitem__`` may resolve to a non-callable node (e.g. an
2616 # ``AssignName`` or an ``Import``), which has no
2617 # ``infer_call_result`` method.
2618 if not method.callable():
2619 raise AstroidTypeError(node=self, context=context) from exc
2620 raise
2621 except InferenceError:
2622 return util.Uninferable
2623
2624 def methods(self) -> Iterator[FunctionDef]:
2625 """Iterate over all of the method defined in this class and its parents.
2626
2627 :returns: The methods defined on the class.
2628 """
2629 done = {}
2630 for astroid in itertools.chain(iter((self,)), self.ancestors()):
2631 for meth in astroid.mymethods():
2632 if meth.name in done:
2633 continue
2634 done[meth.name] = None
2635 yield meth
2636
2637 def mymethods(self) -> Iterator[FunctionDef]:
2638 """Iterate over all of the method defined in this class only.
2639
2640 :returns: The methods defined on the class.
2641 """
2642 for member in self.values():
2643 if isinstance(member, FunctionDef):
2644 yield member
2645
2646 def implicit_metaclass(self) -> NodeNG:
2647 """Get the implicit metaclass of the current class.
2648
2649 This will return an instance of builtins.type.
2650
2651 :returns: The metaclass.
2652 """
2653 return builtin_lookup("type")[1][0]
2654
2655 def declared_metaclass(
2656 self, context: InferenceContext | None = None
2657 ) -> SuccessfulInferenceResult | None:
2658 """Return the explicit declared metaclass for the current class.
2659
2660 An explicit declared metaclass is defined by passing the
2661 ``metaclass`` keyword argument in the class definition line.
2662
2663 :returns: The metaclass of this class,
2664 or None if one could not be found.
2665 """
2666 for base in self.bases:
2667 try:
2668 for baseobj in base.infer(context=context):
2669 if isinstance(baseobj, ClassDef) and baseobj.hide:
2670 self._metaclass = baseobj._metaclass
2671 self._metaclass_hack = True
2672 break
2673 except InferenceError:
2674 pass
2675
2676 if self._metaclass:
2677 try:
2678 return next(
2679 node
2680 for node in self._metaclass.infer(context=context)
2681 if not isinstance(node, util.UninferableBase)
2682 )
2683 except (InferenceError, StopIteration):
2684 return None
2685
2686 return None
2687
2688 def _find_metaclass(
2689 self, seen: set[ClassDef] | None = None, context: InferenceContext | None = None
2690 ) -> SuccessfulInferenceResult | None:
2691 if seen is None:
2692 seen = set()
2693 seen.add(self)
2694
2695 klass = self.declared_metaclass(context=context)
2696 if klass is None:
2697 for parent in self.ancestors(context=context):
2698 if parent not in seen:
2699 klass = parent._find_metaclass(seen)
2700 if klass is not None:
2701 break
2702 return klass
2703
2704 def metaclass(
2705 self, context: InferenceContext | None = None
2706 ) -> SuccessfulInferenceResult | None:
2707 """Get the metaclass of this class.
2708
2709 If this class does not define explicitly a metaclass,
2710 then the first defined metaclass in ancestors will be used
2711 instead.
2712
2713 :returns: The metaclass of this class.
2714 """
2715 return self._find_metaclass(context=context)
2716
2717 def has_metaclass_hack(self) -> bool:
2718 return self._metaclass_hack
2719
2720 def _islots(self):
2721 """Return an iterator with the inferred slots."""
2722 if "__slots__" not in self.locals:
2723 return None
2724 try:
2725 slots_attributes = list(self.igetattr("__slots__"))
2726 except InferenceError:
2727 # ``__slots__`` is present in ``locals`` but cannot be inferred,
2728 # e.g. an annotation-only ``__slots__: ...`` with no assigned value.
2729 return None
2730 for slots in slots_attributes:
2731 # check if __slots__ is a valid type
2732 if not hasattr(slots, "getattr"):
2733 continue
2734 for meth in ITER_METHODS:
2735 try:
2736 slots.getattr(meth)
2737 break
2738 except AttributeInferenceError:
2739 continue
2740 else:
2741 continue
2742
2743 if isinstance(slots, node_classes.Const):
2744 # a string. Ignore the following checks,
2745 # but yield the node, only if it has a value
2746 if slots.value:
2747 yield slots
2748 continue
2749 if not hasattr(slots, "itered"):
2750 # we can't obtain the values, maybe a .deque?
2751 continue
2752
2753 if isinstance(slots, node_classes.Dict):
2754 values = [item[0] for item in slots.items]
2755 else:
2756 values = slots.itered()
2757 if isinstance(values, util.UninferableBase):
2758 continue
2759 if not values:
2760 # Stop the iteration, because the class
2761 # has an empty list of slots.
2762 return values
2763
2764 for elt in values:
2765 try:
2766 for inferred in elt.infer():
2767 if not (
2768 isinstance(inferred, node_classes.Const)
2769 and isinstance(inferred.value, str)
2770 ):
2771 continue
2772 if not inferred.value:
2773 continue
2774 yield inferred
2775 except InferenceError:
2776 continue
2777
2778 return None
2779
2780 def _slots(self):
2781
2782 slots = self._islots()
2783 try:
2784 first = next(slots)
2785 except StopIteration as exc:
2786 # The class doesn't have a __slots__ definition or empty slots.
2787 if exc.args and exc.args[0] not in ("", None):
2788 return exc.args[0]
2789 return None
2790 return [first, *slots]
2791
2792 # Cached, because inferring them all the time is expensive
2793 @cached_property
2794 def _all_slots(self) -> list[node_classes.Const] | None:
2795 """Get all the slots for this node.
2796
2797 :returns: The names of slots for this class.
2798 If the class doesn't define any slot, through the ``__slots__``
2799 variable, then this function will return a None.
2800 Also, it will return None in the case the slots were not inferred.
2801 """
2802
2803 def grouped_slots(
2804 mro: list[ClassDef],
2805 ) -> Iterator[node_classes.NodeNG | None]:
2806 for cls in mro:
2807 # Not interested in object, since it can't have slots.
2808 if cls.qname() == "builtins.object":
2809 continue
2810 try:
2811 cls_slots = cls._slots()
2812 except NotImplementedError:
2813 continue
2814 if cls_slots is not None:
2815 yield from cls_slots
2816 else:
2817 yield None
2818
2819 try:
2820 mro = self.mro()
2821 except MroError as e:
2822 raise NotImplementedError(
2823 "Cannot get slots while parsing mro fails."
2824 ) from e
2825
2826 slots = list(grouped_slots(mro))
2827 if not all(slot is not None for slot in slots):
2828 return None
2829
2830 return sorted(set(slots), key=lambda item: item.value)
2831
2832 def slots(self):
2833 return self._all_slots
2834
2835 def _inferred_bases(
2836 self,
2837 context: InferenceContext | None = None,
2838 *,
2839 base_classes: frozenset[ClassDef] = frozenset(),
2840 ):
2841 # Similar with .ancestors, but the difference is when one base is inferred,
2842 # only the first object is wanted. That's because
2843 # we aren't interested in superclasses, as in the following
2844 # example:
2845 #
2846 # class SomeSuperClass(object): pass
2847 # class SomeClass(SomeSuperClass): pass
2848 # class Test(SomeClass): pass
2849 #
2850 # Inferring SomeClass from the Test's bases will give
2851 # us both SomeClass and SomeSuperClass, but we are interested
2852 # only in SomeClass.
2853
2854 if context is None:
2855 context = InferenceContext()
2856 if not self.bases and self.qname() != "builtins.object":
2857 yield builtin_lookup("object")[1][0]
2858 return
2859
2860 for stmt in self.bases:
2861 try:
2862 baseobj = _infer_last(stmt, context)
2863 except InferenceError:
2864 continue
2865 if isinstance(baseobj, bases.Instance):
2866 baseobj = baseobj._proxied
2867 if not isinstance(baseobj, ClassDef):
2868 continue
2869 if baseobj is self or baseobj in base_classes:
2870 # Circular base due to name rebinding (e.g. pdb.Pdb = CustomPdb
2871 # where CustomPdb inherits from pdb.Pdb). Fall back to the
2872 # first non-circular inferred value from the base expression.
2873 baseobj = self._resolve_circular_base(stmt, context)
2874 if baseobj is None:
2875 continue
2876 if not baseobj.hide:
2877 yield baseobj
2878 else:
2879 yield from baseobj.bases
2880
2881 def _resolve_circular_base(
2882 self,
2883 stmt: nodes.NodeNG,
2884 context: InferenceContext | None,
2885 ) -> ClassDef | None:
2886 """Resolve a circular base reference by finding the original class.
2887
2888 When a name is rebound to a subclass (e.g. ``pdb.Pdb = CustomPdb``),
2889 ``_infer_last`` follows the rebinding and returns the subclass itself.
2890 This method iterates through all inferred values to find the first
2891 non-circular ClassDef.
2892 """
2893 inf_context = copy_context(context)
2894 try:
2895 for inferred in stmt.infer(context=inf_context):
2896 if isinstance(inferred, bases.Instance):
2897 inferred = inferred._proxied
2898 if isinstance(inferred, ClassDef) and inferred is not self:
2899 return inferred
2900 except InferenceError:
2901 pass
2902 return None
2903
2904 def _compute_mro(
2905 self,
2906 context: InferenceContext,
2907 *,
2908 base_chain: frozenset[ClassDef] = frozenset(),
2909 ):
2910 if self.qname() == "builtins.object":
2911 return [self]
2912
2913 inferred_bases = list(
2914 self._inferred_bases(context=context, base_classes=base_chain)
2915 )
2916 bases_mro = []
2917 base_chain |= {self}
2918 for base in inferred_bases:
2919 if base in base_chain:
2920 continue
2921
2922 mro = base._compute_mro(context=context, base_chain=base_chain)
2923 bases_mro.append(mro)
2924
2925 unmerged_mro: list[list[ClassDef]] = [[self], *bases_mro, inferred_bases]
2926 unmerged_mro = clean_duplicates_mro(unmerged_mro, self, context)
2927 clean_typing_generic_mro(unmerged_mro)
2928 return _c3_merge(unmerged_mro, self, context)
2929
2930 def mro(self, context: InferenceContext | None = None) -> list[ClassDef]:
2931 """Get the method resolution order, using C3 linearization.
2932
2933 :returns: The list of ancestors, sorted by the mro.
2934 :raises DuplicateBasesError: Duplicate bases in the same class base
2935 :raises InconsistentMroError: A class' MRO is inconsistent
2936 """
2937 return self._compute_mro(context=context)
2938
2939 def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
2940 """Determine the boolean value of this node.
2941
2942 :returns: The boolean value of this node.
2943 For a :class:`ClassDef` this is always ``True``.
2944 """
2945 return True
2946
2947 def get_children(self):
2948 if self.decorators is not None:
2949 yield self.decorators
2950
2951 yield from self.bases
2952 if self.keywords is not None:
2953 yield from self.keywords
2954 yield from self.type_params
2955
2956 yield from self.body
2957
2958 @cached_property
2959 def _assign_nodes_in_scope(self):
2960 children_assign_nodes = (
2961 child_node._assign_nodes_in_scope for child_node in self.body
2962 )
2963 return list(itertools.chain.from_iterable(children_assign_nodes))
2964
2965 def frame(self, *, future: Literal[None, True] = None) -> Self:
2966 """The node's frame node.
2967
2968 A frame node is a :class:`Module`, :class:`FunctionDef`,
2969 :class:`ClassDef` or :class:`Lambda`.
2970
2971 :returns: The node itself.
2972 """
2973 return self
2974
2975 def _infer(self, context: InferenceContext | None = None) -> Generator[ClassDef]:
2976 yield self