-
-
Notifications
You must be signed in to change notification settings - Fork 264
/
node_classes.py
5533 lines (4366 loc) · 164 KB
/
node_classes.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/PyCQA/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
"""Module for some node classes. More nodes in scoped_nodes.py"""
from __future__ import annotations
import abc
import itertools
import sys
import typing
import warnings
from collections.abc import Generator, Iterable, Mapping
from functools import lru_cache
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional, TypeVar, Union
from astroid import decorators, util
from astroid.bases import Instance, _infer_stmts
from astroid.const import Context
from astroid.context import InferenceContext
from astroid.exceptions import (
AstroidIndexError,
AstroidTypeError,
AstroidValueError,
InferenceError,
NoDefault,
ParentMissingError,
)
from astroid.manager import AstroidManager
from astroid.nodes import _base_nodes
from astroid.nodes.const import OP_PRECEDENCE
from astroid.nodes.node_ng import NodeNG
from astroid.typing import (
ConstFactoryResult,
InferenceErrorInfo,
InferenceResult,
SuccessfulInferenceResult,
)
if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal
if TYPE_CHECKING:
from astroid import nodes
from astroid.nodes import LocalsDictNodeNG
if sys.version_info >= (3, 8):
from functools import cached_property
else:
from astroid.decorators import cachedproperty as cached_property
def _is_const(value):
return isinstance(value, tuple(CONST_CLS))
_NodesT = TypeVar("_NodesT", bound=NodeNG)
_BadOpMessageT = TypeVar("_BadOpMessageT", bound=util.BadOperationMessage)
AssignedStmtsPossibleNode = Union["List", "Tuple", "AssignName", "AssignAttr", None]
AssignedStmtsCall = Callable[
[
_NodesT,
AssignedStmtsPossibleNode,
Optional[InferenceContext],
Optional[typing.List[int]],
],
Any,
]
InferBinaryOperation = Callable[
[_NodesT, Optional[InferenceContext]],
typing.Generator[Union[InferenceResult, _BadOpMessageT], None, None],
]
InferLHS = Callable[
[_NodesT, Optional[InferenceContext]],
typing.Generator[InferenceResult, None, Optional[InferenceErrorInfo]],
]
InferUnaryOp = Callable[[_NodesT, str], ConstFactoryResult]
@decorators.raise_if_nothing_inferred
def unpack_infer(stmt, context=None):
"""recursively generate nodes inferred by the given statement.
If the inferred value is a list or a tuple, recurse on the elements
"""
if isinstance(stmt, (List, Tuple)):
for elt in stmt.elts:
if elt is util.Uninferable:
yield elt
continue
yield from unpack_infer(elt, context)
return dict(node=stmt, context=context)
# if inferred is a final node, return it and stop
inferred = next(stmt.infer(context), util.Uninferable)
if inferred is stmt:
yield inferred
return dict(node=stmt, context=context)
# else, infer recursively, except Uninferable object that should be returned as is
for inferred in stmt.infer(context):
if inferred is util.Uninferable:
yield inferred
else:
yield from unpack_infer(inferred, context)
return dict(node=stmt, context=context)
def are_exclusive(stmt1, stmt2, exceptions: list[str] | None = None) -> bool:
"""return true if the two given statements are mutually exclusive
`exceptions` may be a list of exception names. If specified, discard If
branches and check one of the statement is in an exception handler catching
one of the given exceptions.
algorithm :
1) index stmt1's parents
2) climb among stmt2's parents until we find a common parent
3) if the common parent is a If or TryExcept statement, look if nodes are
in exclusive branches
"""
# index stmt1's parents
stmt1_parents = {}
children = {}
previous = stmt1
for node in stmt1.node_ancestors():
stmt1_parents[node] = 1
children[node] = previous
previous = node
# climb among stmt2's parents until we find a common parent
previous = stmt2
for node in stmt2.node_ancestors():
if node in stmt1_parents:
# if the common parent is a If or TryExcept statement, look if
# nodes are in exclusive branches
if isinstance(node, If) and exceptions is None:
if (
node.locate_child(previous)[1]
is not node.locate_child(children[node])[1]
):
return True
elif isinstance(node, TryExcept):
c2attr, c2node = node.locate_child(previous)
c1attr, c1node = node.locate_child(children[node])
if c1node is not c2node:
first_in_body_caught_by_handlers = (
c2attr == "handlers"
and c1attr == "body"
and previous.catch(exceptions)
)
second_in_body_caught_by_handlers = (
c2attr == "body"
and c1attr == "handlers"
and children[node].catch(exceptions)
)
first_in_else_other_in_handlers = (
c2attr == "handlers" and c1attr == "orelse"
)
second_in_else_other_in_handlers = (
c2attr == "orelse" and c1attr == "handlers"
)
if any(
(
first_in_body_caught_by_handlers,
second_in_body_caught_by_handlers,
first_in_else_other_in_handlers,
second_in_else_other_in_handlers,
)
):
return True
elif c2attr == "handlers" and c1attr == "handlers":
return previous is not children[node]
return False
previous = node
return False
# getitem() helpers.
_SLICE_SENTINEL = object()
def _slice_value(index, context=None):
"""Get the value of the given slice index."""
if isinstance(index, Const):
if isinstance(index.value, (int, type(None))):
return index.value
elif index is None:
return None
else:
# Try to infer what the index actually is.
# Since we can't return all the possible values,
# we'll stop at the first possible value.
try:
inferred = next(index.infer(context=context))
except (InferenceError, StopIteration):
pass
else:
if isinstance(inferred, Const):
if isinstance(inferred.value, (int, type(None))):
return inferred.value
# Use a sentinel, because None can be a valid
# value that this function can return,
# as it is the case for unspecified bounds.
return _SLICE_SENTINEL
def _infer_slice(node, context=None):
lower = _slice_value(node.lower, context)
upper = _slice_value(node.upper, context)
step = _slice_value(node.step, context)
if all(elem is not _SLICE_SENTINEL for elem in (lower, upper, step)):
return slice(lower, upper, step)
raise AstroidTypeError(
message="Could not infer slice used in subscript",
node=node,
index=node.parent,
context=context,
)
def _container_getitem(instance, elts, index, context=None):
"""Get a slice or an item, using the given *index*, for the given sequence."""
try:
if isinstance(index, Slice):
index_slice = _infer_slice(index, context=context)
new_cls = instance.__class__()
new_cls.elts = elts[index_slice]
new_cls.parent = instance.parent
return new_cls
if isinstance(index, Const):
return elts[index.value]
except ValueError as exc:
raise AstroidValueError(
message="Slice {index!r} cannot index container",
node=instance,
index=index,
context=context,
) from exc
except IndexError as exc:
raise AstroidIndexError(
message="Index {index!s} out of range",
node=instance,
index=index,
context=context,
) from exc
except TypeError as exc:
raise AstroidTypeError(
message="Type error {error!r}", node=instance, index=index, context=context
) from exc
raise AstroidTypeError(f"Could not use {index} as subscript index")
class BaseContainer(_base_nodes.ParentAssignNode, Instance, metaclass=abc.ABCMeta):
"""Base class for Set, FrozenSet, Tuple and List."""
_astroid_fields = ("elts",)
def __init__(
self,
lineno: int | None = None,
col_offset: int | None = None,
parent: NodeNG | None = None,
*,
end_lineno: int | None = None,
end_col_offset: int | None = None,
) -> None:
"""
:param lineno: The line that this node appears on in the source code.
:param col_offset: The column that this node appears on in the
source code.
:param parent: The parent node in the syntax tree.
:param end_lineno: The last line this node appears on in the source code.
:param end_col_offset: The end column this node appears on in the
source code. Note: This is after the last symbol.
"""
self.elts: list[NodeNG] = []
"""The elements in the node."""
super().__init__(
lineno=lineno,
col_offset=col_offset,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
parent=parent,
)
def postinit(self, elts: list[NodeNG]) -> None:
"""Do some setup after initialisation.
:param elts: The list of elements the that node contains.
"""
self.elts = elts
@classmethod
def from_elements(cls, elts=None):
"""Create a node of this type from the given list of elements.
:param elts: The list of elements that the node should contain.
:type elts: list(NodeNG)
:returns: A new node containing the given elements.
:rtype: NodeNG
"""
node = cls()
if elts is None:
node.elts = []
else:
node.elts = [const_factory(e) if _is_const(e) else e for e in elts]
return node
def itered(self):
"""An iterator over the elements this node contains.
:returns: The contents of this node.
:rtype: iterable(NodeNG)
"""
return self.elts
def bool_value(self, context=None):
"""Determine the boolean value of this node.
:returns: The boolean value of this node.
:rtype: bool or Uninferable
"""
return bool(self.elts)
@abc.abstractmethod
def pytype(self) -> str:
"""Get the name of the type that this node represents.
:returns: The name of the type.
"""
def get_children(self):
yield from self.elts
# TODO: Move into _base_nodes. Blocked by import of _infer_stmts from bases.
class LookupMixIn(NodeNG):
"""Mixin to look up a name in the right scope."""
@lru_cache() # noqa
def lookup(self, name: str) -> tuple[LocalsDictNodeNG, list[NodeNG]]:
"""Lookup where the given variable is assigned.
The lookup starts from self's scope. If self is not a frame itself
and the name is found in the inner frame locals, statements will be
filtered to remove ignorable statements according to self's location.
:param name: The name of the variable to find assignments for.
:returns: The 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).
"""
return self.scope().scope_lookup(self, name)
def ilookup(self, name):
"""Lookup the inferred values of the given variable.
:param name: The variable name to find values for.
:type name: str
:returns: The inferred values of the statements returned from
:meth:`lookup`.
:rtype: iterable
"""
frame, stmts = self.lookup(name)
context = InferenceContext()
return _infer_stmts(stmts, context, frame)
# Name classes
class AssignName(_base_nodes.NoChildrenNode, LookupMixIn, _base_nodes.ParentAssignNode):
"""Variation of :class:`ast.Assign` representing assignment to a name.
An :class:`AssignName` is the name of something that is assigned to.
This includes variables defined in a function signature or in a loop.
>>> import astroid
>>> node = astroid.extract_node('variable = range(10)')
>>> node
<Assign l.1 at 0x7effe1db8550>
>>> list(node.get_children())
[<AssignName.variable l.1 at 0x7effe1db8748>, <Call l.1 at 0x7effe1db8630>]
>>> list(node.get_children())[0].as_string()
'variable'
"""
_other_fields = ("name",)
infer_lhs: ClassVar[InferLHS[AssignName]]
@decorators.deprecate_default_argument_values(name="str")
def __init__(
self,
name: str | None = None,
lineno: int | None = None,
col_offset: int | None = None,
parent: NodeNG | None = None,
*,
end_lineno: int | None = None,
end_col_offset: int | None = None,
) -> None:
"""
:param name: The name that is assigned to.
:param lineno: The line that this node appears on in the source code.
:param col_offset: The column that this node appears on in the
source code.
:param parent: The parent node in the syntax tree.
:param end_lineno: The last line this node appears on in the source code.
:param end_col_offset: The end column this node appears on in the
source code. Note: This is after the last symbol.
"""
self.name: str | None = name
"""The name that is assigned to."""
super().__init__(
lineno=lineno,
col_offset=col_offset,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
parent=parent,
)
assigned_stmts: ClassVar[AssignedStmtsCall[AssignName]]
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
class DelName(_base_nodes.NoChildrenNode, LookupMixIn, _base_nodes.ParentAssignNode):
"""Variation of :class:`ast.Delete` representing deletion of a name.
A :class:`DelName` is the name of something that is deleted.
>>> import astroid
>>> node = astroid.extract_node("del variable #@")
>>> list(node.get_children())
[<DelName.variable l.1 at 0x7effe1da4d30>]
>>> list(node.get_children())[0].as_string()
'variable'
"""
_other_fields = ("name",)
@decorators.deprecate_default_argument_values(name="str")
def __init__(
self,
name: str | None = None,
lineno: int | None = None,
col_offset: int | None = None,
parent: NodeNG | None = None,
*,
end_lineno: int | None = None,
end_col_offset: int | None = None,
) -> None:
"""
:param name: The name that is being deleted.
:param lineno: The line that this node appears on in the source code.
:param col_offset: The column that this node appears on in the
source code.
:param parent: The parent node in the syntax tree.
:param end_lineno: The last line this node appears on in the source code.
:param end_col_offset: The end column this node appears on in the
source code. Note: This is after the last symbol.
"""
self.name: str | None = name
"""The name that is being deleted."""
super().__init__(
lineno=lineno,
col_offset=col_offset,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
parent=parent,
)
class Name(_base_nodes.NoChildrenNode, LookupMixIn):
"""Class representing an :class:`ast.Name` node.
A :class:`Name` node is something that is named, but not covered by
:class:`AssignName` or :class:`DelName`.
>>> import astroid
>>> node = astroid.extract_node('range(10)')
>>> node
<Call l.1 at 0x7effe1db8710>
>>> list(node.get_children())
[<Name.range l.1 at 0x7effe1db86a0>, <Const.int l.1 at 0x7effe1db8518>]
>>> list(node.get_children())[0].as_string()
'range'
"""
_other_fields = ("name",)
@decorators.deprecate_default_argument_values(name="str")
def __init__(
self,
name: str | None = None,
lineno: int | None = None,
col_offset: int | None = None,
parent: NodeNG | None = None,
*,
end_lineno: int | None = None,
end_col_offset: int | None = None,
) -> None:
"""
:param name: The name that this node refers to.
:param lineno: The line that this node appears on in the source code.
:param col_offset: The column that this node appears on in the
source code.
:param parent: The parent node in the syntax tree.
:param end_lineno: The last line this node appears on in the source code.
:param end_col_offset: The end column this node appears on in the
source code. Note: This is after the last symbol.
"""
self.name: str | None = name
"""The name that this node refers to."""
super().__init__(
lineno=lineno,
col_offset=col_offset,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
parent=parent,
)
def _get_name_nodes(self):
yield self
for child_node in self.get_children():
yield from child_node._get_name_nodes()
class Arguments(_base_nodes.AssignTypeNode):
"""Class representing an :class:`ast.arguments` node.
An :class:`Arguments` node represents that arguments in a
function definition.
>>> import astroid
>>> node = astroid.extract_node('def foo(bar): pass')
>>> node
<FunctionDef.foo l.1 at 0x7effe1db8198>
>>> node.args
<Arguments l.1 at 0x7effe1db82e8>
"""
# Python 3.4+ uses a different approach regarding annotations,
# each argument is a new class, _ast.arg, which exposes an
# 'annotation' attribute. In astroid though, arguments are exposed
# as is in the Arguments node and the only way to expose annotations
# is by using something similar with Python 3.3:
# - we expose 'varargannotation' and 'kwargannotation' of annotations
# of varargs and kwargs.
# - we expose 'annotation', a list with annotations for
# for each normal argument. If an argument doesn't have an
# annotation, its value will be None.
_astroid_fields = (
"args",
"defaults",
"kwonlyargs",
"posonlyargs",
"posonlyargs_annotations",
"kw_defaults",
"annotations",
"varargannotation",
"kwargannotation",
"kwonlyargs_annotations",
"type_comment_args",
"type_comment_kwonlyargs",
"type_comment_posonlyargs",
)
_other_fields = ("vararg", "kwarg")
lineno: None
col_offset: None
end_lineno: None
end_col_offset: None
def __init__(
self,
vararg: str | None = None,
kwarg: str | None = None,
parent: NodeNG | None = None,
) -> None:
"""
:param vararg: The name of the variable length arguments.
:param kwarg: The name of the variable length keyword arguments.
:param parent: The parent node in the syntax tree.
"""
super().__init__(parent=parent)
self.vararg: str | None = vararg # can be None
"""The name of the variable length arguments."""
self.kwarg: str | None = kwarg # can be None
"""The name of the variable length keyword arguments."""
self.args: list[AssignName] | None
"""The names of the required arguments.
Can be None if the associated function does not have a retrievable
signature and the arguments are therefore unknown.
This can happen with (builtin) functions implemented in C that have
incomplete signature information.
"""
# TODO: Check if other attributes should also be None when
# .args is None.
self.defaults: list[NodeNG]
"""The default values for arguments that can be passed positionally."""
self.kwonlyargs: list[AssignName]
"""The keyword arguments that cannot be passed positionally."""
self.posonlyargs: list[AssignName] = []
"""The arguments that can only be passed positionally."""
self.kw_defaults: list[NodeNG | None]
"""The default values for keyword arguments that cannot be passed positionally."""
self.annotations: list[NodeNG | None]
"""The type annotations of arguments that can be passed positionally."""
self.posonlyargs_annotations: list[NodeNG | None] = []
"""The type annotations of arguments that can only be passed positionally."""
self.kwonlyargs_annotations: list[NodeNG | None] = []
"""The type annotations of arguments that cannot be passed positionally."""
self.type_comment_args: list[NodeNG | None] = []
"""The type annotation, passed by a type comment, of each argument.
If an argument does not have a type comment,
the value for that argument will be None.
"""
self.type_comment_kwonlyargs: list[NodeNG | None] = []
"""The type annotation, passed by a type comment, of each keyword only argument.
If an argument does not have a type comment,
the value for that argument will be None.
"""
self.type_comment_posonlyargs: list[NodeNG | None] = []
"""The type annotation, passed by a type comment, of each positional argument.
If an argument does not have a type comment,
the value for that argument will be None.
"""
self.varargannotation: NodeNG | None = None # can be None
"""The type annotation for the variable length arguments."""
self.kwargannotation: NodeNG | None = None # can be None
"""The type annotation for the variable length keyword arguments."""
# pylint: disable=too-many-arguments
def postinit(
self,
args: list[AssignName] | None,
defaults: list[NodeNG],
kwonlyargs: list[AssignName],
kw_defaults: list[NodeNG | None],
annotations: list[NodeNG | None],
posonlyargs: list[AssignName] | None = None,
kwonlyargs_annotations: list[NodeNG | None] | None = None,
posonlyargs_annotations: list[NodeNG | None] | None = None,
varargannotation: NodeNG | None = None,
kwargannotation: NodeNG | None = None,
type_comment_args: list[NodeNG | None] | None = None,
type_comment_kwonlyargs: list[NodeNG | None] | None = None,
type_comment_posonlyargs: list[NodeNG | None] | None = None,
) -> None:
"""Do some setup after initialisation.
:param args: The names of the required arguments.
:param defaults: The default values for arguments that can be passed
positionally.
:param kwonlyargs: The keyword arguments that cannot be passed
positionally.
:param posonlyargs: The arguments that can only be passed
positionally.
:param kw_defaults: The default values for keyword arguments that
cannot be passed positionally.
:param annotations: The type annotations of arguments that can be
passed positionally.
:param kwonlyargs_annotations: The type annotations of arguments that
cannot be passed positionally. This should always be passed in
Python 3.
:param posonlyargs_annotations: The type annotations of arguments that
can only be passed positionally. This should always be passed in
Python 3.
:param varargannotation: The type annotation for the variable length
arguments.
:param kwargannotation: The type annotation for the variable length
keyword arguments.
:param type_comment_args: The type annotation,
passed by a type comment, of each argument.
:param type_comment_args: The type annotation,
passed by a type comment, of each keyword only argument.
:param type_comment_args: The type annotation,
passed by a type comment, of each positional argument.
"""
self.args = args
self.defaults = defaults
self.kwonlyargs = kwonlyargs
if posonlyargs is not None:
self.posonlyargs = posonlyargs
self.kw_defaults = kw_defaults
self.annotations = annotations
if kwonlyargs_annotations is not None:
self.kwonlyargs_annotations = kwonlyargs_annotations
if posonlyargs_annotations is not None:
self.posonlyargs_annotations = posonlyargs_annotations
self.varargannotation = varargannotation
self.kwargannotation = kwargannotation
if type_comment_args is not None:
self.type_comment_args = type_comment_args
if type_comment_kwonlyargs is not None:
self.type_comment_kwonlyargs = type_comment_kwonlyargs
if type_comment_posonlyargs is not None:
self.type_comment_posonlyargs = type_comment_posonlyargs
assigned_stmts: ClassVar[AssignedStmtsCall[Arguments]]
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
def _infer_name(self, frame, name):
if self.parent is frame:
return name
return None
@cached_property
def fromlineno(self):
"""The first line that this node appears on in the source code.
:type: int or None
"""
lineno = super().fromlineno
return max(lineno, self.parent.fromlineno or 0)
@cached_property
def arguments(self):
"""Get all the arguments for this node, including positional only and positional and keyword"""
return list(itertools.chain((self.posonlyargs or ()), self.args or ()))
def format_args(self, *, skippable_names: set[str] | None = None) -> str:
"""Get the arguments formatted as string.
:returns: The formatted arguments.
:rtype: str
"""
result = []
positional_only_defaults = []
positional_or_keyword_defaults = self.defaults
if self.defaults:
args = self.args or []
positional_or_keyword_defaults = self.defaults[-len(args) :]
positional_only_defaults = self.defaults[: len(self.defaults) - len(args)]
if self.posonlyargs:
result.append(
_format_args(
self.posonlyargs,
positional_only_defaults,
self.posonlyargs_annotations,
skippable_names=skippable_names,
)
)
result.append("/")
if self.args:
result.append(
_format_args(
self.args,
positional_or_keyword_defaults,
getattr(self, "annotations", None),
skippable_names=skippable_names,
)
)
if self.vararg:
result.append(f"*{self.vararg}")
if self.kwonlyargs:
if not self.vararg:
result.append("*")
result.append(
_format_args(
self.kwonlyargs,
self.kw_defaults,
self.kwonlyargs_annotations,
skippable_names=skippable_names,
)
)
if self.kwarg:
result.append(f"**{self.kwarg}")
return ", ".join(result)
def _get_arguments_data(
self,
) -> tuple[
dict[str, tuple[str | None, str | None]],
dict[str, tuple[str | None, str | None]],
]:
"""Get the arguments as dictionary with information about typing and defaults.
The return tuple contains a dictionary for positional and keyword arguments with their typing
and their default value, if any.
The method follows a similar order as format_args but instead of formatting into a string it
returns the data that is used to do so.
"""
pos_only: dict[str, tuple[str | None, str | None]] = {}
kw_only: dict[str, tuple[str | None, str | None]] = {}
# Setup and match defaults with arguments
positional_only_defaults = []
positional_or_keyword_defaults = self.defaults
if self.defaults:
args = self.args or []
positional_or_keyword_defaults = self.defaults[-len(args) :]
positional_only_defaults = self.defaults[: len(self.defaults) - len(args)]
for index, posonly in enumerate(self.posonlyargs):
annotation, default = self.posonlyargs_annotations[index], None
if annotation is not None:
annotation = annotation.as_string()
if positional_only_defaults:
default = positional_only_defaults[index].as_string()
pos_only[posonly.name] = (annotation, default)
for index, arg in enumerate(self.args):
annotation, default = self.annotations[index], None
if annotation is not None:
annotation = annotation.as_string()
if positional_or_keyword_defaults:
defaults_offset = len(self.args) - len(positional_or_keyword_defaults)
default_index = index - defaults_offset
if (
default_index > -1
and positional_or_keyword_defaults[default_index] is not None
):
default = positional_or_keyword_defaults[default_index].as_string()
pos_only[arg.name] = (annotation, default)
if self.vararg:
annotation = self.varargannotation
if annotation is not None:
annotation = annotation.as_string()
pos_only[self.vararg] = (annotation, None)
for index, kwarg in enumerate(self.kwonlyargs):
annotation = self.kwonlyargs_annotations[index]
if annotation is not None:
annotation = annotation.as_string()
default = self.kw_defaults[index]
if default is not None:
default = default.as_string()
kw_only[kwarg.name] = (annotation, default)
if self.kwarg:
annotation = self.kwargannotation
if annotation is not None:
annotation = annotation.as_string()
kw_only[self.kwarg] = (annotation, None)
return pos_only, kw_only
def default_value(self, argname):
"""Get the default value for an argument.
:param argname: The name of the argument to get the default value for.
:type argname: str
:raises NoDefault: If there is no default value defined for the
given argument.
"""
args = self.arguments
index = _find_arg(argname, args)[0]
if index is not None:
idx = index - (len(args) - len(self.defaults))
if idx >= 0:
return self.defaults[idx]
index = _find_arg(argname, self.kwonlyargs)[0]
if index is not None and self.kw_defaults[index] is not None:
return self.kw_defaults[index]
raise NoDefault(func=self.parent, name=argname)
def is_argument(self, name):
"""Check if the given name is defined in the arguments.
:param name: The name to check for.
:type name: str
:returns: True if the given name is defined in the arguments,
False otherwise.
:rtype: bool
"""
if name == self.vararg:
return True
if name == self.kwarg:
return True
return (
self.find_argname(name, rec=True)[1] is not None
or self.kwonlyargs
and _find_arg(name, self.kwonlyargs, rec=True)[1] is not None
)
def find_argname(self, argname, rec=False):
"""Get the index and :class:`AssignName` node for given name.
:param argname: The name of the argument to search for.
:type argname: str
:param rec: Whether or not to include arguments in unpacked tuples
in the search.
:type rec: bool
:returns: The index and node for the argument.
:rtype: tuple(str or None, AssignName or None)
"""
if self.arguments:
return _find_arg(argname, self.arguments, rec)
return None, None
def get_children(self):
yield from self.posonlyargs or ()
for elt in self.posonlyargs_annotations:
if elt is not None:
yield elt
yield from self.args or ()
yield from self.defaults
yield from self.kwonlyargs
for elt in self.kw_defaults:
if elt is not None:
yield elt
for elt in self.annotations:
if elt is not None:
yield elt
if self.varargannotation is not None:
yield self.varargannotation
if self.kwargannotation is not None:
yield self.kwargannotation
for elt in self.kwonlyargs_annotations:
if elt is not None:
yield elt