forked from pylint-dev/pylint
/
utils.py
1764 lines (1468 loc) · 58.2 KB
/
utils.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 GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
"""Some functions that may be useful for various checkers."""
from __future__ import annotations
import builtins
import itertools
import numbers
import re
import string
import warnings
from collections.abc import Iterable
from functools import lru_cache, partial
from re import Match
from typing import TYPE_CHECKING, Callable, TypeVar
import _string
import astroid.objects
from astroid import TooManyLevelsError, nodes
from astroid.context import InferenceContext
from pylint.constants import TYPING_TYPE_CHECKS_GUARDS
if TYPE_CHECKING:
from pylint.checkers import BaseChecker
_NodeT = TypeVar("_NodeT", bound=nodes.NodeNG)
_CheckerT = TypeVar("_CheckerT", bound="BaseChecker")
AstCallbackMethod = Callable[[_CheckerT, _NodeT], None]
COMP_NODE_TYPES = (
nodes.ListComp,
nodes.SetComp,
nodes.DictComp,
nodes.GeneratorExp,
)
EXCEPTIONS_MODULE = "builtins"
ABC_MODULES = {"abc", "_py_abc"}
ABC_METHODS = {
"abc.abstractproperty",
"abc.abstractmethod",
"abc.abstractclassmethod",
"abc.abstractstaticmethod",
}
TYPING_PROTOCOLS = frozenset(
{"typing.Protocol", "typing_extensions.Protocol", ".Protocol"}
)
ITER_METHOD = "__iter__"
AITER_METHOD = "__aiter__"
NEXT_METHOD = "__next__"
GETITEM_METHOD = "__getitem__"
CLASS_GETITEM_METHOD = "__class_getitem__"
SETITEM_METHOD = "__setitem__"
DELITEM_METHOD = "__delitem__"
CONTAINS_METHOD = "__contains__"
KEYS_METHOD = "keys"
# Dictionary which maps the number of expected parameters a
# special method can have to a set of special methods.
# The following keys are used to denote the parameters restrictions:
#
# * None: variable number of parameters
# * number: exactly that number of parameters
# * tuple: these are the odd ones. Basically it means that the function
# can work with any number of arguments from that tuple,
# although it's best to implement it in order to accept
# all of them.
_SPECIAL_METHODS_PARAMS = {
None: ("__new__", "__init__", "__call__"),
0: (
"__del__",
"__repr__",
"__str__",
"__bytes__",
"__hash__",
"__bool__",
"__dir__",
"__len__",
"__length_hint__",
"__iter__",
"__reversed__",
"__neg__",
"__pos__",
"__abs__",
"__invert__",
"__complex__",
"__int__",
"__float__",
"__index__",
"__trunc__",
"__floor__",
"__ceil__",
"__enter__",
"__aenter__",
"__getnewargs_ex__",
"__getnewargs__",
"__getstate__",
"__reduce__",
"__copy__",
"__unicode__",
"__nonzero__",
"__await__",
"__aiter__",
"__anext__",
"__fspath__",
"__subclasses__",
"__init_subclass__",
),
1: (
"__format__",
"__lt__",
"__le__",
"__eq__",
"__ne__",
"__gt__",
"__ge__",
"__getattr__",
"__getattribute__",
"__delattr__",
"__delete__",
"__instancecheck__",
"__subclasscheck__",
"__getitem__",
"__missing__",
"__delitem__",
"__contains__",
"__add__",
"__sub__",
"__mul__",
"__truediv__",
"__floordiv__",
"__rfloordiv__",
"__mod__",
"__divmod__",
"__lshift__",
"__rshift__",
"__and__",
"__xor__",
"__or__",
"__radd__",
"__rsub__",
"__rmul__",
"__rtruediv__",
"__rmod__",
"__rdivmod__",
"__rpow__",
"__rlshift__",
"__rrshift__",
"__rand__",
"__rxor__",
"__ror__",
"__iadd__",
"__isub__",
"__imul__",
"__itruediv__",
"__ifloordiv__",
"__imod__",
"__ilshift__",
"__irshift__",
"__iand__",
"__ixor__",
"__ior__",
"__ipow__",
"__setstate__",
"__reduce_ex__",
"__deepcopy__",
"__cmp__",
"__matmul__",
"__rmatmul__",
"__imatmul__",
"__div__",
),
2: ("__setattr__", "__get__", "__set__", "__setitem__", "__set_name__"),
3: ("__exit__", "__aexit__"),
(0, 1): ("__round__",),
(1, 2): ("__pow__",),
}
SPECIAL_METHODS_PARAMS = {
name: params
for params, methods in _SPECIAL_METHODS_PARAMS.items()
for name in methods
}
PYMETHODS = set(SPECIAL_METHODS_PARAMS)
SUBSCRIPTABLE_CLASSES_PEP585 = frozenset(
(
"builtins.tuple",
"builtins.list",
"builtins.dict",
"builtins.set",
"builtins.frozenset",
"builtins.type",
"collections.deque",
"collections.defaultdict",
"collections.OrderedDict",
"collections.Counter",
"collections.ChainMap",
"_collections_abc.Awaitable",
"_collections_abc.Coroutine",
"_collections_abc.AsyncIterable",
"_collections_abc.AsyncIterator",
"_collections_abc.AsyncGenerator",
"_collections_abc.Iterable",
"_collections_abc.Iterator",
"_collections_abc.Generator",
"_collections_abc.Reversible",
"_collections_abc.Container",
"_collections_abc.Collection",
"_collections_abc.Callable",
"_collections_abc.Set",
"_collections_abc.MutableSet",
"_collections_abc.Mapping",
"_collections_abc.MutableMapping",
"_collections_abc.Sequence",
"_collections_abc.MutableSequence",
"_collections_abc.ByteString",
"_collections_abc.MappingView",
"_collections_abc.KeysView",
"_collections_abc.ItemsView",
"_collections_abc.ValuesView",
"contextlib.AbstractContextManager",
"contextlib.AbstractAsyncContextManager",
"re.Pattern",
"re.Match",
)
)
class NoSuchArgumentError(Exception):
pass
class InferredTypeError(Exception):
pass
def is_inside_lambda(node: nodes.NodeNG) -> bool:
"""Return whether the given node is inside a lambda."""
warnings.warn(
"utils.is_inside_lambda will be removed in favour of calling "
"utils.get_node_first_ancestor_of_type(x, nodes.Lambda) in pylint 3.0",
DeprecationWarning,
)
return any(isinstance(parent, nodes.Lambda) for parent in node.node_ancestors())
def get_all_elements(
node: nodes.NodeNG,
) -> Iterable[nodes.NodeNG]:
"""Recursively returns all atoms in nested lists and tuples."""
if isinstance(node, (nodes.Tuple, nodes.List)):
for child in node.elts:
yield from get_all_elements(child)
else:
yield node
def is_super(node: nodes.NodeNG) -> bool:
"""Return True if the node is referencing the "super" builtin function."""
if getattr(node, "name", None) == "super" and node.root().name == "builtins":
return True
return False
def is_error(node: nodes.FunctionDef) -> bool:
"""Return true if the given function node only raises an exception."""
return len(node.body) == 1 and isinstance(node.body[0], nodes.Raise)
builtins = builtins.__dict__.copy() # type: ignore[assignment]
SPECIAL_BUILTINS = ("__builtins__",) # '__path__', '__file__')
def is_builtin_object(node: nodes.NodeNG) -> bool:
"""Returns True if the given node is an object from the __builtin__ module."""
return node and node.root().name == "builtins"
def is_builtin(name: str) -> bool:
"""Return true if <name> could be considered as a builtin defined by python."""
return name in builtins or name in SPECIAL_BUILTINS # type: ignore[attr-defined]
def is_defined_in_scope(
var_node: nodes.NodeNG,
varname: str,
scope: nodes.NodeNG,
) -> bool:
if isinstance(scope, nodes.If):
for node in scope.body:
if (
isinstance(node, nodes.Assign)
and any(
isinstance(target, nodes.AssignName) and target.name == varname
for target in node.targets
)
) or (isinstance(node, nodes.Nonlocal) and varname in node.names):
return True
elif isinstance(scope, (COMP_NODE_TYPES, nodes.For)):
for ass_node in scope.nodes_of_class(nodes.AssignName):
if ass_node.name == varname:
return True
elif isinstance(scope, nodes.With):
for expr, ids in scope.items:
if expr.parent_of(var_node):
break
if ids and isinstance(ids, nodes.AssignName) and ids.name == varname:
return True
elif isinstance(scope, (nodes.Lambda, nodes.FunctionDef)):
if scope.args.is_argument(varname):
# If the name is found inside a default value
# of a function, then let the search continue
# in the parent's tree.
if scope.args.parent_of(var_node):
try:
scope.args.default_value(varname)
scope = scope.parent
is_defined_in_scope(var_node, varname, scope)
except astroid.NoDefault:
pass
return True
if getattr(scope, "name", None) == varname:
return True
elif isinstance(scope, nodes.ExceptHandler):
if isinstance(scope.name, nodes.AssignName):
ass_node = scope.name
if ass_node.name == varname:
return True
return False
def is_defined_before(var_node: nodes.Name) -> bool:
"""Check if the given variable node is defined before.
Verify that the variable node is defined by a parent node
(list, set, dict, or generator comprehension, lambda)
or in a previous sibling node on the same line
(statement_defining ; statement_using).
"""
varname = var_node.name
for parent in var_node.node_ancestors():
if is_defined_in_scope(var_node, varname, parent):
return True
# possibly multiple statements on the same line using semicolon separator
stmt = var_node.statement(future=True)
_node = stmt.previous_sibling()
lineno = stmt.fromlineno
while _node and _node.fromlineno == lineno:
for assign_node in _node.nodes_of_class(nodes.AssignName):
if assign_node.name == varname:
return True
for imp_node in _node.nodes_of_class((nodes.ImportFrom, nodes.Import)):
if varname in [name[1] or name[0] for name in imp_node.names]:
return True
_node = _node.previous_sibling()
return False
def is_default_argument(node: nodes.NodeNG, scope: nodes.NodeNG | None = None) -> bool:
"""Return true if the given Name node is used in function or lambda
default argument's value.
"""
if not scope:
scope = node.scope()
if isinstance(scope, (nodes.FunctionDef, nodes.Lambda)):
all_defaults = itertools.chain(
scope.args.defaults, (d for d in scope.args.kw_defaults if d is not None)
)
return any(
default_name_node is node
for default_node in all_defaults
for default_name_node in default_node.nodes_of_class(nodes.Name)
)
return False
def is_func_decorator(node: nodes.NodeNG) -> bool:
"""Return true if the name is used in function decorator."""
for parent in node.node_ancestors():
if isinstance(parent, nodes.Decorators):
return True
if parent.is_statement or isinstance(
parent,
(
nodes.Lambda,
nodes.ComprehensionScope,
nodes.ListComp,
),
):
break
return False
def is_ancestor_name(frame: nodes.ClassDef, node: nodes.NodeNG) -> bool:
"""Return whether `frame` is an astroid.Class node with `node` in the
subtree of its bases attribute.
"""
if not isinstance(frame, nodes.ClassDef):
return False
return any(node in base.nodes_of_class(nodes.Name) for base in frame.bases)
def is_being_called(node: nodes.NodeNG) -> bool:
"""Return True if node is the function being called in a Call node."""
return isinstance(node.parent, nodes.Call) and node.parent.func is node
def assign_parent(node: nodes.NodeNG) -> nodes.NodeNG:
"""Return the higher parent which is not an AssignName, Tuple or List node."""
while node and isinstance(node, (nodes.AssignName, nodes.Tuple, nodes.List)):
node = node.parent
return node
def overrides_a_method(class_node: nodes.ClassDef, name: str) -> bool:
"""Return True if <name> is a method overridden from an ancestor
which is not the base object class.
"""
for ancestor in class_node.ancestors():
if ancestor.name == "object":
continue
if name in ancestor and isinstance(ancestor[name], nodes.FunctionDef):
return True
return False
def only_required_for_messages(
*messages: str,
) -> Callable[
[AstCallbackMethod[_CheckerT, _NodeT]], AstCallbackMethod[_CheckerT, _NodeT]
]:
"""Decorator to store messages that are handled by a checker method as an
attribute of the function object.
This information is used by ``ASTWalker`` to decide whether to call the decorated
method or not. If none of the messages is enabled, the method will be skipped.
Therefore, the list of messages must be well maintained at all times!
This decorator only has an effect on ``visit_*`` and ``leave_*`` methods
of a class inheriting from ``BaseChecker``.
"""
def store_messages(
func: AstCallbackMethod[_CheckerT, _NodeT]
) -> AstCallbackMethod[_CheckerT, _NodeT]:
setattr(func, "checks_msgs", messages)
return func
return store_messages
def check_messages(
*messages: str,
) -> Callable[
[AstCallbackMethod[_CheckerT, _NodeT]], AstCallbackMethod[_CheckerT, _NodeT]
]:
"""Kept for backwards compatibility, deprecated.
Use only_required_for_messages instead, which conveys the intent of the decorator much clearer.
"""
warnings.warn(
"utils.check_messages will be removed in favour of calling "
"utils.only_required_for_messages in pylint 3.0",
DeprecationWarning,
)
return only_required_for_messages(*messages)
class IncompleteFormatString(Exception):
"""A format string ended in the middle of a format specifier."""
class UnsupportedFormatCharacter(Exception):
"""A format character in a format string is not one of the supported
format characters.
"""
def __init__(self, index):
super().__init__(index)
self.index = index
def parse_format_string(
format_string: str,
) -> tuple[set[str], int, dict[str, str], list[str]]:
"""Parses a format string, returning a tuple (keys, num_args).
Where 'keys' is the set of mapping keys in the format string, and 'num_args' is the number
of arguments required by the format string. Raises IncompleteFormatString or
UnsupportedFormatCharacter if a parse error occurs.
"""
keys = set()
key_types = {}
pos_types = []
num_args = 0
def next_char(i):
i += 1
if i == len(format_string):
raise IncompleteFormatString
return (i, format_string[i])
i = 0
while i < len(format_string):
char = format_string[i]
if char == "%":
i, char = next_char(i)
# Parse the mapping key (optional).
key = None
if char == "(":
depth = 1
i, char = next_char(i)
key_start = i
while depth != 0:
if char == "(":
depth += 1
elif char == ")":
depth -= 1
i, char = next_char(i)
key_end = i - 1
key = format_string[key_start:key_end]
# Parse the conversion flags (optional).
while char in "#0- +":
i, char = next_char(i)
# Parse the minimum field width (optional).
if char == "*":
num_args += 1
i, char = next_char(i)
else:
while char in string.digits:
i, char = next_char(i)
# Parse the precision (optional).
if char == ".":
i, char = next_char(i)
if char == "*":
num_args += 1
i, char = next_char(i)
else:
while char in string.digits:
i, char = next_char(i)
# Parse the length modifier (optional).
if char in "hlL":
i, char = next_char(i)
# Parse the conversion type (mandatory).
flags = "diouxXeEfFgGcrs%a"
if char not in flags:
raise UnsupportedFormatCharacter(i)
if key:
keys.add(key)
key_types[key] = char
elif char != "%":
num_args += 1
pos_types.append(char)
i += 1
return keys, num_args, key_types, pos_types
def split_format_field_names(format_string) -> tuple[str, Iterable[tuple[bool, str]]]:
try:
return _string.formatter_field_name_split(format_string)
except ValueError as e:
raise IncompleteFormatString() from e
def collect_string_fields(format_string) -> Iterable[str | None]:
"""Given a format string, return an iterator
of all the valid format fields.
It handles nested fields as well.
"""
formatter = string.Formatter()
try:
parseiterator = formatter.parse(format_string)
for result in parseiterator:
if all(item is None for item in result[1:]):
# not a replacement format
continue
name = result[1]
nested = result[2]
yield name
if nested:
yield from collect_string_fields(nested)
except ValueError as exc:
# Probably the format string is invalid.
if exc.args[0].startswith("cannot switch from manual"):
# On Jython, parsing a string with both manual
# and automatic positions will fail with a ValueError,
# while on CPython it will simply return the fields,
# the validation being done in the interpreter (?).
# We're just returning two mixed fields in order
# to trigger the format-combined-specification check.
yield ""
yield "1"
return
raise IncompleteFormatString(format_string) from exc
def parse_format_method_string(
format_string: str,
) -> tuple[list[tuple[str, list[tuple[bool, str]]]], int, int]:
"""Parses a PEP 3101 format string, returning a tuple of
(keyword_arguments, implicit_pos_args_cnt, explicit_pos_args).
keyword_arguments is the set of mapping keys in the format string, implicit_pos_args_cnt
is the number of arguments required by the format string and
explicit_pos_args is the number of arguments passed with the position.
"""
keyword_arguments = []
implicit_pos_args_cnt = 0
explicit_pos_args = set()
for name in collect_string_fields(format_string):
if name and str(name).isdigit():
explicit_pos_args.add(str(name))
elif name:
keyname, fielditerator = split_format_field_names(name)
if isinstance(keyname, numbers.Number):
explicit_pos_args.add(str(keyname))
try:
keyword_arguments.append((keyname, list(fielditerator)))
except ValueError as e:
raise IncompleteFormatString() from e
else:
implicit_pos_args_cnt += 1
return keyword_arguments, implicit_pos_args_cnt, len(explicit_pos_args)
def is_attr_protected(attrname: str) -> bool:
"""Return True if attribute name is protected (start with _ and some other
details), False otherwise.
"""
return (
attrname[0] == "_"
and attrname != "_"
and not (attrname.startswith("__") and attrname.endswith("__"))
)
def node_frame_class(node: nodes.NodeNG) -> nodes.ClassDef | None:
"""Return the class that is wrapping the given node.
The function returns a class for a method node (or a staticmethod or a
classmethod), otherwise it returns `None`.
"""
klass = node.frame(future=True)
nodes_to_check = (
nodes.NodeNG,
astroid.UnboundMethod,
astroid.BaseInstance,
)
while (
klass
and isinstance(klass, nodes_to_check)
and not isinstance(klass, nodes.ClassDef)
):
if klass.parent is None:
return None
klass = klass.parent.frame(future=True)
return klass
def get_outer_class(class_node: astroid.ClassDef) -> astroid.ClassDef | None:
"""Return the class that is the outer class of given (nested) class_node."""
parent_klass = class_node.parent.frame(future=True)
return parent_klass if isinstance(parent_klass, astroid.ClassDef) else None
def is_attr_private(attrname: str) -> Match[str] | None:
"""Check that attribute name is private (at least two leading underscores,
at most one trailing underscore).
"""
regex = re.compile("^_{2,}.*[^_]+_?$")
return regex.match(attrname)
def get_argument_from_call(
call_node: nodes.Call, position: int | None = None, keyword: str | None = None
) -> nodes.Name:
"""Returns the specified argument from a function call.
:param nodes.Call call_node: Node representing a function call to check.
:param int position: position of the argument.
:param str keyword: the keyword of the argument.
:returns: The node representing the argument, None if the argument is not found.
:rtype: nodes.Name
:raises ValueError: if both position and keyword are None.
:raises NoSuchArgumentError: if no argument at the provided position or with
the provided keyword.
"""
if position is None and keyword is None:
raise ValueError("Must specify at least one of: position or keyword.")
if position is not None:
try:
return call_node.args[position]
except IndexError:
pass
if keyword and call_node.keywords:
for arg in call_node.keywords:
if arg.arg == keyword:
return arg.value
raise NoSuchArgumentError
def inherit_from_std_ex(node: nodes.NodeNG | astroid.Instance) -> bool:
"""Return whether the given class node is subclass of
exceptions.Exception.
"""
ancestors = node.ancestors() if hasattr(node, "ancestors") else []
return any(
ancestor.name in {"Exception", "BaseException"}
and ancestor.root().name == EXCEPTIONS_MODULE
for ancestor in itertools.chain([node], ancestors)
)
def error_of_type(handler: nodes.ExceptHandler, error_type) -> bool:
"""Check if the given exception handler catches
the given error_type.
The *handler* parameter is a node, representing an ExceptHandler node.
The *error_type* can be an exception, such as AttributeError,
the name of an exception, or it can be a tuple of errors.
The function will return True if the handler catches any of the
given errors.
"""
def stringify_error(error):
if not isinstance(error, str):
return error.__name__
return error
if not isinstance(error_type, tuple):
error_type = (error_type,)
expected_errors = {stringify_error(error) for error in error_type}
if not handler.type:
return False
return handler.catch(expected_errors)
def decorated_with_property(node: nodes.FunctionDef) -> bool:
"""Detect if the given function node is decorated with a property."""
if not node.decorators:
return False
for decorator in node.decorators.nodes:
try:
if _is_property_decorator(decorator):
return True
except astroid.InferenceError:
pass
return False
def _is_property_kind(node, *kinds):
if not isinstance(node, (astroid.UnboundMethod, nodes.FunctionDef)):
return False
if node.decorators:
for decorator in node.decorators.nodes:
if isinstance(decorator, nodes.Attribute) and decorator.attrname in kinds:
return True
return False
def is_property_setter(node: nodes.FunctionDef) -> bool:
"""Check if the given node is a property setter."""
return _is_property_kind(node, "setter")
def is_property_deleter(node: nodes.FunctionDef) -> bool:
"""Check if the given node is a property deleter."""
return _is_property_kind(node, "deleter")
def is_property_setter_or_deleter(node: nodes.FunctionDef) -> bool:
"""Check if the given node is either a property setter or a deleter."""
return _is_property_kind(node, "setter", "deleter")
def _is_property_decorator(decorator: nodes.Name) -> bool:
for inferred in decorator.infer():
if isinstance(inferred, nodes.ClassDef):
if inferred.qname() in {"builtins.property", "functools.cached_property"}:
return True
for ancestor in inferred.ancestors():
if ancestor.name == "property" and ancestor.root().name == "builtins":
return True
elif isinstance(inferred, nodes.FunctionDef):
# If decorator is function, check if it has exactly one return
# and the return is itself a function decorated with property
returns: list[nodes.Return] = list(
inferred._get_return_nodes_skip_functions()
)
if len(returns) == 1 and isinstance(
returns[0].value, (nodes.Name, nodes.Attribute)
):
inferred = safe_infer(returns[0].value)
if (
inferred
and isinstance(inferred, astroid.objects.Property)
and isinstance(inferred.function, nodes.FunctionDef)
):
return decorated_with_property(inferred.function)
return False
def decorated_with(
func: (
nodes.ClassDef | nodes.FunctionDef | astroid.BoundMethod | astroid.UnboundMethod
),
qnames: Iterable[str],
) -> bool:
"""Determine if the `func` node has a decorator with the qualified name `qname`."""
decorators = func.decorators.nodes if func.decorators else []
for decorator_node in decorators:
if isinstance(decorator_node, nodes.Call):
# We only want to infer the function name
decorator_node = decorator_node.func
try:
if any(
i.name in qnames or i.qname() in qnames
for i in decorator_node.infer()
if i is not None and i != astroid.Uninferable
):
return True
except astroid.InferenceError:
continue
return False
def uninferable_final_decorators(
node: nodes.Decorators,
) -> list[nodes.Attribute | nodes.Name | None]:
"""Return a list of uninferable `typing.final` decorators in `node`.
This function is used to determine if the `typing.final` decorator is used
with an unsupported Python version; the decorator cannot be inferred when
using a Python version lower than 3.8.
"""
decorators = []
for decorator in getattr(node, "nodes", []):
if isinstance(decorator, nodes.Attribute) and hasattr(decorator.expr, "lookup"):
_, import_nodes = decorator.expr.lookup(decorator.expr.name)
# The `final` decorator is expected to be found in the
# import_nodes. In case it is not, continue.
if not import_nodes:
continue
import_node = import_nodes[0]
elif isinstance(decorator, nodes.Name):
lookup_values = decorator.lookup(decorator.name)
if lookup_values[1]:
import_node = lookup_values[1][0]
else:
continue # pragma: no cover # Covered on Python < 3.8
else:
continue
if not isinstance(import_node, (astroid.Import, astroid.ImportFrom)):
continue
import_names = dict(import_node.names)
# from typing import final
is_from_import = ("final" in import_names) and import_node.modname == "typing"
# import typing
is_import = ("typing" in import_names) and getattr(
decorator, "attrname", None
) == "final"
if (is_from_import or is_import) and safe_infer(decorator) in [
astroid.Uninferable,
None,
]:
decorators.append(decorator)
return decorators
@lru_cache(maxsize=1024)
def unimplemented_abstract_methods(
node: nodes.ClassDef, is_abstract_cb: nodes.FunctionDef = None
) -> dict[str, nodes.NodeNG]:
"""Get the unimplemented abstract methods for the given *node*.
A method can be considered abstract if the callback *is_abstract_cb*
returns a ``True`` value. The check defaults to verifying that
a method is decorated with abstract methods.
The function will work only for new-style classes. For old-style
classes, it will simply return an empty dictionary.
For the rest of them, it will return a dictionary of abstract method
names and their inferred objects.
"""
if is_abstract_cb is None:
is_abstract_cb = partial(decorated_with, qnames=ABC_METHODS)
visited: dict[str, nodes.NodeNG] = {}
try:
mro = reversed(node.mro())
except NotImplementedError:
# Old style class, it will not have a mro.
return {}
except astroid.ResolveError:
# Probably inconsistent hierarchy, don't try to figure this out here.
return {}
for ancestor in mro:
for obj in ancestor.values():
inferred = obj
if isinstance(obj, nodes.AssignName):
inferred = safe_infer(obj)
if not inferred:
# Might be an abstract function,
# but since we don't have enough information
# in order to take this decision, we're taking
# the *safe* decision instead.
if obj.name in visited:
del visited[obj.name]
continue
if not isinstance(inferred, nodes.FunctionDef):
if obj.name in visited:
del visited[obj.name]
if isinstance(inferred, nodes.FunctionDef):
# It's critical to use the original name,
# since after inferring, an object can be something
# else than expected, as in the case of the
# following assignment.
#
# class A:
# def keys(self): pass
# __iter__ = keys
abstract = is_abstract_cb(inferred)
if abstract:
visited[obj.name] = inferred
elif not abstract and obj.name in visited:
del visited[obj.name]
return visited
def find_try_except_wrapper_node(
node: nodes.NodeNG,
) -> nodes.ExceptHandler | nodes.TryExcept | None:
"""Return the ExceptHandler or the TryExcept node in which the node is."""
current = node
ignores = (nodes.ExceptHandler, nodes.TryExcept)
while current and not isinstance(current.parent, ignores):
current = current.parent
if current and isinstance(current.parent, ignores):
return current.parent
return None
def find_except_wrapper_node_in_scope(
node: nodes.NodeNG,
) -> nodes.ExceptHandler | nodes.TryExcept | None:
"""Return the ExceptHandler in which the node is, without going out of scope."""
for current in node.node_ancestors():
if isinstance(current, astroid.scoped_nodes.LocalsDictNodeNG):
# If we're inside a function/class definition, we don't want to keep checking
# higher ancestors for `except` clauses, because if these exist, it means our
# function/class was defined in an `except` clause, rather than the current code
# actually running in an `except` clause.
return None
if isinstance(current, nodes.ExceptHandler):
return current
return None
def is_from_fallback_block(node: nodes.NodeNG) -> bool:
"""Check if the given node is from a fallback import block."""
context = find_try_except_wrapper_node(node)
if not context:
return False
if isinstance(context, nodes.ExceptHandler):
other_body = context.parent.body
handlers = context.parent.handlers
else:
other_body = itertools.chain.from_iterable(
handler.body for handler in context.handlers
)
handlers = context.handlers
has_fallback_imports = any(
isinstance(import_node, (nodes.ImportFrom, nodes.Import))
for import_node in other_body
)
ignores_import_error = _except_handlers_ignores_exceptions(
handlers, (ImportError, ModuleNotFoundError)
)
return ignores_import_error or has_fallback_imports
def _except_handlers_ignores_exceptions(
handlers: nodes.ExceptHandler,