-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathscoped_nodes.py
2904 lines (2427 loc) · 98.5 KB
/
scoped_nodes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
"""
This module contains the classes for "scoped" node, i.e. which are opening a
new local scope in the language definition : Module, ClassDef, FunctionDef (and
Lambda, GeneratorExp, DictComp and SetComp to some extent).
"""
from __future__ import annotations
import io
import itertools
import os
import warnings
from collections.abc import Generator, Iterable, Iterator, Sequence
from functools import cached_property, lru_cache
from typing import TYPE_CHECKING, Any, ClassVar, Literal, NoReturn, TypeVar
from astroid import bases, protocols, util
from astroid.context import (
CallContext,
InferenceContext,
bind_context_to_node,
copy_context,
)
from astroid.exceptions import (
AstroidBuildingError,
AstroidTypeError,
AttributeInferenceError,
DuplicateBasesError,
InconsistentMroError,
InferenceError,
MroError,
ParentMissingError,
StatementMissing,
TooManyLevelsError,
)
from astroid.interpreter.dunder_lookup import lookup
from astroid.interpreter.objectmodel import ClassModel, FunctionModel, ModuleModel
from astroid.manager import AstroidManager
from astroid.nodes import _base_nodes, node_classes
from astroid.nodes.scoped_nodes.mixin import ComprehensionScope, LocalsDictNodeNG
from astroid.nodes.scoped_nodes.utils import builtin_lookup
from astroid.nodes.utils import Position
from astroid.typing import (
InferBinaryOp,
InferenceErrorInfo,
InferenceResult,
SuccessfulInferenceResult,
)
if TYPE_CHECKING:
from astroid import nodes, objects
from astroid.nodes import Arguments, Const, NodeNG
from astroid.nodes._base_nodes import LookupMixIn
ITER_METHODS = ("__iter__", "__getitem__")
EXCEPTION_BASE_CLASSES = frozenset({"Exception", "BaseException"})
BUILTIN_DESCRIPTORS = frozenset(
{"classmethod", "staticmethod", "builtins.classmethod", "builtins.staticmethod"}
)
_T = TypeVar("_T")
def _c3_merge(sequences, cls, context):
"""Merges MROs in *sequences* to a single MRO using the C3 algorithm.
Adapted from http://www.python.org/download/releases/2.3/mro/.
"""
result = []
while True:
sequences = [s for s in sequences if s] # purge empty sequences
if not sequences:
return result
for s1 in sequences: # find merge candidates among seq heads
candidate = s1[0]
for s2 in sequences:
if candidate in s2[1:]:
candidate = None
break # reject the current head, it appears later
else:
break
if not candidate:
# Show all the remaining bases, which were considered as
# candidates for the next mro sequence.
raise InconsistentMroError(
message="Cannot create a consistent method resolution order "
"for MROs {mros} of class {cls!r}.",
mros=sequences,
cls=cls,
context=context,
)
result.append(candidate)
# remove the chosen candidate
for seq in sequences:
if seq[0] == candidate:
del seq[0]
return None
def clean_typing_generic_mro(sequences: list[list[ClassDef]]) -> None:
"""A class can inherit from typing.Generic directly, as base,
and as base of bases. The merged MRO must however only contain the last entry.
To prepare for _c3_merge, remove some typing.Generic entries from
sequences if multiple are present.
This method will check if Generic is in inferred_bases and also
part of bases_mro. If true, remove it from inferred_bases
as well as its entry the bases_mro.
Format sequences: [[self]] + bases_mro + [inferred_bases]
"""
bases_mro = sequences[1:-1]
inferred_bases = sequences[-1]
# Check if Generic is part of inferred_bases
for i, base in enumerate(inferred_bases):
if base.qname() == "typing.Generic":
position_in_inferred_bases = i
break
else:
return
# Check if also part of bases_mro
# Ignore entry for typing.Generic
for i, seq in enumerate(bases_mro):
if i == position_in_inferred_bases:
continue
if any(base.qname() == "typing.Generic" for base in seq):
break
else:
return
# Found multiple Generics in mro, remove entry from inferred_bases
# and the corresponding one from bases_mro
inferred_bases.pop(position_in_inferred_bases)
bases_mro.pop(position_in_inferred_bases)
def clean_duplicates_mro(
sequences: list[list[ClassDef]],
cls: ClassDef,
context: InferenceContext | None,
) -> list[list[ClassDef]]:
for sequence in sequences:
seen = set()
for node in sequence:
lineno_and_qname = (node.lineno, node.qname())
if lineno_and_qname in seen:
raise DuplicateBasesError(
message="Duplicates found in MROs {mros} for {cls!r}.",
mros=sequences,
cls=cls,
context=context,
)
seen.add(lineno_and_qname)
return sequences
def function_to_method(n, klass):
if isinstance(n, FunctionDef):
if n.type == "classmethod":
return bases.BoundMethod(n, klass)
if n.type == "property":
return n
if n.type != "staticmethod":
return bases.UnboundMethod(n)
return n
def _infer_last(
arg: SuccessfulInferenceResult, context: InferenceContext
) -> InferenceResult:
res = util.Uninferable
for b in arg.infer(context=context.clone()):
res = b
return res
class Module(LocalsDictNodeNG):
"""Class representing an :class:`ast.Module` node.
>>> import astroid
>>> node = astroid.extract_node('import astroid')
>>> node
<Import l.1 at 0x7f23b2e4e5c0>
>>> node.parent
<Module l.0 at 0x7f23b2e4eda0>
"""
_astroid_fields = ("doc_node", "body")
doc_node: Const | None
"""The doc node associated with this node."""
# attributes below are set by the builder module or by raw factories
file_bytes: str | bytes | None = None
"""The string/bytes that this ast was built from."""
file_encoding: str | None = None
"""The encoding of the source file.
This is used to get unicode out of a source file.
Python 2 only.
"""
special_attributes = ModuleModel()
"""The names of special attributes that this module has."""
# names of module attributes available through the global scope
scope_attrs: ClassVar[set[str]] = {
"__name__",
"__doc__",
"__file__",
"__path__",
"__package__",
}
"""The names of module attributes available through the global scope."""
_other_fields = (
"name",
"file",
"path",
"package",
"pure_python",
"future_imports",
)
_other_other_fields = ("locals", "globals")
def __init__(
self,
name: str,
file: str | None = None,
path: Sequence[str] | None = None,
package: bool = False,
pure_python: bool = True,
) -> None:
self.name = name
"""The name of the module."""
self.file = file
"""The path to the file that this ast has been extracted from.
This will be ``None`` when the representation has been built from a
built-in module.
"""
self.path = path
self.package = package
"""Whether the node represents a package or a module."""
self.pure_python = pure_python
"""Whether the ast was built from source."""
self.globals: dict[str, list[InferenceResult]]
"""A map of the name of a global variable to the node defining the global."""
self.locals = self.globals = {}
"""A map of the name of a local variable to the node defining the local."""
self.body: list[node_classes.NodeNG] = []
"""The contents of the module."""
self.future_imports: set[str] = set()
"""The imports from ``__future__``."""
super().__init__(
lineno=0, parent=None, col_offset=0, end_lineno=None, end_col_offset=None
)
# pylint: enable=redefined-builtin
def postinit(
self, body: list[node_classes.NodeNG], *, doc_node: Const | None = None
):
self.body = body
self.doc_node = doc_node
def _get_stream(self):
if self.file_bytes is not None:
return io.BytesIO(self.file_bytes)
if self.file is not None:
# pylint: disable=consider-using-with
stream = open(self.file, "rb")
return stream
return None
def stream(self):
"""Get a stream to the underlying file or bytes.
:type: file or io.BytesIO or None
"""
return self._get_stream()
def block_range(self, lineno: int) -> tuple[int, int]:
"""Get a range from where this node starts to where this node ends.
:param lineno: Unused.
:returns: The range of line numbers that this node belongs to.
"""
return self.fromlineno, self.tolineno
def scope_lookup(
self, node: LookupMixIn, name: str, offset: int = 0
) -> tuple[LocalsDictNodeNG, list[node_classes.NodeNG]]:
"""Lookup where the given variable is assigned.
:param node: The node to look for assignments up to.
Any assignments after the given node are ignored.
:param name: The name of the variable to find assignments for.
:param offset: The line offset to filter statements up to.
:returns: This scope node and the list of assignments associated to the
given name according to the scope where it has been found (locals,
globals or builtin).
"""
if name in self.scope_attrs and name not in self.locals:
try:
return self, self.getattr(name)
except AttributeInferenceError:
return self, []
return self._scope_lookup(node, name, offset)
def pytype(self) -> Literal["builtins.module"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
"""
return "builtins.module"
def display_type(self) -> str:
"""A human readable type of this node.
:returns: The type of this node.
:rtype: str
"""
return "Module"
def getattr(
self, name, context: InferenceContext | None = None, ignore_locals=False
):
if not name:
raise AttributeInferenceError(target=self, attribute=name, context=context)
result = []
name_in_locals = name in self.locals
if name in self.special_attributes and not ignore_locals and not name_in_locals:
result = [self.special_attributes.lookup(name)]
if name == "__name__":
main_const = node_classes.const_factory("__main__")
main_const.parent = AstroidManager().builtins_module
result.append(main_const)
elif not ignore_locals and name_in_locals:
result = self.locals[name]
elif self.package:
try:
result = [self.import_module(name, relative_only=True)]
except (AstroidBuildingError, SyntaxError) as exc:
raise AttributeInferenceError(
target=self, attribute=name, context=context
) from exc
result = [n for n in result if not isinstance(n, node_classes.DelName)]
if result:
return result
raise AttributeInferenceError(target=self, attribute=name, context=context)
def igetattr(
self, name: str, context: InferenceContext | None = None
) -> Iterator[InferenceResult]:
"""Infer the possible values of the given variable.
:param name: The name of the variable to infer.
:returns: The inferred possible values.
"""
# set lookup name since this is necessary to infer on import nodes for
# instance
context = copy_context(context)
context.lookupname = name
try:
return bases._infer_stmts(self.getattr(name, context), context, frame=self)
except AttributeInferenceError as error:
raise InferenceError(
str(error), target=self, attribute=name, context=context
) from error
def fully_defined(self) -> bool:
"""Check if this module has been build from a .py file.
If so, the module contains a complete representation,
including the code.
:returns: Whether the module has been built from a .py file.
"""
return self.file is not None and self.file.endswith(".py")
def statement(self, *, future: Literal[None, True] = None) -> NoReturn:
"""The first parent node, including self, marked as statement node.
When called on a :class:`Module` this raises a StatementMissing.
"""
if future is not None:
warnings.warn(
"The future arg will be removed in astroid 4.0.",
DeprecationWarning,
stacklevel=2,
)
raise StatementMissing(target=self)
def previous_sibling(self):
"""The previous sibling statement.
:returns: The previous sibling statement node.
:rtype: NodeNG or None
"""
def next_sibling(self):
"""The next sibling statement node.
:returns: The next sibling statement node.
:rtype: NodeNG or None
"""
_absolute_import_activated = True
def absolute_import_activated(self) -> bool:
"""Whether :pep:`328` absolute import behaviour has been enabled.
:returns: Whether :pep:`328` has been enabled.
"""
return self._absolute_import_activated
def import_module(
self,
modname: str,
relative_only: bool = False,
level: int | None = None,
use_cache: bool = True,
) -> Module:
"""Get the ast for a given module as if imported from this module.
:param modname: The name of the module to "import".
:param relative_only: Whether to only consider relative imports.
:param level: The level of relative import.
:param use_cache: Whether to use the astroid_cache of modules.
:returns: The imported module ast.
"""
if relative_only and level is None:
level = 0
absmodname = self.relative_to_absolute_name(modname, level)
try:
return AstroidManager().ast_from_module_name(
absmodname, use_cache=use_cache
)
except AstroidBuildingError:
# we only want to import a sub module or package of this module,
# skip here
if relative_only:
raise
# Don't repeat the same operation, e.g. for missing modules
# like "_winapi" or "nt" on POSIX systems.
if modname == absmodname:
raise
return AstroidManager().ast_from_module_name(modname, use_cache=use_cache)
def relative_to_absolute_name(self, modname: str, level: int | None) -> str:
"""Get the absolute module name for a relative import.
The relative import can be implicit or explicit.
:param modname: The module name to convert.
:param level: The level of relative import.
:returns: The absolute module name.
:raises TooManyLevelsError: When the relative import refers to a
module too far above this one.
"""
# XXX this returns non sens when called on an absolute import
# like 'pylint.checkers.astroid.utils'
# XXX doesn't return absolute name if self.name isn't absolute name
if self.absolute_import_activated() and level is None:
return modname
if level:
if self.package:
level = level - 1
package_name = self.name.rsplit(".", level)[0]
elif (
self.path
and not os.path.exists(os.path.dirname(self.path[0]) + "/__init__.py")
and os.path.exists(
os.path.dirname(self.path[0]) + "/" + modname.split(".")[0]
)
):
level = level - 1
package_name = ""
else:
package_name = self.name.rsplit(".", level)[0]
if level and self.name.count(".") < level:
raise TooManyLevelsError(level=level, name=self.name)
elif self.package:
package_name = self.name
else:
package_name = self.name.rsplit(".", 1)[0]
if package_name:
if not modname:
return package_name
return f"{package_name}.{modname}"
return modname
def wildcard_import_names(self):
"""The list of imported names when this module is 'wildcard imported'.
It doesn't include the '__builtins__' name which is added by the
current CPython implementation of wildcard imports.
:returns: The list of imported names.
:rtype: list(str)
"""
# We separate the different steps of lookup in try/excepts
# to avoid catching too many Exceptions
default = [name for name in self.keys() if not name.startswith("_")]
try:
all_values = self["__all__"]
except KeyError:
return default
try:
explicit = next(all_values.assigned_stmts())
except (InferenceError, StopIteration):
return default
except AttributeError:
# not an assignment node
# XXX infer?
return default
# Try our best to detect the exported name.
inferred = []
try:
explicit = next(explicit.infer())
except (InferenceError, StopIteration):
return default
if not isinstance(explicit, (node_classes.Tuple, node_classes.List)):
return default
def str_const(node) -> bool:
return isinstance(node, node_classes.Const) and isinstance(node.value, str)
for node in explicit.elts:
if str_const(node):
inferred.append(node.value)
else:
try:
inferred_node = next(node.infer())
except (InferenceError, StopIteration):
continue
if str_const(inferred_node):
inferred.append(inferred_node.value)
return inferred
def public_names(self):
"""The list of the names that are publicly available in this module.
:returns: The list of public names.
:rtype: list(str)
"""
return [name for name in self.keys() if not name.startswith("_")]
def bool_value(self, context: InferenceContext | None = None) -> bool:
"""Determine the boolean value of this node.
:returns: The boolean value of this node.
For a :class:`Module` this is always ``True``.
"""
return True
def get_children(self):
yield from self.body
def frame(self: _T, *, future: Literal[None, True] = None) -> _T:
"""The node's frame node.
A frame node is a :class:`Module`, :class:`FunctionDef`,
:class:`ClassDef` or :class:`Lambda`.
:returns: The node itself.
"""
return self
def _infer(
self, context: InferenceContext | None = None, **kwargs: Any
) -> Generator[Module]:
yield self
class __SyntheticRoot(Module):
def __init__(self):
super().__init__("__astroid_synthetic", pure_python=False)
SYNTHETIC_ROOT = __SyntheticRoot()
class GeneratorExp(ComprehensionScope):
"""Class representing an :class:`ast.GeneratorExp` node.
>>> import astroid
>>> node = astroid.extract_node('(thing for thing in things if thing)')
>>> node
<GeneratorExp l.1 at 0x7f23b2e4e400>
"""
_astroid_fields = ("elt", "generators")
_other_other_fields = ("locals",)
elt: NodeNG
"""The element that forms the output of the expression."""
def __init__(
self,
lineno: int,
col_offset: int,
parent: NodeNG,
*,
end_lineno: int | None,
end_col_offset: int | None,
) -> None:
self.locals = {}
"""A map of the name of a local variable to the node defining the local."""
self.generators: list[nodes.Comprehension] = []
"""The generators that are looped through."""
super().__init__(
lineno=lineno,
col_offset=col_offset,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
parent=parent,
)
def postinit(self, elt: NodeNG, generators: list[nodes.Comprehension]) -> None:
self.elt = elt
self.generators = generators
def bool_value(self, context: InferenceContext | None = None) -> Literal[True]:
"""Determine the boolean value of this node.
:returns: The boolean value of this node.
For a :class:`GeneratorExp` this is always ``True``.
"""
return True
def get_children(self):
yield self.elt
yield from self.generators
class DictComp(ComprehensionScope):
"""Class representing an :class:`ast.DictComp` node.
>>> import astroid
>>> node = astroid.extract_node('{k:v for k, v in things if k > v}')
>>> node
<DictComp l.1 at 0x7f23b2e41d68>
"""
_astroid_fields = ("key", "value", "generators")
_other_other_fields = ("locals",)
key: NodeNG
"""What produces the keys."""
value: NodeNG
"""What produces the values."""
def __init__(
self,
lineno: int,
col_offset: int,
parent: NodeNG,
*,
end_lineno: int | None,
end_col_offset: int | None,
) -> None:
self.locals = {}
"""A map of the name of a local variable to the node defining the local."""
super().__init__(
lineno=lineno,
col_offset=col_offset,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
parent=parent,
)
def postinit(
self, key: NodeNG, value: NodeNG, generators: list[nodes.Comprehension]
) -> None:
self.key = key
self.value = value
self.generators = generators
def bool_value(self, context: InferenceContext | None = None):
"""Determine the boolean value of this node.
:returns: The boolean value of this node.
For a :class:`DictComp` this is always :class:`Uninferable`.
:rtype: Uninferable
"""
return util.Uninferable
def get_children(self):
yield self.key
yield self.value
yield from self.generators
class SetComp(ComprehensionScope):
"""Class representing an :class:`ast.SetComp` node.
>>> import astroid
>>> node = astroid.extract_node('{thing for thing in things if thing}')
>>> node
<SetComp l.1 at 0x7f23b2e41898>
"""
_astroid_fields = ("elt", "generators")
_other_other_fields = ("locals",)
elt: NodeNG
"""The element that forms the output of the expression."""
def __init__(
self,
lineno: int,
col_offset: int,
parent: NodeNG,
*,
end_lineno: int | None,
end_col_offset: int | None,
) -> None:
self.locals = {}
"""A map of the name of a local variable to the node defining the local."""
self.generators: list[nodes.Comprehension] = []
"""The generators that are looped through."""
super().__init__(
lineno=lineno,
col_offset=col_offset,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
parent=parent,
)
def postinit(self, elt: NodeNG, generators: list[nodes.Comprehension]) -> None:
self.elt = elt
self.generators = generators
def bool_value(self, context: InferenceContext | None = None):
"""Determine the boolean value of this node.
:returns: The boolean value of this node.
For a :class:`SetComp` this is always :class:`Uninferable`.
:rtype: Uninferable
"""
return util.Uninferable
def get_children(self):
yield self.elt
yield from self.generators
class ListComp(ComprehensionScope):
"""Class representing an :class:`ast.ListComp` node.
>>> import astroid
>>> node = astroid.extract_node('[thing for thing in things if thing]')
>>> node
<ListComp l.1 at 0x7f23b2e418d0>
"""
_astroid_fields = ("elt", "generators")
_other_other_fields = ("locals",)
elt: NodeNG
"""The element that forms the output of the expression."""
def __init__(
self,
lineno: int,
col_offset: int,
parent: NodeNG,
*,
end_lineno: int | None,
end_col_offset: int | None,
) -> None:
self.locals = {}
"""A map of the name of a local variable to the node defining it."""
self.generators: list[nodes.Comprehension] = []
"""The generators that are looped through."""
super().__init__(
lineno=lineno,
col_offset=col_offset,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
parent=parent,
)
def postinit(self, elt: NodeNG, generators: list[nodes.Comprehension]):
self.elt = elt
self.generators = generators
def bool_value(self, context: InferenceContext | None = None):
"""Determine the boolean value of this node.
:returns: The boolean value of this node.
For a :class:`ListComp` this is always :class:`Uninferable`.
:rtype: Uninferable
"""
return util.Uninferable
def get_children(self):
yield self.elt
yield from self.generators
def _infer_decorator_callchain(node):
"""Detect decorator call chaining and see if the end result is a
static or a classmethod.
"""
if not isinstance(node, FunctionDef):
return None
if not node.parent:
return None
try:
result = next(node.infer_call_result(node.parent), None)
except InferenceError:
return None
if isinstance(result, bases.Instance):
result = result._proxied
if isinstance(result, ClassDef):
if result.is_subtype_of("builtins.classmethod"):
return "classmethod"
if result.is_subtype_of("builtins.staticmethod"):
return "staticmethod"
if isinstance(result, FunctionDef):
if not result.decorators:
return None
# Determine if this function is decorated with one of the builtin descriptors we want.
for decorator in result.decorators.nodes:
if isinstance(decorator, node_classes.Name):
if decorator.name in BUILTIN_DESCRIPTORS:
return decorator.name
if (
isinstance(decorator, node_classes.Attribute)
and isinstance(decorator.expr, node_classes.Name)
and decorator.expr.name == "builtins"
and decorator.attrname in BUILTIN_DESCRIPTORS
):
return decorator.attrname
return None
class Lambda(_base_nodes.FilterStmtsBaseNode, LocalsDictNodeNG):
"""Class representing an :class:`ast.Lambda` node.
>>> import astroid
>>> node = astroid.extract_node('lambda arg: arg + 1')
>>> node
<Lambda.<lambda> l.1 at 0x7f23b2e41518>
"""
_astroid_fields: ClassVar[tuple[str, ...]] = ("args", "body")
_other_other_fields: ClassVar[tuple[str, ...]] = ("locals",)
name = "<lambda>"
is_lambda = True
special_attributes = FunctionModel()
"""The names of special attributes that this function has."""
args: Arguments
"""The arguments that the function takes."""
body: NodeNG
"""The contents of the function body."""
def implicit_parameters(self) -> Literal[0]:
return 0
@property
def type(self) -> Literal["method", "function"]:
"""Whether this is a method or function.
:returns: 'method' if this is a method, 'function' otherwise.
"""
if self.args.arguments and self.args.arguments[0].name == "self":
if self.parent and isinstance(self.parent.scope(), ClassDef):
return "method"
return "function"
def __init__(
self,
lineno: int,
col_offset: int,
parent: NodeNG,
*,
end_lineno: int | None,
end_col_offset: int | None,
):
self.locals = {}
"""A map of the name of a local variable to the node defining it."""
self.instance_attrs: dict[str, list[NodeNG]] = {}
super().__init__(
lineno=lineno,
col_offset=col_offset,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
parent=parent,
)
def postinit(self, args: Arguments, body: NodeNG) -> None:
self.args = args
self.body = body
def pytype(self) -> Literal["builtins.instancemethod", "builtins.function"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
"""
if "method" in self.type:
return "builtins.instancemethod"
return "builtins.function"
def display_type(self) -> str:
"""A human readable type of this node.
:returns: The type of this node.
:rtype: str
"""
if "method" in self.type:
return "Method"
return "Function"
def callable(self) -> Literal[True]:
"""Whether this node defines something that is callable.
:returns: Whether this defines something that is callable
For a :class:`Lambda` this is always ``True``.
"""
return True
def argnames(self) -> list[str]:
"""Get the names of each of the arguments, including that
of the collections of variable-length arguments ("args", "kwargs",
etc.), as well as positional-only and keyword-only arguments.
:returns: The names of the arguments.
:rtype: list(str)
"""
if self.args.arguments: # maybe None with builtin functions
names = [elt.name for elt in self.args.arguments]
else:
names = []
return names
def infer_call_result(
self,
caller: SuccessfulInferenceResult | None,
context: InferenceContext | None = None,
) -> Iterator[InferenceResult]:
"""Infer what the function returns when called."""
return self.body.infer(context)
def scope_lookup(
self, node: LookupMixIn, name: str, offset: int = 0
) -> tuple[LocalsDictNodeNG, list[NodeNG]]: