/
classes.py
2394 lines (2137 loc) · 89.7 KB
/
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
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
# Copyright (c) 2010 Maarten ter Huurne <maarten@treewalker.org>
# Copyright (c) 2012-2014 Google, Inc.
# Copyright (c) 2012 FELD Boris <lothiraldan@gmail.com>
# Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2014 Michal Nowikowski <godfryd@gmail.com>
# Copyright (c) 2014 Brett Cannon <brett@python.org>
# Copyright (c) 2014 Arun Persaud <arun@nubati.net>
# Copyright (c) 2014 David Pursehouse <david.pursehouse@gmail.com>
# Copyright (c) 2015 Dmitry Pribysh <dmand@yandex.ru>
# Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
# Copyright (c) 2016-2017 Łukasz Rogalski <rogalski.91@gmail.com>
# Copyright (c) 2016 Alexander Todorov <atodorov@otb.bg>
# Copyright (c) 2016 Anthony Foglia <afoglia@users.noreply.github.com>
# Copyright (c) 2016 Florian Bruhin <me@the-compiler.org>
# Copyright (c) 2016 Moises Lopez <moylop260@vauxoo.com>
# Copyright (c) 2016 Jakub Wilk <jwilk@jwilk.net>
# Copyright (c) 2017, 2019-2020 hippo91 <guillaume.peillex@gmail.com>
# Copyright (c) 2018, 2020 Anthony Sottile <asottile@umich.edu>
# Copyright (c) 2018-2019 Nick Drozd <nicholasdrozd@gmail.com>
# Copyright (c) 2018-2019 Ashley Whetter <ashley@awhetter.co.uk>
# Copyright (c) 2018 Lucas Cimon <lucas.cimon@gmail.com>
# Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com>
# Copyright (c) 2018 ssolanki <sushobhitsolanki@gmail.com>
# Copyright (c) 2018 Ben Green <benhgreen@icloud.com>
# Copyright (c) 2018 Ville Skyttä <ville.skytta@iki.fi>
# Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyright (c) 2019 mattlbeck <17108752+mattlbeck@users.noreply.github.com>
# Copyright (c) 2019-2020 craig-sh <craig-sh@users.noreply.github.com>
# Copyright (c) 2019 Janne Rönkkö <jannero@users.noreply.github.com>
# Copyright (c) 2019 Hugo van Kemenade <hugovk@users.noreply.github.com>
# Copyright (c) 2019 Grygorii Iermolenko <gyermolenko@gmail.com>
# Copyright (c) 2019 Andrzej Klajnert <github@aklajnert.pl>
# Copyright (c) 2019 Pascal Corpet <pcorpet@users.noreply.github.com>
# Copyright (c) 2020 GergelyKalmar <gergely.kalmar@logikal.jp>
# Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
# Copyright (c) 2021 yushao2 <36848472+yushao2@users.noreply.github.com>
# Copyright (c) 2021 Yu Shao, Pang <p.yushao2@gmail.com>
# Copyright (c) 2021 Konstantina Saketou <56515303+ksaketou@users.noreply.github.com>
# Copyright (c) 2021 James Sinclair <james@nurfherder.com>
# Copyright (c) 2021 tiagohonorato <61059243+tiagohonorato@users.noreply.github.com>
# 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
"""classes checker for Python code
"""
import collections
from itertools import chain, zip_longest
from typing import List, Pattern
import astroid
from astroid import nodes
from pylint.checkers import BaseChecker, utils
from pylint.checkers.utils import (
PYMETHODS,
SPECIAL_METHODS_PARAMS,
check_messages,
class_is_abstract,
decorated_with,
decorated_with_property,
has_known_bases,
is_attr_private,
is_attr_protected,
is_builtin_object,
is_comprehension,
is_iterable,
is_overload_stub,
is_property_setter,
is_property_setter_or_deleter,
is_protocol_class,
node_frame_class,
overrides_a_method,
safe_infer,
unimplemented_abstract_methods,
)
from pylint.interfaces import IAstroidChecker
from pylint.utils import get_global_option
NEXT_METHOD = "__next__"
INVALID_BASE_CLASSES = {"bool", "range", "slice", "memoryview"}
BUILTIN_DECORATORS = {"builtins.property", "builtins.classmethod"}
# Dealing with useless override detection, with regard
# to parameters vs arguments
_CallSignature = collections.namedtuple(
"_CallSignature", "args kws starred_args starred_kws"
)
_ParameterSignature = collections.namedtuple(
"_ParameterSignature", "args kwonlyargs varargs kwargs"
)
def _signature_from_call(call):
kws = {}
args = []
starred_kws = []
starred_args = []
for keyword in call.keywords or []:
arg, value = keyword.arg, keyword.value
if arg is None and isinstance(value, nodes.Name):
# Starred node and we are interested only in names,
# otherwise some transformation might occur for the parameter.
starred_kws.append(value.name)
elif isinstance(value, nodes.Name):
kws[arg] = value.name
else:
kws[arg] = None
for arg in call.args:
if isinstance(arg, nodes.Starred) and isinstance(arg.value, nodes.Name):
# Positional variadic and a name, otherwise some transformation
# might have occurred.
starred_args.append(arg.value.name)
elif isinstance(arg, nodes.Name):
args.append(arg.name)
else:
args.append(None)
return _CallSignature(args, kws, starred_args, starred_kws)
def _signature_from_arguments(arguments):
kwarg = arguments.kwarg
vararg = arguments.vararg
args = [
arg.name
for arg in chain(arguments.posonlyargs, arguments.args)
if arg.name != "self"
]
kwonlyargs = [arg.name for arg in arguments.kwonlyargs]
return _ParameterSignature(args, kwonlyargs, vararg, kwarg)
def _definition_equivalent_to_call(definition, call):
"""Check if a definition signature is equivalent to a call."""
if definition.kwargs:
same_kw_variadics = definition.kwargs in call.starred_kws
else:
same_kw_variadics = not call.starred_kws
if definition.varargs:
same_args_variadics = definition.varargs in call.starred_args
else:
same_args_variadics = not call.starred_args
same_kwonlyargs = all(kw in call.kws for kw in definition.kwonlyargs)
same_args = definition.args == call.args
no_additional_kwarg_arguments = True
if call.kws:
for keyword in call.kws:
is_arg = keyword in call.args
is_kwonly = keyword in definition.kwonlyargs
if not is_arg and not is_kwonly:
# Maybe this argument goes into **kwargs,
# or it is an extraneous argument.
# In any case, the signature is different than
# the call site, which stops our search.
no_additional_kwarg_arguments = False
break
return all(
(
same_args,
same_kwonlyargs,
same_args_variadics,
same_kw_variadics,
no_additional_kwarg_arguments,
)
)
# Deal with parameters overridding in two methods.
def _positional_parameters(method):
positional = method.args.args
if method.type in ("classmethod", "method"):
positional = positional[1:]
return positional
def _get_node_type(node, potential_types):
"""
Return the type of the node if it exists in potential_types.
Args:
node (astroid.node): node to get the type of.
potential_types (tuple): potential types of the node.
Returns:
type: type of the node or None.
"""
for potential_type in potential_types:
if isinstance(node, potential_type):
return potential_type
return None
def _check_arg_equality(node_a, node_b, attr_name):
"""
Check equality of nodes based on the comparison of their attributes named attr_name.
Args:
node_a (astroid.node): first node to compare.
node_b (astroid.node): second node to compare.
attr_name (str): name of the nodes attribute to use for comparison.
Returns:
bool: True if node_a.attr_name == node_b.attr_name, False otherwise.
"""
return getattr(node_a, attr_name) == getattr(node_b, attr_name)
def _has_different_parameters_default_value(original, overridden):
"""
Check if original and overridden methods arguments have different default values
Return True if one of the overridden arguments has a default
value different from the default value of the original argument
If one of the method doesn't have argument (.args is None)
return False
"""
if original.args is None or overridden.args is None:
return False
all_args = chain(original.args, original.kwonlyargs)
original_param_names = [param.name for param in all_args]
default_missing = object()
for param_name in original_param_names:
try:
original_default = original.default_value(param_name)
except astroid.exceptions.NoDefault:
original_default = default_missing
try:
overridden_default = overridden.default_value(param_name)
except astroid.exceptions.NoDefault:
overridden_default = default_missing
default_list = [
arg == default_missing for arg in (original_default, overridden_default)
]
if any(default_list) and not all(default_list):
# Only one arg has no default value
return True
astroid_type_compared_attr = {
nodes.Const: "value",
nodes.ClassDef: "name",
nodes.Tuple: "elts",
nodes.List: "elts",
nodes.Dict: "items",
}
handled_types = tuple(
astroid_type for astroid_type in astroid_type_compared_attr
)
original_type = _get_node_type(original_default, handled_types)
if original_type:
# We handle only astroid types that are inside the dict astroid_type_compared_attr
if not isinstance(overridden_default, original_type):
# Two args with same name but different types
return True
if not _check_arg_equality(
original_default,
overridden_default,
astroid_type_compared_attr[original_type],
):
# Two args with same type but different values
return True
return False
def _has_different_parameters(
original: List[nodes.AssignName],
overridden: List[nodes.AssignName],
dummy_parameter_regex: Pattern,
) -> List[str]:
result = []
zipped = zip_longest(original, overridden)
for original_param, overridden_param in zipped:
params = (original_param, overridden_param)
if not all(params):
return ["Number of parameters "]
# check for the arguments' name
names = [param.name for param in params]
if any(dummy_parameter_regex.match(name) for name in names):
continue
if original_param.name != overridden_param.name:
result.append(
f"Parameter '{original_param.name}' has been renamed "
f"to '{overridden_param.name}' in"
)
return result
def _different_parameters(
original: nodes.FunctionDef,
overridden: nodes.FunctionDef,
dummy_parameter_regex: Pattern,
) -> List[str]:
"""Determine if the two methods have different parameters
They are considered to have different parameters if:
* they have different positional parameters, including different names
* one of the methods is having variadics, while the other is not
* they have different keyword only parameters.
"""
output_messages = []
original_parameters = _positional_parameters(original)
overridden_parameters = _positional_parameters(overridden)
# Copy kwonlyargs list so that we don't affect later function linting
original_kwonlyargs = original.args.kwonlyargs
# Allow positional/keyword variadic in overridden to match against any
# positional/keyword argument in original.
# Keep any arguments that are found seperately in overridden to satisfy
# later tests
if overridden.args.vararg:
overidden_names = [v.name for v in overridden_parameters]
original_parameters = [
v for v in original_parameters if v.name in overidden_names
]
if overridden.args.kwarg:
overidden_names = [v.name for v in overridden.args.kwonlyargs]
original_kwonlyargs = [
v for v in original.args.kwonlyargs if v.name in overidden_names
]
different_positional = _has_different_parameters(
original_parameters, overridden_parameters, dummy_parameter_regex
)
different_kwonly = _has_different_parameters(
original_kwonlyargs, overridden.args.kwonlyargs, dummy_parameter_regex
)
if different_kwonly and different_positional:
if "Number " in different_positional[0] and "Number " in different_kwonly[0]:
output_messages.append("Number of parameters ")
output_messages += different_positional[1:]
output_messages += different_kwonly[1:]
else:
output_messages += different_positional
output_messages += different_kwonly
else:
if different_positional:
output_messages += different_positional
if different_kwonly:
output_messages += different_kwonly
if original.name in PYMETHODS:
# Ignore the difference for special methods. If the parameter
# numbers are different, then that is going to be caught by
# unexpected-special-method-signature.
# If the names are different, it doesn't matter, since they can't
# be used as keyword arguments anyway.
output_messages.clear()
# Arguments will only violate LSP if there are variadics in the original
# that are then removed from the overridden
kwarg_lost = original.args.kwarg and not overridden.args.kwarg
vararg_lost = original.args.vararg and not overridden.args.vararg
if kwarg_lost or vararg_lost:
output_messages += ["Variadics removed in"]
return output_messages
def _is_invalid_base_class(cls):
return cls.name in INVALID_BASE_CLASSES and is_builtin_object(cls)
def _has_data_descriptor(cls, attr):
attributes = cls.getattr(attr)
for attribute in attributes:
try:
for inferred in attribute.infer():
if isinstance(inferred, astroid.Instance):
try:
inferred.getattr("__get__")
inferred.getattr("__set__")
except astroid.NotFoundError:
continue
else:
return True
except astroid.InferenceError:
# Can't infer, avoid emitting a false positive in this case.
return True
return False
def _called_in_methods(func, klass, methods):
"""Check if the func was called in any of the given methods,
belonging to the *klass*. Returns True if so, False otherwise.
"""
if not isinstance(func, nodes.FunctionDef):
return False
for method in methods:
try:
inferred = klass.getattr(method)
except astroid.NotFoundError:
continue
for infer_method in inferred:
for call in infer_method.nodes_of_class(nodes.Call):
try:
bound = next(call.func.infer())
except (astroid.InferenceError, StopIteration):
continue
if not isinstance(bound, astroid.BoundMethod):
continue
func_obj = bound._proxied
if isinstance(func_obj, astroid.UnboundMethod):
func_obj = func_obj._proxied
if func_obj.name == func.name:
return True
return False
def _is_attribute_property(name, klass):
"""Check if the given attribute *name* is a property in the given *klass*.
It will look for `property` calls or for functions
with the given name, decorated by `property` or `property`
subclasses.
Returns ``True`` if the name is a property in the given klass,
``False`` otherwise.
"""
try:
attributes = klass.getattr(name)
except astroid.NotFoundError:
return False
property_name = "builtins.property"
for attr in attributes:
if attr is astroid.Uninferable:
continue
try:
inferred = next(attr.infer())
except astroid.InferenceError:
continue
if isinstance(inferred, nodes.FunctionDef) and decorated_with_property(
inferred
):
return True
if inferred.pytype() != property_name:
continue
cls = node_frame_class(inferred)
if cls == klass.declared_metaclass():
continue
return True
return False
def _has_bare_super_call(fundef_node):
for call in fundef_node.nodes_of_class(nodes.Call):
func = call.func
if isinstance(func, nodes.Name) and func.name == "super" and not call.args:
return True
return False
def _safe_infer_call_result(node, caller, context=None):
"""
Safely infer the return value of a function.
Returns None if inference failed or if there is some ambiguity (more than
one node has been inferred). Otherwise returns inferred value.
"""
try:
inferit = node.infer_call_result(caller, context=context)
value = next(inferit)
except astroid.InferenceError:
return None # inference failed
except StopIteration:
return None # no values inferred
try:
next(inferit)
return None # there is ambiguity on the inferred node
except astroid.InferenceError:
return None # there is some kind of ambiguity
except StopIteration:
return value
def _has_same_layout_slots(slots, assigned_value):
inferred = next(assigned_value.infer())
if isinstance(inferred, nodes.ClassDef):
other_slots = inferred.slots()
if all(
first_slot and second_slot and first_slot.value == second_slot.value
for (first_slot, second_slot) in zip_longest(slots, other_slots)
):
return True
return False
MSGS = { # pylint: disable=consider-using-namedtuple-or-dataclass
"F0202": (
"Unable to check methods signature (%s / %s)",
"method-check-failed",
"Used when Pylint has been unable to check methods signature "
"compatibility for an unexpected reason. Please report this kind "
"if you don't make sense of it.",
),
"E0202": (
"An attribute defined in %s line %s hides this method",
"method-hidden",
"Used when a class defines a method which is hidden by an "
"instance attribute from an ancestor class or set by some "
"client code.",
),
"E0203": (
"Access to member %r before its definition line %s",
"access-member-before-definition",
"Used when an instance member is accessed before it's actually assigned.",
),
"W0201": (
"Attribute %r defined outside __init__",
"attribute-defined-outside-init",
"Used when an instance attribute is defined outside the __init__ method.",
),
"W0212": (
"Access to a protected member %s of a client class", # E0214
"protected-access",
"Used when a protected member (i.e. class member with a name "
"beginning with an underscore) is access outside the class or a "
"descendant of the class where it's defined.",
),
"E0211": (
"Method has no argument",
"no-method-argument",
"Used when a method which should have the bound instance as "
"first argument has no argument defined.",
),
"E0213": (
'Method should have "self" as first argument',
"no-self-argument",
'Used when a method has an attribute different the "self" as '
"first argument. This is considered as an error since this is "
"a so common convention that you shouldn't break it!",
),
"C0202": (
"Class method %s should have %s as first argument",
"bad-classmethod-argument",
"Used when a class method has a first argument named differently "
"than the value specified in valid-classmethod-first-arg option "
'(default to "cls"), recommended to easily differentiate them '
"from regular instance methods.",
),
"C0203": (
"Metaclass method %s should have %s as first argument",
"bad-mcs-method-argument",
"Used when a metaclass method has a first argument named "
"differently than the value specified in valid-classmethod-first"
'-arg option (default to "cls"), recommended to easily '
"differentiate them from regular instance methods.",
),
"C0204": (
"Metaclass class method %s should have %s as first argument",
"bad-mcs-classmethod-argument",
"Used when a metaclass class method has a first argument named "
"differently than the value specified in valid-metaclass-"
'classmethod-first-arg option (default to "mcs"), recommended to '
"easily differentiate them from regular instance methods.",
),
"W0211": (
"Static method with %r as first argument",
"bad-staticmethod-argument",
'Used when a static method has "self" or a value specified in '
"valid-classmethod-first-arg option or "
"valid-metaclass-classmethod-first-arg option as first argument.",
),
"R0201": (
"Method could be a function",
"no-self-use",
"Used when a method doesn't use its bound instance, and so could "
"be written as a function.",
),
"W0221": (
"%s %s %r method",
"arguments-differ",
"Used when a method has a different number of arguments than in "
"the implemented interface or in an overridden method.",
),
"W0222": (
"Signature differs from %s %r method",
"signature-differs",
"Used when a method signature is different than in the "
"implemented interface or in an overridden method.",
),
"W0223": (
"Method %r is abstract in class %r but is not overridden",
"abstract-method",
"Used when an abstract method (i.e. raise NotImplementedError) is "
"not overridden in concrete class.",
),
"W0231": (
"__init__ method from base class %r is not called",
"super-init-not-called",
"Used when an ancestor class method has an __init__ method "
"which is not called by a derived class.",
),
"W0232": (
"Class has no __init__ method",
"no-init",
"Used when a class has no __init__ method, neither its parent classes.",
),
"W0233": (
"__init__ method from a non direct base class %r is called",
"non-parent-init-called",
"Used when an __init__ method is called on a class which is not "
"in the direct ancestors for the analysed class.",
),
"W0235": (
"Useless super delegation in method %r",
"useless-super-delegation",
"Used whenever we can detect that an overridden method is useless, "
"relying on super() delegation to do the same thing as another method "
"from the MRO.",
),
"W0236": (
"Method %r was expected to be %r, found it instead as %r",
"invalid-overridden-method",
"Used when we detect that a method was overridden in a way "
"that does not match its base class "
"which could result in potential bugs at runtime.",
),
"W0237": (
"%s %s %r method",
"arguments-renamed",
"Used when a method parameter has a different name than in "
"the implemented interface or in an overridden method.",
),
"W0238": (
"Unused private member `%s.%s`",
"unused-private-member",
"Emitted when a private member of a class is defined but not used.",
),
"E0236": (
"Invalid object %r in __slots__, must contain only non empty strings",
"invalid-slots-object",
"Used when an invalid (non-string) object occurs in __slots__.",
),
"E0237": (
"Assigning to attribute %r not defined in class slots",
"assigning-non-slot",
"Used when assigning to an attribute not defined in the class slots.",
),
"E0238": (
"Invalid __slots__ object",
"invalid-slots",
"Used when an invalid __slots__ is found in class. "
"Only a string, an iterable or a sequence is permitted.",
),
"E0239": (
"Inheriting %r, which is not a class.",
"inherit-non-class",
"Used when a class inherits from something which is not a class.",
),
"E0240": (
"Inconsistent method resolution order for class %r",
"inconsistent-mro",
"Used when a class has an inconsistent method resolution order.",
),
"E0241": (
"Duplicate bases for class %r",
"duplicate-bases",
"Used when a class has duplicate bases.",
),
"E0242": (
"Value %r in slots conflicts with class variable",
"class-variable-slots-conflict",
"Used when a value in __slots__ conflicts with a class variable, property or method.",
),
"E0243": (
"Invalid __class__ object",
"invalid-class-object",
"Used when an invalid object is assigned to a __class__ property. "
"Only a class is permitted.",
),
"R0202": (
"Consider using a decorator instead of calling classmethod",
"no-classmethod-decorator",
"Used when a class method is defined without using the decorator syntax.",
),
"R0203": (
"Consider using a decorator instead of calling staticmethod",
"no-staticmethod-decorator",
"Used when a static method is defined without using the decorator syntax.",
),
"C0205": (
"Class __slots__ should be a non-string iterable",
"single-string-used-for-slots",
"Used when a class __slots__ is a simple string, rather than an iterable.",
),
"R0205": (
"Class %r inherits from object, can be safely removed from bases in python3",
"useless-object-inheritance",
"Used when a class inherit from object, which under python3 is implicit, "
"hence can be safely removed from bases.",
),
"R0206": (
"Cannot have defined parameters for properties",
"property-with-parameters",
"Used when we detect that a property also has parameters, which are useless, "
"given that properties cannot be called with additional arguments.",
),
}
def _scope_default():
return collections.defaultdict(list)
class ScopeAccessMap:
"""Store the accessed variables per scope."""
def __init__(self):
self._scopes = collections.defaultdict(_scope_default)
def set_accessed(self, node):
"""Set the given node as accessed."""
frame = node_frame_class(node)
if frame is None:
# The node does not live in a class.
return
self._scopes[frame][node.attrname].append(node)
def accessed(self, scope):
"""Get the accessed variables for the given scope."""
return self._scopes.get(scope, {})
class ClassChecker(BaseChecker):
"""checks for :
* methods without self as first argument
* overridden methods signature
* access only to existent members via self
* attributes not defined in the __init__ method
* unreachable code
"""
__implements__ = (IAstroidChecker,)
# configuration section name
name = "classes"
# messages
msgs = MSGS
priority = -2
# configuration options
options = (
(
"defining-attr-methods",
{
"default": ("__init__", "__new__", "setUp", "__post_init__"),
"type": "csv",
"metavar": "<method names>",
"help": "List of method names used to declare (i.e. assign) \
instance attributes.",
},
),
(
"valid-classmethod-first-arg",
{
"default": ("cls",),
"type": "csv",
"metavar": "<argument names>",
"help": "List of valid names for the first argument in \
a class method.",
},
),
(
"valid-metaclass-classmethod-first-arg",
{
"default": ("cls",),
"type": "csv",
"metavar": "<argument names>",
"help": "List of valid names for the first argument in \
a metaclass class method.",
},
),
(
"exclude-protected",
{
"default": (
# namedtuple public API.
"_asdict",
"_fields",
"_replace",
"_source",
"_make",
),
"type": "csv",
"metavar": "<protected access exclusions>",
"help": (
"List of member names, which should be excluded "
"from the protected access warning."
),
},
),
(
"check-protected-access-in-special-methods",
{
"default": False,
"type": "yn",
"metavar": "<y or n>",
"help": "Warn about protected attribute access inside special methods",
},
),
)
def __init__(self, linter=None):
BaseChecker.__init__(self, linter)
self._accessed = ScopeAccessMap()
self._first_attrs = []
self._meth_could_be_func = None
@astroid.decorators.cachedproperty
def _dummy_rgx(self):
return get_global_option(self, "dummy-variables-rgx", default=None)
@astroid.decorators.cachedproperty
def _ignore_mixin(self):
return get_global_option(self, "ignore-mixin-members", default=True)
@check_messages(
"abstract-method",
"no-init",
"invalid-slots",
"single-string-used-for-slots",
"invalid-slots-object",
"class-variable-slots-conflict",
"inherit-non-class",
"useless-object-inheritance",
"inconsistent-mro",
"duplicate-bases",
)
def visit_classdef(self, node: nodes.ClassDef) -> None:
"""init visit variable _accessed"""
self._check_bases_classes(node)
# if not an exception or a metaclass
if node.type == "class" and has_known_bases(node):
try:
node.local_attr("__init__")
except astroid.NotFoundError:
self.add_message("no-init", args=node, node=node)
self._check_slots(node)
self._check_proper_bases(node)
self._check_consistent_mro(node)
def _check_consistent_mro(self, node):
"""Detect that a class has a consistent mro or duplicate bases."""
try:
node.mro()
except astroid.InconsistentMroError:
self.add_message("inconsistent-mro", args=node.name, node=node)
except astroid.DuplicateBasesError:
self.add_message("duplicate-bases", args=node.name, node=node)
except NotImplementedError:
# Old style class, there's no mro so don't do anything.
pass
def _check_proper_bases(self, node):
"""
Detect that a class inherits something which is not
a class or a type.
"""
for base in node.bases:
ancestor = safe_infer(base)
if not ancestor:
continue
if isinstance(ancestor, astroid.Instance) and ancestor.is_subtype_of(
"builtins.type"
):
continue
if not isinstance(ancestor, nodes.ClassDef) or _is_invalid_base_class(
ancestor
):
self.add_message("inherit-non-class", args=base.as_string(), node=node)
if ancestor.name == object.__name__:
self.add_message(
"useless-object-inheritance", args=node.name, node=node
)
@check_messages("unused-private-member", "attribute-defined-outside-init")
def leave_classdef(self, node: nodes.ClassDef) -> None:
"""close a class node:
check that instance attributes are defined in __init__ and check
access to existent members
"""
self._check_unused_private_functions(node)
self._check_unused_private_variables(node)
self._check_unused_private_attributes(node)
self._check_attribute_defined_outside_init(node)
def _check_unused_private_functions(self, node: nodes.ClassDef) -> None:
for function_def in node.nodes_of_class(nodes.FunctionDef):
if not is_attr_private(function_def.name):
continue
parent_scope = function_def.parent.scope()
if isinstance(parent_scope, nodes.FunctionDef):
# Handle nested functions
if function_def.name in (
n.name for n in parent_scope.nodes_of_class(nodes.Name)
):
continue
for attribute in node.nodes_of_class(nodes.Attribute):
if (
attribute.attrname != function_def.name
or attribute.scope() == function_def # We ignore recursive calls
):
continue
if isinstance(attribute.expr, nodes.Name) and attribute.expr.name in (
"self",
"cls",
node.name,
):
# self.__attrname
# cls.__attrname
# node_name.__attrname
break
if isinstance(attribute.expr, nodes.Call):
# type(self).__attrname
inferred = safe_infer(attribute.expr)
if (
isinstance(inferred, nodes.ClassDef)
and inferred.name == node.name
):
break
else:
name_stack = []
curr = parent_scope
# Generate proper names for nested functions
while curr != node:
name_stack.append(curr.name)
curr = curr.parent.scope()
outer_level_names = f"{'.'.join(reversed(name_stack))}"
function_repr = f"{outer_level_names}.{function_def.name}({function_def.args.as_string()})"
self.add_message(
"unused-private-member",
node=function_def,
args=(node.name, function_repr.lstrip(".")),
)
def _check_unused_private_variables(self, node: nodes.ClassDef) -> None:
for assign_name in node.nodes_of_class(nodes.AssignName):
if isinstance(assign_name.parent, nodes.Arguments):
continue # Ignore function arguments
if not is_attr_private(assign_name.name):
continue
for child in node.nodes_of_class((nodes.Name, nodes.Attribute)):
if isinstance(child, nodes.Name) and child.name == assign_name.name:
break
if (
isinstance(child, nodes.Attribute)
and child.attrname == assign_name.name
and child.expr.name in ("self", "cls", node.name)
):
break
else:
args = (node.name, assign_name.name)
self.add_message("unused-private-member", node=assign_name, args=args)
def _check_unused_private_attributes(self, node: nodes.ClassDef) -> None:
for assign_attr in node.nodes_of_class(nodes.AssignAttr):
if not is_attr_private(assign_attr.attrname) or not isinstance(
assign_attr.expr, nodes.Name
):
continue
# Logic for checking false positive when using __new__,
# Get the returned object names of the __new__ magic function
# Then check if the attribute was consumed in other instance methods
acceptable_obj_names: List[str] = ["self"]
scope = assign_attr.scope()
if isinstance(scope, nodes.FunctionDef) and scope.name == "__new__":
acceptable_obj_names.extend(
[
return_node.value.name
for return_node in scope.nodes_of_class(nodes.Return)
if isinstance(return_node.value, nodes.Name)
]
)
for attribute in node.nodes_of_class(nodes.Attribute):
if attribute.attrname != assign_attr.attrname:
continue