-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathnode_classes.py
5579 lines (4535 loc) · 169 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/pylint-dev/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
"""Module for some node classes. More nodes in scoped_nodes.py"""
from __future__ import annotations
import abc
import ast
import itertools
import operator
import sys
import typing
import warnings
from collections.abc import Callable, Generator, Iterable, Iterator, Mapping
from functools import cached_property
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Literal,
Optional,
Union,
)
from astroid import decorators, protocols, util
from astroid.bases import Instance, _infer_stmts
from astroid.const import _EMPTY_OBJECT_MARKER, Context
from astroid.context import CallContext, InferenceContext, copy_context
from astroid.exceptions import (
AstroidBuildingError,
AstroidError,
AstroidIndexError,
AstroidTypeError,
AstroidValueError,
AttributeInferenceError,
InferenceError,
NameInferenceError,
NoDefault,
ParentMissingError,
_NonDeducibleTypeHierarchy,
)
from astroid.interpreter import dunder_lookup
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.nodes.scoped_nodes import SYNTHETIC_ROOT
from astroid.typing import (
ConstFactoryResult,
InferenceErrorInfo,
InferenceResult,
SuccessfulInferenceResult,
)
if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
if TYPE_CHECKING:
from astroid import nodes
from astroid.nodes import LocalsDictNodeNG
def _is_const(value) -> bool:
return isinstance(value, tuple(CONST_CLS))
_NodesT = typing.TypeVar("_NodesT", bound=NodeNG)
_BadOpMessageT = typing.TypeVar("_BadOpMessageT", bound=util.BadOperationMessage)
AssignedStmtsPossibleNode = Union["List", "Tuple", "AssignName", "AssignAttr", None]
AssignedStmtsCall = Callable[
[
_NodesT,
AssignedStmtsPossibleNode,
Optional[InferenceContext],
Optional[list[int]],
],
Any,
]
InferBinaryOperation = Callable[
[_NodesT, Optional[InferenceContext]],
Generator[Union[InferenceResult, _BadOpMessageT]],
]
InferLHS = Callable[
[_NodesT, Optional[InferenceContext]],
Generator[InferenceResult, None, Optional[InferenceErrorInfo]],
]
InferUnaryOp = Callable[[_NodesT, str], ConstFactoryResult]
@decorators.raise_if_nothing_inferred
def unpack_infer(stmt, context: InferenceContext | None = 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 {"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 {"node": stmt, "context": context}
# else, infer recursively, except Uninferable object that should be returned as is
for inferred in stmt.infer(context):
if isinstance(inferred, util.UninferableBase):
yield inferred
else:
yield from unpack_infer(inferred, context)
return {"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 Try 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 Try statement, look if
# nodes are in exclusive branches
if isinstance(node, If) and exceptions is None:
c2attr, c2node = node.locate_child(previous)
c1attr, c1node = node.locate_child(children[node])
if "test" in (c1attr, c2attr):
# If any node is `If.test`, then it must be inclusive with
# the other node (`If.body` and `If.orelse`)
return False
if c1attr != c2attr:
# different `If` branches (`If.body` and `If.orelse`)
return True
elif isinstance(node, Try):
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: InferenceContext | None = 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: InferenceContext | None = 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: InferenceContext | None = 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,
col_offset: int | None,
parent: NodeNG | None,
*,
end_lineno: int | None,
end_col_offset: int | None,
) -> None:
self.elts: list[SuccessfulInferenceResult] = []
"""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[SuccessfulInferenceResult]) -> None:
self.elts = elts
@classmethod
def from_elements(cls, elts: Iterable[Any]) -> Self:
"""Create a node of this type from the given list of elements.
:param elts: The list of elements that the node should contain.
:returns: A new node containing the given elements.
"""
node = cls(
lineno=None,
col_offset=None,
parent=None,
end_lineno=None,
end_col_offset=None,
)
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: InferenceContext | None = None) -> bool:
"""Determine the boolean value of this node.
:returns: The boolean value of this node.
"""
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
@decorators.raise_if_nothing_inferred
def _infer(
self,
context: InferenceContext | None = None,
**kwargs: Any,
) -> Iterator[Self]:
has_starred_named_expr = any(
isinstance(e, (Starred, NamedExpr)) for e in self.elts
)
if has_starred_named_expr:
values = self._infer_sequence_helper(context)
new_seq = type(self)(
lineno=self.lineno,
col_offset=self.col_offset,
parent=self.parent,
end_lineno=self.end_lineno,
end_col_offset=self.end_col_offset,
)
new_seq.postinit(values)
yield new_seq
else:
yield self
def _infer_sequence_helper(
self, context: InferenceContext | None = None
) -> list[SuccessfulInferenceResult]:
"""Infer all values based on BaseContainer.elts."""
values = []
for elt in self.elts:
if isinstance(elt, Starred):
starred = util.safe_infer(elt.value, context)
if not starred:
raise InferenceError(node=self, context=context)
if not hasattr(starred, "elts"):
raise InferenceError(node=self, context=context)
# TODO: fresh context?
values.extend(starred._infer_sequence_helper(context))
elif isinstance(elt, NamedExpr):
value = util.safe_infer(elt.value, context)
if not value:
raise InferenceError(node=self, context=context)
values.append(value)
else:
values.append(elt)
return values
# Name classes
class AssignName(
_base_nodes.NoChildrenNode,
_base_nodes.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",)
def __init__(
self,
name: str,
lineno: int,
col_offset: int,
parent: NodeNG,
*,
end_lineno: int | None,
end_col_offset: int | None,
) -> None:
self.name = 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 = protocols.assend_assigned_stmts
"""Returns the assigned statement (non inferred) according to the assignment type.
See astroid/protocols.py for actual implementation.
"""
@decorators.raise_if_nothing_inferred
@decorators.path_wrapper
def _infer(
self, context: InferenceContext | None = None, **kwargs: Any
) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
"""Infer an AssignName: need to inspect the RHS part of the
assign node.
"""
if isinstance(self.parent, AugAssign):
return self.parent.infer(context)
stmts = list(self.assigned_stmts(context=context))
return _infer_stmts(stmts, context)
@decorators.raise_if_nothing_inferred
def infer_lhs(
self, context: InferenceContext | None = None, **kwargs: Any
) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
"""Infer a Name: use name lookup rules.
Same implementation as Name._infer."""
# pylint: disable=import-outside-toplevel
from astroid.constraint import get_constraints
from astroid.helpers import _higher_function_scope
frame, stmts = self.lookup(self.name)
if not stmts:
# Try to see if the name is enclosed in a nested function
# and use the higher (first function) scope for searching.
parent_function = _higher_function_scope(self.scope())
if parent_function:
_, stmts = parent_function.lookup(self.name)
if not stmts:
raise NameInferenceError(
name=self.name, scope=self.scope(), context=context
)
context = copy_context(context)
context.lookupname = self.name
context.constraints[self.name] = get_constraints(self, frame)
return _infer_stmts(stmts, context, frame)
class DelName(
_base_nodes.NoChildrenNode, _base_nodes.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",)
def __init__(
self,
name: str,
lineno: int,
col_offset: int,
parent: NodeNG,
*,
end_lineno: int | None,
end_col_offset: int | None,
) -> None:
self.name = 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.LookupMixIn, _base_nodes.NoChildrenNode):
"""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",)
def __init__(
self,
name: str,
lineno: int,
col_offset: int,
parent: NodeNG,
*,
end_lineno: int | None,
end_col_offset: int | None,
) -> None:
self.name = 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()
@decorators.raise_if_nothing_inferred
@decorators.path_wrapper
def _infer(
self, context: InferenceContext | None = None, **kwargs: Any
) -> Generator[InferenceResult, None, InferenceErrorInfo | None]:
"""Infer a Name: use name lookup rules
Same implementation as AssignName._infer_lhs."""
# pylint: disable=import-outside-toplevel
from astroid.constraint import get_constraints
from astroid.helpers import _higher_function_scope
frame, stmts = self.lookup(self.name)
if not stmts:
# Try to see if the name is enclosed in a nested function
# and use the higher (first function) scope for searching.
parent_function = _higher_function_scope(self.scope())
if parent_function:
_, stmts = parent_function.lookup(self.name)
if not stmts:
raise NameInferenceError(
name=self.name, scope=self.scope(), context=context
)
context = copy_context(context)
context.lookupname = self.name
context.constraints[self.name] = get_constraints(self, frame)
return _infer_stmts(stmts, context, frame)
DEPRECATED_ARGUMENT_DEFAULT = "DEPRECATED_ARGUMENT_DEFAULT"
class Arguments(
_base_nodes.AssignTypeNode
): # pylint: disable=too-many-instance-attributes
"""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")
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.
"""
defaults: list[NodeNG] | None
"""The default values for arguments that can be passed positionally."""
kwonlyargs: list[AssignName]
"""The keyword arguments that cannot be passed positionally."""
posonlyargs: list[AssignName]
"""The arguments that can only be passed positionally."""
kw_defaults: list[NodeNG | None] | None
"""The default values for keyword arguments that cannot be passed positionally."""
annotations: list[NodeNG | None]
"""The type annotations of arguments that can be passed positionally."""
posonlyargs_annotations: list[NodeNG | None]
"""The type annotations of arguments that can only be passed positionally."""
kwonlyargs_annotations: list[NodeNG | None]
"""The type annotations of arguments that cannot be passed positionally."""
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.
"""
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.
"""
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.
"""
varargannotation: NodeNG | None
"""The type annotation for the variable length arguments."""
kwargannotation: NodeNG | None
"""The type annotation for the variable length keyword arguments."""
vararg_node: AssignName | None
"""The node for variable length arguments"""
kwarg_node: AssignName | None
"""The node for variable keyword arguments"""
def __init__(
self,
vararg: str | None,
kwarg: str | None,
parent: NodeNG,
vararg_node: AssignName | None = None,
kwarg_node: AssignName | None = None,
) -> None:
"""Almost all attributes can be None for living objects where introspection failed."""
super().__init__(
parent=parent,
lineno=None,
col_offset=None,
end_lineno=None,
end_col_offset=None,
)
self.vararg = vararg
"""The name of the variable length arguments."""
self.kwarg = kwarg
"""The name of the variable length keyword arguments."""
self.vararg_node = vararg_node
self.kwarg_node = kwarg_node
# pylint: disable=too-many-arguments, too-many-positional-arguments
def postinit(
self,
args: list[AssignName] | None,
defaults: list[NodeNG] | None,
kwonlyargs: list[AssignName],
kw_defaults: list[NodeNG | None] | None,
annotations: list[NodeNG | None],
posonlyargs: list[AssignName],
kwonlyargs_annotations: list[NodeNG | None],
posonlyargs_annotations: list[NodeNG | 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:
self.args = args
self.defaults = defaults
self.kwonlyargs = kwonlyargs
self.posonlyargs = posonlyargs
self.kw_defaults = kw_defaults
self.annotations = annotations
self.kwonlyargs_annotations = kwonlyargs_annotations
self.posonlyargs_annotations = posonlyargs_annotations
# Parameters that got added later and need a default
self.varargannotation = varargannotation
self.kwargannotation = kwargannotation
if type_comment_args is None:
type_comment_args = []
self.type_comment_args = type_comment_args
if type_comment_kwonlyargs is None:
type_comment_kwonlyargs = []
self.type_comment_kwonlyargs = type_comment_kwonlyargs
if type_comment_posonlyargs is None:
type_comment_posonlyargs = []
self.type_comment_posonlyargs = type_comment_posonlyargs
assigned_stmts = protocols.arguments_assigned_stmts
"""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) -> int:
"""The first line that this node appears on in the source code.
Can also return 0 if the line can not be determined.
"""
lineno = super().fromlineno
return max(lineno, self.parent.fromlineno or 0)
@cached_property
def arguments(self):
"""Get all the arguments for this node. This includes:
* Positional only arguments
* Positional arguments
* Keyword arguments
* Variable arguments (.e.g *args)
* Variable keyword arguments (e.g **kwargs)
"""
retval = list(itertools.chain((self.posonlyargs or ()), (self.args or ())))
if self.vararg_node:
retval.append(self.vararg_node)
retval += self.kwonlyargs or ()
if self.kwarg_node:
retval.append(self.kwarg_node)
return retval
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 = [
arg for arg in self.arguments if arg.name not in [self.vararg, self.kwarg]
]
index = _find_arg(argname, self.kwonlyargs)[0]
if (index is not None) and (len(self.kw_defaults) > index):
if self.kw_defaults[index] is not None:
return self.kw_defaults[index]
raise NoDefault(func=self.parent, name=argname)
index = _find_arg(argname, args)[0]
if index is not None:
idx = index - (len(args) - len(self.defaults) - len(self.kw_defaults))
if idx >= 0:
return self.defaults[idx]
raise NoDefault(func=self.parent, name=argname)
def is_argument(self, name) -> bool:
"""Check if the given name is defined in the arguments.
:param name: The name to check for.
:type name: str
:returns: Whether the given name is defined in the arguments,
"""
if name == self.vararg:
return True
if name == self.kwarg:
return True
return self.find_argname(name)[1] is not None
def find_argname(self, argname, rec=DEPRECATED_ARGUMENT_DEFAULT):
"""Get the index and :class:`AssignName` node for given name.
:param argname: The name of the argument to search for.
:type argname: str
:returns: The index and node for the argument.
:rtype: tuple(str or None, AssignName or None)
"""
if rec != DEPRECATED_ARGUMENT_DEFAULT: # pragma: no cover
warnings.warn(
"The rec argument will be removed in astroid 3.1.",
DeprecationWarning,
stacklevel=2,
)
if self.arguments:
index, argument = _find_arg(argname, self.arguments)
if argument:
return index, argument
return None, None
def get_children(self):
yield from self.posonlyargs or ()