-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
refactoring_checker.py
2466 lines (2194 loc) · 100 KB
/
refactoring_checker.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/pylint-dev/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
from __future__ import annotations
import collections
import copy
import itertools
import tokenize
from collections.abc import Iterator
from functools import cached_property, reduce
from re import Pattern
from typing import TYPE_CHECKING, Any, NamedTuple, Union, cast
import astroid
from astroid import bases, nodes
from astroid.util import UninferableBase
from pylint import checkers
from pylint.checkers import utils
from pylint.checkers.base.basic_error_checker import _loop_exits_early
from pylint.checkers.utils import node_frame_class
from pylint.interfaces import HIGH, INFERENCE, Confidence
if TYPE_CHECKING:
from pylint.lint import PyLinter
NodesWithNestedBlocks = Union[nodes.Try, nodes.While, nodes.For, nodes.If]
KNOWN_INFINITE_ITERATORS = {"itertools.count", "itertools.cycle"}
BUILTIN_EXIT_FUNCS = frozenset(("quit", "exit"))
CALLS_THAT_COULD_BE_REPLACED_BY_WITH = frozenset(
(
"threading.lock.acquire",
"threading._RLock.acquire",
"threading.Semaphore.acquire",
"multiprocessing.managers.BaseManager.start",
"multiprocessing.managers.SyncManager.start",
)
)
CALLS_RETURNING_CONTEXT_MANAGERS = frozenset(
(
"_io.open", # regular 'open()' call
"pathlib.Path.open",
"pathlib._local.Path.open", # Python 3.13
"codecs.open",
"urllib.request.urlopen",
"tempfile.NamedTemporaryFile",
"tempfile.SpooledTemporaryFile",
"tempfile.TemporaryDirectory",
"tempfile.TemporaryFile",
"zipfile.ZipFile",
"zipfile.PyZipFile",
"zipfile.ZipFile.open",
"zipfile.PyZipFile.open",
"tarfile.TarFile",
"tarfile.TarFile.open",
"multiprocessing.context.BaseContext.Pool",
"subprocess.Popen",
)
)
def _if_statement_is_always_returning(
if_node: nodes.If, returning_node_class: nodes.NodeNG
) -> bool:
return any(isinstance(node, returning_node_class) for node in if_node.body)
def _except_statement_is_always_returning(
node: nodes.Try, returning_node_class: nodes.NodeNG
) -> bool:
"""Detect if all except statements return."""
return all(
any(isinstance(child, returning_node_class) for child in handler.body)
for handler in node.handlers
)
def _is_trailing_comma(tokens: list[tokenize.TokenInfo], index: int) -> bool:
"""Check if the given token is a trailing comma.
:param tokens: Sequence of modules tokens
:type tokens: list[tokenize.TokenInfo]
:param int index: Index of token under check in tokens
:returns: True if the token is a comma which trails an expression
:rtype: bool
"""
token = tokens[index]
if token.exact_type != tokenize.COMMA:
return False
# Must have remaining tokens on the same line such as NEWLINE
left_tokens = itertools.islice(tokens, index + 1, None)
more_tokens_on_line = False
for remaining_token in left_tokens:
if remaining_token.start[0] == token.start[0]:
more_tokens_on_line = True
# If one of the remaining same line tokens is not NEWLINE or COMMENT
# the comma is not trailing.
if remaining_token.type not in (tokenize.NEWLINE, tokenize.COMMENT):
return False
if not more_tokens_on_line:
return False
def get_curline_index_start() -> int:
"""Get the index denoting the start of the current line."""
for subindex, token in enumerate(reversed(tokens[:index])):
# See Lib/tokenize.py and Lib/token.py in cpython for more info
if token.type == tokenize.NEWLINE:
return index - subindex
return 0
curline_start = get_curline_index_start()
expected_tokens = {"return", "yield"}
return any(
"=" in prevtoken.string or prevtoken.string in expected_tokens
for prevtoken in tokens[curline_start:index]
)
def _is_inside_context_manager(node: nodes.Call) -> bool:
frame = node.frame()
if not isinstance(
frame, (nodes.FunctionDef, astroid.BoundMethod, astroid.UnboundMethod)
):
return False
return frame.name == "__enter__" or utils.decorated_with(
frame, "contextlib.contextmanager"
)
def _is_a_return_statement(node: nodes.Call) -> bool:
frame = node.frame()
for parent in node.node_ancestors():
if parent is frame:
break
if isinstance(parent, nodes.Return):
return True
return False
def _is_part_of_with_items(node: nodes.Call) -> bool:
"""Checks if one of the node's parents is a ``nodes.With`` node and that the node
itself is located somewhere under its ``items``.
"""
frame = node.frame()
current = node
while current != frame:
if isinstance(current, nodes.With):
items_start = current.items[0][0].lineno
items_end = current.items[-1][0].tolineno
return items_start <= node.lineno <= items_end # type: ignore[no-any-return]
current = current.parent
return False
def _will_be_released_automatically(node: nodes.Call) -> bool:
"""Checks if a call that could be used in a ``with`` statement is used in an
alternative construct which would ensure that its __exit__ method is called.
"""
callables_taking_care_of_exit = frozenset(
(
"contextlib._BaseExitStack.enter_context",
"contextlib.ExitStack.enter_context", # necessary for Python 3.6 compatibility
)
)
if not isinstance(node.parent, nodes.Call):
return False
func = utils.safe_infer(node.parent.func)
if not func:
return False
return func.qname() in callables_taking_care_of_exit
def _is_part_of_assignment_target(node: nodes.NodeNG) -> bool:
"""Check whether use of a variable is happening as part of the left-hand
side of an assignment.
This requires recursive checking, because destructuring assignment can have
arbitrarily nested tuples and lists to unpack.
"""
if isinstance(node.parent, nodes.Assign):
return node in node.parent.targets
if isinstance(node.parent, nodes.AugAssign):
return node == node.parent.target # type: ignore[no-any-return]
if isinstance(node.parent, (nodes.Tuple, nodes.List)):
return _is_part_of_assignment_target(node.parent)
return False
class ConsiderUsingWithStack(NamedTuple):
"""Stack for objects that may potentially trigger a R1732 message
if they are not used in a ``with`` block later on.
"""
module_scope: dict[str, nodes.NodeNG] = {}
class_scope: dict[str, nodes.NodeNG] = {}
function_scope: dict[str, nodes.NodeNG] = {}
def __iter__(self) -> Iterator[dict[str, nodes.NodeNG]]:
yield from (self.function_scope, self.class_scope, self.module_scope)
def get_stack_for_frame(
self, frame: nodes.FunctionDef | nodes.ClassDef | nodes.Module
) -> dict[str, nodes.NodeNG]:
"""Get the stack corresponding to the scope of the given frame."""
if isinstance(frame, nodes.FunctionDef):
return self.function_scope
if isinstance(frame, nodes.ClassDef):
return self.class_scope
return self.module_scope
def clear_all(self) -> None:
"""Convenience method to clear all stacks."""
for stack in self:
stack.clear()
class RefactoringChecker(checkers.BaseTokenChecker):
"""Looks for code which can be refactored.
This checker also mixes the astroid and the token approaches
in order to create knowledge about whether an "else if" node
is a true "else if" node, or an "elif" node.
"""
name = "refactoring"
msgs = {
"R1701": (
"Consider merging these isinstance calls to isinstance(%s, (%s))",
"consider-merging-isinstance",
"Used when multiple consecutive isinstance calls can be merged into one.",
),
"R1706": (
"Consider using ternary (%s)",
"consider-using-ternary",
"Used when one of known pre-python 2.5 ternary syntax is used.",
),
"R1709": (
"Boolean expression may be simplified to %s",
"simplify-boolean-expression",
"Emitted when redundant pre-python 2.5 ternary syntax is used.",
),
"R1726": (
'Boolean condition "%s" may be simplified to "%s"',
"simplifiable-condition",
"Emitted when a boolean condition is able to be simplified.",
),
"R1727": (
"Boolean condition '%s' will always evaluate to '%s'",
"condition-evals-to-constant",
"Emitted when a boolean condition can be simplified to a constant value.",
),
"R1702": (
"Too many nested blocks (%s/%s)",
"too-many-nested-blocks",
"Used when a function or a method has too many nested "
"blocks. This makes the code less understandable and "
"maintainable.",
{"old_names": [("R0101", "old-too-many-nested-blocks")]},
),
"R1703": (
"The if statement can be replaced with %s",
"simplifiable-if-statement",
"Used when an if statement can be replaced with 'bool(test)'.",
{"old_names": [("R0102", "old-simplifiable-if-statement")]},
),
"R1704": (
"Redefining argument with the local name %r",
"redefined-argument-from-local",
"Used when a local name is redefining an argument, which might "
"suggest a potential error. This is taken in account only for "
"a handful of name binding operations, such as for iteration, "
"with statement assignment and exception handler assignment.",
),
"R1705": (
'Unnecessary "%s" after "return", %s',
"no-else-return",
"Used in order to highlight an unnecessary block of "
"code following an if, or a try/except containing a return statement. "
"As such, it will warn when it encounters an else "
"following a chain of ifs, all of them containing a "
"return statement.",
),
"R1707": (
"Disallow trailing comma tuple",
"trailing-comma-tuple",
"In Python, a tuple is actually created by the comma symbol, "
"not by the parentheses. Unfortunately, one can actually create a "
"tuple by misplacing a trailing comma, which can lead to potential "
"weird bugs in your code. You should always use parentheses "
"explicitly for creating a tuple.",
),
"R1708": (
"Do not raise StopIteration in generator, use return statement instead",
"stop-iteration-return",
"According to PEP479, the raise of StopIteration to end the loop of "
"a generator may lead to hard to find bugs. This PEP specify that "
"raise StopIteration has to be replaced by a simple return statement",
),
"R1710": (
"Either all return statements in a function should return an expression, "
"or none of them should.",
"inconsistent-return-statements",
"According to PEP8, if any return statement returns an expression, "
"any return statements where no value is returned should explicitly "
"state this as return None, and an explicit return statement "
"should be present at the end of the function (if reachable)",
),
"R1711": (
"Useless return at end of function or method",
"useless-return",
'Emitted when a single "return" or "return None" statement is found '
"at the end of function or method definition. This statement can safely be "
"removed because Python will implicitly return None",
),
"R1712": (
"Consider using tuple unpacking for swapping variables",
"consider-swap-variables",
"You do not have to use a temporary variable in order to "
'swap variables. Using "tuple unpacking" to directly swap '
"variables makes the intention more clear.",
),
"R1713": (
"Consider using str.join(sequence) for concatenating "
"strings from an iterable",
"consider-using-join",
"Using str.join(sequence) is faster, uses less memory "
"and increases readability compared to for-loop iteration.",
),
"R1714": (
"Consider merging these comparisons with 'in' by using '%s %sin (%s)'."
" Use a set instead if elements are hashable.",
"consider-using-in",
"To check if a variable is equal to one of many values, "
'combine the values into a set or tuple and check if the variable is contained "in" it '
"instead of checking for equality against each of the values. "
"This is faster and less verbose.",
),
"R1715": (
"Consider using dict.get for getting values from a dict "
"if a key is present or a default if not",
"consider-using-get",
"Using the builtin dict.get for getting a value from a dictionary "
"if a key is present or a default if not, is simpler and considered "
"more idiomatic, although sometimes a bit slower",
),
"R1716": (
"Simplify chained comparison between the operands",
"chained-comparison",
"This message is emitted when pylint encounters boolean operation like "
'"a < b and b < c", suggesting instead to refactor it to "a < b < c"',
),
"R1717": (
"Consider using a dictionary comprehension",
"consider-using-dict-comprehension",
"Emitted when we detect the creation of a dictionary "
"using the dict() callable and a transient list. "
"Although there is nothing syntactically wrong with this code, "
"it is hard to read and can be simplified to a dict comprehension. "
"Also it is faster since you don't need to create another "
"transient list",
),
"R1718": (
"Consider using a set comprehension",
"consider-using-set-comprehension",
"Although there is nothing syntactically wrong with this code, "
"it is hard to read and can be simplified to a set comprehension. "
"Also it is faster since you don't need to create another "
"transient list",
),
"R1719": (
"The if expression can be replaced with %s",
"simplifiable-if-expression",
"Used when an if expression can be replaced with 'bool(test)' "
"or simply 'test' if the boolean cast is implicit.",
),
"R1720": (
'Unnecessary "%s" after "raise", %s',
"no-else-raise",
"Used in order to highlight an unnecessary block of "
"code following an if, or a try/except containing a raise statement. "
"As such, it will warn when it encounters an else "
"following a chain of ifs, all of them containing a "
"raise statement.",
),
"R1721": (
"Unnecessary use of a comprehension, use %s instead.",
"unnecessary-comprehension",
"Instead of using an identity comprehension, "
"consider using the list, dict or set constructor. "
"It is faster and simpler.",
),
"R1722": (
"Consider using 'sys.exit' instead",
"consider-using-sys-exit",
"Contrary to 'exit()' or 'quit()', 'sys.exit' does not rely on the "
"site module being available (as the 'sys' module is always available).",
),
"R1723": (
'Unnecessary "%s" after "break", %s',
"no-else-break",
"Used in order to highlight an unnecessary block of "
"code following an if containing a break statement. "
"As such, it will warn when it encounters an else "
"following a chain of ifs, all of them containing a "
"break statement.",
),
"R1724": (
'Unnecessary "%s" after "continue", %s',
"no-else-continue",
"Used in order to highlight an unnecessary block of "
"code following an if containing a continue statement. "
"As such, it will warn when it encounters an else "
"following a chain of ifs, all of them containing a "
"continue statement.",
),
"R1725": (
"Consider using Python 3 style super() without arguments",
"super-with-arguments",
"Emitted when calling the super() builtin with the current class "
"and instance. On Python 3 these arguments are the default and they can be omitted.",
),
"R1728": (
"Consider using a generator instead '%s(%s)'",
"consider-using-generator",
"If your container can be large using "
"a generator will bring better performance.",
),
"R1729": (
"Use a generator instead '%s(%s)'",
"use-a-generator",
"Comprehension inside of 'any', 'all', 'max', 'min' or 'sum' is unnecessary. "
"A generator would be sufficient and faster.",
),
"R1730": (
"Consider using '%s' instead of unnecessary if block",
"consider-using-min-builtin",
"Using the min builtin instead of a conditional improves readability and conciseness.",
),
"R1731": (
"Consider using '%s' instead of unnecessary if block",
"consider-using-max-builtin",
"Using the max builtin instead of a conditional improves readability and conciseness.",
),
"R1732": (
"Consider using 'with' for resource-allocating operations",
"consider-using-with",
"Emitted if a resource-allocating assignment or call may be replaced by a 'with' block. "
"By using 'with' the release of the allocated resources is ensured even in the case "
"of an exception.",
),
"R1733": (
"Unnecessary dictionary index lookup, use '%s' instead",
"unnecessary-dict-index-lookup",
"Emitted when iterating over the dictionary items (key-item pairs) and accessing the "
"value by index lookup. "
"The value can be accessed directly instead.",
),
"R1734": (
"Consider using [] instead of list()",
"use-list-literal",
"Emitted when using list() to create an empty list instead of the literal []. "
"The literal is faster as it avoids an additional function call.",
),
"R1735": (
"Consider using '%s' instead of a call to 'dict'.",
"use-dict-literal",
"Emitted when using dict() to create a dictionary instead of a literal '{ ... }'. "
"The literal is faster as it avoids an additional function call.",
),
"R1736": (
"Unnecessary list index lookup, use '%s' instead",
"unnecessary-list-index-lookup",
"Emitted when iterating over an enumeration and accessing the "
"value by index lookup. "
"The value can be accessed directly instead.",
),
"R1737": (
"Use 'yield from' directly instead of yielding each element one by one",
"use-yield-from",
"Yielding directly from the iterator is faster and arguably cleaner code than yielding each element "
"one by one in the loop.",
),
}
options = (
(
"max-nested-blocks",
{
"default": 5,
"type": "int",
"metavar": "<int>",
"help": "Maximum number of nested blocks for function / method body",
},
),
(
"never-returning-functions",
{
"default": ("sys.exit", "argparse.parse_error"),
"type": "csv",
"metavar": "<members names>",
"help": "Complete name of functions that never returns. When checking "
"for inconsistent-return-statements if a never returning function is "
"called then it will be considered as an explicit return statement "
"and no message will be printed.",
},
),
(
"suggest-join-with-non-empty-separator",
{
"default": True,
"type": "yn",
"metavar": "<y or n>",
"help": (
"Let 'consider-using-join' be raised when the separator to "
"join on would be non-empty (resulting in expected fixes "
'of the type: ``"- " + "\n- ".join(items)``)'
),
},
),
)
def __init__(self, linter: PyLinter) -> None:
super().__init__(linter)
self._return_nodes: dict[str, list[nodes.Return]] = {}
self._consider_using_with_stack = ConsiderUsingWithStack()
self._init()
self._never_returning_functions: set[str] = set()
self._suggest_join_with_non_empty_separator: bool = False
def _init(self) -> None:
self._nested_blocks: list[NodesWithNestedBlocks] = []
self._elifs: list[tuple[int, int]] = []
self._reported_swap_nodes: set[nodes.NodeNG] = set()
self._can_simplify_bool_op: bool = False
self._consider_using_with_stack.clear_all()
def open(self) -> None:
# do this in open since config not fully initialized in __init__
self._never_returning_functions = set(
self.linter.config.never_returning_functions
)
self._suggest_join_with_non_empty_separator = (
self.linter.config.suggest_join_with_non_empty_separator
)
@cached_property
def _dummy_rgx(self) -> Pattern[str]:
return self.linter.config.dummy_variables_rgx # type: ignore[no-any-return]
@staticmethod
def _is_bool_const(node: nodes.Return | nodes.Assign) -> bool:
return isinstance(node.value, nodes.Const) and isinstance(
node.value.value, bool
)
def _is_actual_elif(self, node: nodes.If | nodes.Try) -> bool:
"""Check if the given node is an actual elif.
This is a problem we're having with the builtin ast module,
which splits `elif` branches into a separate if statement.
Unfortunately we need to know the exact type in certain
cases.
"""
if isinstance(node.parent, nodes.If):
orelse = node.parent.orelse
# current if node must directly follow an "else"
if orelse and orelse == [node]:
if (node.lineno, node.col_offset) in self._elifs:
return True
return False
def _check_simplifiable_if(self, node: nodes.If) -> None:
"""Check if the given if node can be simplified.
The if statement can be reduced to a boolean expression
in some cases. For instance, if there are two branches
and both of them return a boolean value that depends on
the result of the statement's test, then this can be reduced
to `bool(test)` without losing any functionality.
"""
if self._is_actual_elif(node):
# Not interested in if statements with multiple branches.
return
if len(node.orelse) != 1 or len(node.body) != 1:
return
# Check if both branches can be reduced.
first_branch = node.body[0]
else_branch = node.orelse[0]
if isinstance(first_branch, nodes.Return):
if not isinstance(else_branch, nodes.Return):
return
first_branch_is_bool = self._is_bool_const(first_branch)
else_branch_is_bool = self._is_bool_const(else_branch)
reduced_to = "'return bool(test)'"
elif isinstance(first_branch, nodes.Assign):
if not isinstance(else_branch, nodes.Assign):
return
# Check if we assign to the same value
first_branch_targets = [
target.name
for target in first_branch.targets
if isinstance(target, nodes.AssignName)
]
else_branch_targets = [
target.name
for target in else_branch.targets
if isinstance(target, nodes.AssignName)
]
if not first_branch_targets or not else_branch_targets:
return
if sorted(first_branch_targets) != sorted(else_branch_targets):
return
first_branch_is_bool = self._is_bool_const(first_branch)
else_branch_is_bool = self._is_bool_const(else_branch)
reduced_to = "'var = bool(test)'"
else:
return
if not first_branch_is_bool or not else_branch_is_bool:
return
if not first_branch.value.value:
# This is a case that can't be easily simplified and
# if it can be simplified, it will usually result in a
# code that's harder to understand and comprehend.
# Let's take for instance `arg and arg <= 3`. This could theoretically be
# reduced to `not arg or arg > 3`, but the net result is that now the
# condition is harder to understand, because it requires understanding of
# an extra clause:
# * first, there is the negation of truthness with `not arg`
# * the second clause is `arg > 3`, which occurs when arg has a
# a truth value, but it implies that `arg > 3` is equivalent
# with `arg and arg > 3`, which means that the user must
# think about this assumption when evaluating `arg > 3`.
# The original form is easier to grasp.
return
self.add_message("simplifiable-if-statement", node=node, args=(reduced_to,))
def process_tokens(self, tokens: list[tokenize.TokenInfo]) -> None:
# Optimization flag because '_is_trailing_comma' is costly
trailing_comma_tuple_enabled_for_file = self.linter.is_message_enabled(
"trailing-comma-tuple"
)
trailing_comma_tuple_enabled_once: bool = trailing_comma_tuple_enabled_for_file
# Process tokens and look for 'if' or 'elif'
for index, token in enumerate(tokens):
token_string = token[1]
if (
not trailing_comma_tuple_enabled_once
and token_string.startswith("#")
# We have at least 1 '#' (one char) at the start of the token
and "pylint:" in token_string[1:]
# We have at least '#' 'pylint' ( + ':') (8 chars) at the start of the token
and "enable" in token_string[8:]
# We have at least '#', 'pylint', ( + ':'), 'enable' (+ '=') (15 chars) at
# the start of the token
and any(
c in token_string[15:] for c in ("trailing-comma-tuple", "R1707")
)
):
# Way to not have to check if "trailing-comma-tuple" is enabled or
# disabled on each line: Any enable for it during tokenization and
# we'll start using the costly '_is_trailing_comma' to check if we
# need to raise the message. We still won't raise if it's disabled
# again due to the usual generic message control handling later.
trailing_comma_tuple_enabled_once = True
if token_string == "elif":
# AST exists by the time process_tokens is called, so
# it's safe to assume tokens[index+1] exists.
# tokens[index+1][2] is the elif's position as
# reported by CPython and PyPy,
# token[2] is the actual position and also is
# reported by IronPython.
self._elifs.extend([token[2], tokens[index + 1][2]])
elif (
trailing_comma_tuple_enabled_for_file
or trailing_comma_tuple_enabled_once
) and _is_trailing_comma(tokens, index):
# If "trailing-comma-tuple" is enabled globally we always check _is_trailing_comma
# it might be for nothing if there's a local disable, or if the message control is
# not enabling 'trailing-comma-tuple', but the alternative is having to check if
# it's enabled for a line each line (just to avoid calling '_is_trailing_comma').
self.add_message(
"trailing-comma-tuple", line=token.start[0], confidence=HIGH
)
@utils.only_required_for_messages("consider-using-with")
def leave_module(self, _: nodes.Module) -> None:
# check for context managers that have been created but not used
self._emit_consider_using_with_if_needed(
self._consider_using_with_stack.module_scope
)
self._init()
@utils.only_required_for_messages("too-many-nested-blocks", "no-else-return")
def visit_try(self, node: nodes.Try) -> None:
self._check_nested_blocks(node)
self._check_superfluous_else_return(node)
self._check_superfluous_else_raise(node)
visit_while = visit_try
def _check_redefined_argument_from_local(self, name_node: nodes.AssignName) -> None:
if self._dummy_rgx and self._dummy_rgx.match(name_node.name):
return
if not name_node.lineno:
# Unknown position, maybe it is a manually built AST?
return
scope = name_node.scope()
if not isinstance(scope, nodes.FunctionDef):
return
for defined_argument in scope.args.nodes_of_class(
nodes.AssignName, skip_klass=(nodes.Lambda,)
):
if defined_argument.name == name_node.name:
self.add_message(
"redefined-argument-from-local",
node=name_node,
args=(name_node.name,),
)
@utils.only_required_for_messages(
"redefined-argument-from-local",
"too-many-nested-blocks",
"unnecessary-dict-index-lookup",
"unnecessary-list-index-lookup",
)
def visit_for(self, node: nodes.For) -> None:
self._check_nested_blocks(node)
self._check_unnecessary_dict_index_lookup(node)
self._check_unnecessary_list_index_lookup(node)
for name in node.target.nodes_of_class(nodes.AssignName):
self._check_redefined_argument_from_local(name)
@utils.only_required_for_messages("redefined-argument-from-local")
def visit_excepthandler(self, node: nodes.ExceptHandler) -> None:
if node.name and isinstance(node.name, nodes.AssignName):
self._check_redefined_argument_from_local(node.name)
@utils.only_required_for_messages(
"redefined-argument-from-local", "consider-using-with"
)
def visit_with(self, node: nodes.With) -> None:
for var, names in node.items:
if isinstance(var, nodes.Name):
for stack in self._consider_using_with_stack:
# We don't need to restrict the stacks we search to the current scope and
# outer scopes, as e.g. the function_scope stack will be empty when we
# check a ``with`` on the class level.
if var.name in stack:
del stack[var.name]
break
if not names:
continue
for name in names.nodes_of_class(nodes.AssignName):
self._check_redefined_argument_from_local(name)
def _check_superfluous_else(
self,
node: nodes.If | nodes.Try,
msg_id: str,
returning_node_class: nodes.NodeNG,
) -> None:
if isinstance(node, nodes.Try) and node.finalbody:
# Not interested in try/except/else/finally statements.
return
if not node.orelse:
# Not interested in if/try statements without else.
return
if self._is_actual_elif(node):
# Not interested in elif nodes; only if
return
if (
isinstance(node, nodes.If)
and _if_statement_is_always_returning(node, returning_node_class)
) or (
isinstance(node, nodes.Try)
and not node.finalbody
and _except_statement_is_always_returning(node, returning_node_class)
):
orelse = node.orelse[0]
if (orelse.lineno, orelse.col_offset) in self._elifs:
args = ("elif", 'remove the leading "el" from "elif"')
else:
args = ("else", 'remove the "else" and de-indent the code inside it')
self.add_message(msg_id, node=node, args=args, confidence=HIGH)
def _check_superfluous_else_return(self, node: nodes.If) -> None:
return self._check_superfluous_else(
node, msg_id="no-else-return", returning_node_class=nodes.Return
)
def _check_superfluous_else_raise(self, node: nodes.If) -> None:
return self._check_superfluous_else(
node, msg_id="no-else-raise", returning_node_class=nodes.Raise
)
def _check_superfluous_else_break(self, node: nodes.If) -> None:
return self._check_superfluous_else(
node, msg_id="no-else-break", returning_node_class=nodes.Break
)
def _check_superfluous_else_continue(self, node: nodes.If) -> None:
return self._check_superfluous_else(
node, msg_id="no-else-continue", returning_node_class=nodes.Continue
)
@staticmethod
def _type_and_name_are_equal(node_a: Any, node_b: Any) -> bool:
if isinstance(node_a, nodes.Name) and isinstance(node_b, nodes.Name):
return node_a.name == node_b.name # type: ignore[no-any-return]
if isinstance(node_a, nodes.AssignName) and isinstance(
node_b, nodes.AssignName
):
return node_a.name == node_b.name # type: ignore[no-any-return]
if isinstance(node_a, nodes.Const) and isinstance(node_b, nodes.Const):
return node_a.value == node_b.value # type: ignore[no-any-return]
return False
def _is_dict_get_block(self, node: nodes.If) -> bool:
# "if <compare node>"
if not isinstance(node.test, nodes.Compare):
return False
# Does not have a single statement in the guard's body
if len(node.body) != 1:
return False
# Look for a single variable assignment on the LHS and a subscript on RHS
stmt = node.body[0]
if not (
isinstance(stmt, nodes.Assign)
and len(node.body[0].targets) == 1
and isinstance(node.body[0].targets[0], nodes.AssignName)
and isinstance(stmt.value, nodes.Subscript)
):
return False
# The subscript's slice needs to be the same as the test variable.
slice_value = stmt.value.slice
if not (
self._type_and_name_are_equal(stmt.value.value, node.test.ops[0][1])
and self._type_and_name_are_equal(slice_value, node.test.left)
):
return False
# The object needs to be a dictionary instance
return isinstance(utils.safe_infer(node.test.ops[0][1]), nodes.Dict)
def _check_consider_get(self, node: nodes.If) -> None:
if_block_ok = self._is_dict_get_block(node)
if if_block_ok and not node.orelse:
self.add_message("consider-using-get", node=node)
elif (
if_block_ok
and len(node.orelse) == 1
and isinstance(node.orelse[0], nodes.Assign)
and self._type_and_name_are_equal(
node.orelse[0].targets[0], node.body[0].targets[0]
)
and len(node.orelse[0].targets) == 1
):
self.add_message("consider-using-get", node=node)
@utils.only_required_for_messages(
"too-many-nested-blocks",
"simplifiable-if-statement",
"no-else-return",
"no-else-raise",
"no-else-break",
"no-else-continue",
"consider-using-get",
"consider-using-min-builtin",
"consider-using-max-builtin",
)
def visit_if(self, node: nodes.If) -> None:
self._check_simplifiable_if(node)
self._check_nested_blocks(node)
self._check_superfluous_else_return(node)
self._check_superfluous_else_raise(node)
self._check_superfluous_else_break(node)
self._check_superfluous_else_continue(node)
self._check_consider_get(node)
self._check_consider_using_min_max_builtin(node)
def _check_consider_using_min_max_builtin(self, node: nodes.If) -> None:
"""Check if the given if node can be refactored as a min/max python builtin."""
# This function is written expecting a test condition of form:
# if a < b: # [consider-using-max-builtin]
# a = b
# if a > b: # [consider-using-min-builtin]
# a = b
if self._is_actual_elif(node) or node.orelse:
# Not interested in if statements with multiple branches.
return
if len(node.body) != 1:
return
def get_node_name(node: nodes.NodeNG) -> str:
"""Obtain simplest representation of a node as a string."""
if isinstance(node, nodes.Name):
return node.name # type: ignore[no-any-return]
if isinstance(node, nodes.Const):
return str(node.value)
# this is a catch-all for nodes that are not of type Name or Const
# extremely helpful for Call or BinOp
return node.as_string() # type: ignore[no-any-return]
body = node.body[0]
# Check if condition can be reduced.
if not hasattr(body, "targets") or len(body.targets) != 1:
return
target = body.targets[0]
if not (
isinstance(node.test, nodes.Compare)
and not isinstance(target, nodes.Subscript)
and not isinstance(node.test.left, nodes.Subscript)
and isinstance(body, nodes.Assign)
):
return
# Assign body line has one requirement and that is the assign target
# is of type name or attribute. Attribute referring to NamedTuple.x perse.
# So we have to check that target is of these types
if not (hasattr(target, "name") or hasattr(target, "attrname")):
return
target_assignation = get_node_name(target)
if len(node.test.ops) > 1:
return
operator, right_statement = node.test.ops[0]
body_value = get_node_name(body.value)
left_operand = get_node_name(node.test.left)
right_statement_value = get_node_name(right_statement)
if left_operand == target_assignation:
# statement is in expected form
pass
elif right_statement_value == target_assignation:
# statement is in reverse form
operator = utils.get_inverse_comparator(operator)
else:
return
if body_value not in (right_statement_value, left_operand):
return
if operator in {"<", "<="}:
reduced_to = (
f"{target_assignation} = max({target_assignation}, {body_value})"
)
self.add_message(
"consider-using-max-builtin", node=node, args=(reduced_to,)
)
elif operator in {">", ">="}:
reduced_to = (
f"{target_assignation} = min({target_assignation}, {body_value})"
)
self.add_message(
"consider-using-min-builtin", node=node, args=(reduced_to,)
)
@utils.only_required_for_messages("simplifiable-if-expression")
def visit_ifexp(self, node: nodes.IfExp) -> None:
self._check_simplifiable_ifexp(node)
def _check_simplifiable_ifexp(self, node: nodes.IfExp) -> None:
if not isinstance(node.body, nodes.Const) or not isinstance(
node.orelse, nodes.Const
):
return
if not isinstance(node.body.value, bool) or not isinstance(
node.orelse.value, bool
):
return