-
Notifications
You must be signed in to change notification settings - Fork 19
/
flake8_simplify.py
2118 lines (1892 loc) · 64.3 KB
/
flake8_simplify.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
# Core Library
import ast
import itertools
import json
import logging
import sys
from collections import defaultdict
from typing import (
Any,
DefaultDict,
Dict,
Generator,
List,
Optional,
Tuple,
Type,
Union,
)
# Third party
import astor
logger = logging.getLogger(__name__)
class UnaryOp(ast.UnaryOp):
def __init__(self, orig: ast.UnaryOp) -> None:
self.op = orig.op
self.operand = orig.operand
# For all ast.*:
self.lineno = orig.lineno
self.col_offset = orig.col_offset
self.parent: ast.Expr = orig.parent # type: ignore
class Call(ast.Call):
def __init__(self, orig: ast.Call) -> None:
self.func = orig.func
self.args = orig.args
self.keywords = orig.keywords
# For all ast.*:
self.lineno = orig.lineno
self.col_offset = orig.col_offset
self.parent: ast.Expr = orig.parent # type: ignore
if sys.version_info < (3, 8): # pragma: no cover (<PY38)
# Third party
import importlib_metadata
else: # pragma: no cover (PY38+)
# Core Library
import importlib.metadata as importlib_metadata
# Python-Specific
SIM101 = (
"SIM101 Multiple isinstance-calls which can be merged into a single "
"call for variable '{var}'"
)
SIM102 = "SIM102 Use a single if-statement instead of nested if-statements"
SIM103 = "SIM103 Return the condition {cond} directly"
SIM104 = "SIM104 Use 'yield from {iterable}'"
SIM105 = "SIM105 Use 'contextlib.suppress({exception})'"
SIM106 = "SIM106 Handle error-cases first"
SIM107 = "SIM107 Don't use return in try/except and finally"
SIM108 = (
"SIM108 Use ternary operator "
"'{assign} = {body} if {cond} else {orelse}' "
"instead of if-else-block"
)
SIM109 = "SIM109 Use '{value} in {values}' instead of '{or_op}'"
SIM110 = "SIM110 Use 'return any({check} for {target} in {iterable})'"
SIM111 = "SIM111 Use 'return all({check} for {target} in {iterable})'"
SIM112 = "SIM112 Use '{expected}' instead of '{original}'"
SIM113 = "SIM113 Use enumerate instead of '{variable}'"
SIM114 = "SIM114 Use logical or (({cond1}) or ({cond2})) and a single body"
SIM115 = "SIM115 Use context handler for opening files"
SIM116 = (
"SIM116 Use a dictionary lookup instead of 3+ if/elif-statements: "
"return {ret}"
)
SIM117 = "SIM117 Use '{merged_with}' instead of multiple with statements"
SIM118 = "SIM118 Use '{el} in {dict}' instead of '{el} in {dict}.keys()'"
SIM119 = "SIM119 Use a dataclass for 'class {classname}'"
SIM120 = (
"SIM120 Use 'class {classname}:' instead of 'class {classname}(object):'"
)
# Comparations
SIM201 = "SIM201 Use '{left} != {right}' instead of 'not {left} == {right}'"
SIM202 = "SIM202 Use '{left} == {right}' instead of 'not {left} != {right}'"
SIM203 = "SIM203 Use '{a} not in {b}' instead of 'not {a} in {b}'"
SIM204 = "SIM204 Use '{a} >= {b}' instead of 'not ({a} < {b})'"
SIM205 = "SIM205 Use '{a} > {b}' instead of 'not ({a} <= {b})'"
SIM206 = "SIM206 Use '{a} <= {b}' instead of 'not ({a} > {b})'"
SIM207 = "SIM207 Use '{a} < {b}' instead of 'not ({a} >= {b})'"
SIM208 = "SIM208 Use '{a}' instead of 'not (not {a})'"
SIM210 = "SIM210 Use 'bool({cond})' instead of 'True if {cond} else False'"
SIM211 = "SIM211 Use 'not {cond}' instead of 'False if {cond} else True'"
SIM212 = (
"SIM212 Use '{a} if {a} else {b}' instead of '{b} if not {a} else {a}'"
)
SIM220 = "SIM220 Use 'False' instead of '{a} and not {a}'"
SIM221 = "SIM221 Use 'True' instead of '{a} or not {a}'"
SIM222 = "SIM222 Use 'True' instead of '... or True'"
SIM223 = "SIM223 Use 'False' instead of '... and False'"
SIM300 = (
"SIM300 Use '{right} == {left}' instead of "
"'{left} == {right}' (Yoda-conditions)"
)
SIM401 = (
"SIM401 Use '{value} = {dict}.get({key}, {default_value})' "
"instead of an if-block"
)
SIM901 = "SIM901 Use '{expected}' instead of '{actual}'"
SIM904 = "SIM904 Initialize dictionary '{dict_name}' directly"
SIM905 = "SIM905 Use '{expected}' instead of '{actual}'"
SIM906 = "SIM906 Use '{expected}' instead of '{actual}'"
# ast.Constant in Python 3.8, ast.NameConstant in Python 3.6 and 3.7
BOOL_CONST_TYPES = (ast.Constant, ast.NameConstant)
AST_CONST_TYPES = (ast.Constant, ast.NameConstant, ast.Str, ast.Num)
STR_TYPES = (ast.Constant, ast.Str)
def strip_parenthesis(string: str) -> str:
if len(string) >= 2 and string[0] == "(" and string[-1] == ")":
return string[1:-1]
return string
def strip_triple_quotes(string: str) -> str:
quotes = '"""'
is_tripple_quoted = string.startswith(quotes) and string.endswith(quotes)
if not (
is_tripple_quoted and '"' not in string[len(quotes) : -len(quotes)]
):
return string
string = string[len(quotes) : -len(quotes)]
string = f'"{string}"'
if len(string) == 0:
string = '""'
return string
def use_double_quotes(string: str) -> str:
quotes = "'''"
if string.startswith(quotes) and string.endswith(quotes):
return f'"""{string[len(quotes):-len(quotes)]}"""'
if len(string) >= 2 and string[0] == "'" and string[-1] == "'":
return f'"{string[1:-1]}"'
return string
def to_source(
node: Union[None, ast.expr, ast.Expr, ast.withitem, ast.slice]
) -> str:
if node is None:
return "None"
source: str = astor.to_source(node).strip()
source = strip_parenthesis(source)
source = strip_triple_quotes(source)
source = use_double_quotes(source)
return source
def _get_duplicated_isinstance_call_by_node(node: ast.BoolOp) -> List[str]:
"""
Get a list of isinstance arguments which could be shortened.
This checks SIM101.
Examples
--------
>> g = _get_duplicated_isinstance_call_by_node
>> g("isinstance(a, int) or isinstance(a, float) or isinstance(b, int)
['a']
>> g("isinstance(a, int) or isinstance(b, float) or isinstance(b, int)
['b']
"""
counter: DefaultDict[str, int] = defaultdict(int)
for call in node.values:
# Make sure that this function call is actually a call of the built-in
# "isinstance"
if not isinstance(call, ast.Call) or len(call.args) != 2:
continue
function_name = to_source(call.func)
if function_name != "isinstance":
continue
# Collect the name of the argument
isinstance_arg0_name = to_source(call.args[0])
counter[isinstance_arg0_name] += 1
return [arg0_name for arg0_name, count in counter.items() if count > 1]
def _get_sim101(
node: ast.BoolOp,
) -> List[Tuple[int, int, str]]:
"""Get a positions where the duplicate isinstance problem appears."""
errors: List[Tuple[int, int, str]] = []
if not isinstance(node.op, ast.Or):
return errors
for var in _get_duplicated_isinstance_call_by_node(node):
errors.append((node.lineno, node.col_offset, SIM101.format(var=var)))
return errors
def _get_sim102(node: ast.If) -> List[Tuple[int, int, str]]:
"""Get a list of all nested if-statements without else-blocks."""
errors: List[Tuple[int, int, str]] = []
# ## Pattern 1
# if a: <---
# if b: <---
# c
is_pattern_1 = (
node.orelse == []
and len(node.body) == 1
and isinstance(node.body[0], ast.If)
and node.body[0].orelse == []
)
# ## Pattern 2
# if a: < irrelvant for here
# pass
# elif b: <--- this is treated like a nested block
# if c: <---
# d
if not is_pattern_1:
return errors
errors.append((node.lineno, node.col_offset, SIM102))
return errors
def _get_sim103(node: ast.If) -> List[Tuple[int, int, str]]:
"""
Get a list of all calls that wrap a condition to return a bool.
if cond:
return True
else:
return False
which is
If(
test=Name(id='cond', ctx=Load()),
body=[
Return(
value=Constant(value=True, kind=None),
),
],
orelse=[
Return(
value=Constant(value=False, kind=None),
),
],
),
"""
errors: List[Tuple[int, int, str]] = []
if (
len(node.body) != 1
or not isinstance(node.body[0], ast.Return)
or not isinstance(node.body[0].value, BOOL_CONST_TYPES)
or not (
node.body[0].value.value is True
or node.body[0].value.value is False
)
or len(node.orelse) != 1
or not isinstance(node.orelse[0], ast.Return)
or not isinstance(node.orelse[0].value, BOOL_CONST_TYPES)
or not (
node.orelse[0].value.value is True
or node.orelse[0].value.value is False
)
):
return errors
cond = to_source(node.test)
errors.append((node.lineno, node.col_offset, SIM103.format(cond=cond)))
return errors
def _get_sim104(node: ast.For) -> List[Tuple[int, int, str]]:
"""
Get a list of all "iterate and yield" patterns.
for item in iterable:
yield item
which is
For(
target=Name(id='item', ctx=Store()),
iter=Name(id='iterable', ctx=Load()),
body=[
Expr(
value=Yield(
value=Name(id='item', ctx=Load()),
),
),
],
orelse=[],
type_comment=None,
),
"""
errors: List[Tuple[int, int, str]] = []
if (
len(node.body) != 1
or not isinstance(node.body[0], ast.Expr)
or not isinstance(node.body[0].value, ast.Yield)
or not isinstance(node.target, ast.Name)
or not isinstance(node.body[0].value.value, ast.Name)
or node.target.id != node.body[0].value.value.id
or node.orelse != []
):
return errors
if isinstance(node.parent, ast.AsyncFunctionDef): # type: ignore
return errors
iterable = to_source(node.iter)
errors.append(
(node.lineno, node.col_offset, SIM104.format(iterable=iterable))
)
return errors
def _get_sim105(node: ast.Try) -> List[Tuple[int, int, str]]:
"""
Get a list of all "try-except-pass" patterns.
try:
foo()
except ValueError:
pass
which is
Try(
body=[
Expr(
value=Call(
func=Name(id='foo', ctx=Load()),
args=[],
keywords=[],
),
),
],
handlers=[
ExceptHandler(
type=Name(id='ValueError', ctx=Load()),
name=None,
body=[Pass()],
),
],
orelse=[],
finalbody=[],
),
"""
errors: List[Tuple[int, int, str]] = []
if (
len(node.body) != 1
or len(node.handlers) != 1
or not isinstance(node.handlers[0], ast.ExceptHandler)
or len(node.handlers[0].body) != 1
or not isinstance(node.handlers[0].body[0], ast.Pass)
or node.orelse != []
):
return errors
if node.handlers[0].type is None:
exception = "Exception"
else:
exception = to_source(node.handlers[0].type)
errors.append(
(node.lineno, node.col_offset, SIM105.format(exception=exception))
)
return errors
def _get_sim106(node: ast.If) -> List[Tuple[int, int, str]]:
"""
Get a list of all calls where an exception is raised in else.
if cond:
return True
else:
raise Exception
which is
If(
test=Name(id='cond', ctx=Load()),
body=[
Expr(
value=Name(id='a', ctx=Load()),
),
Expr(
value=Name(id='b', ctx=Load()),
),
Expr(
value=Name(id='c', ctx=Load()),
),
],
orelse=[
Raise(
exc=Name(id='Exception', ctx=Load()),
cause=None,
),
],
)
"""
errors: List[Tuple[int, int, str]] = []
just_one = (
len(node.orelse) == 1
and len(node.orelse) >= 1
and isinstance(node.orelse[-1], ast.Raise)
and not isinstance(node.body[-1], ast.Raise)
)
many = (
len(node.body) > 2 * len(node.orelse)
and len(node.orelse) >= 1
and isinstance(node.orelse[-1], ast.Raise)
and not isinstance(node.body[-1], ast.Raise)
)
if not (just_one or many):
return errors
ast_raise = node.orelse[-1]
if not isinstance(ast_raise, ast.Raise):
return errors
ast_raised = ast_raise.exc
if (
isinstance(ast_raised, ast.Call)
and ast_raised.func
and isinstance(ast_raised.func, ast.Name)
and ast_raised.func.id in ["ValueError", "NotImplementedError"]
):
return errors
errors.append((node.lineno, node.col_offset, SIM106))
return errors
def _get_sim107(node: ast.Try) -> List[Tuple[int, int, str]]:
"""
Get a list of all calls where try/except and finally have 'return'.
"""
errors: List[Tuple[int, int, str]] = []
try_has_return = False
for stmt in node.body:
if isinstance(stmt, ast.Return):
try_has_return = True
break
except_has_return = False
for stmt2 in node.handlers:
if isinstance(stmt2, ast.Return):
except_has_return = True
break
finally_has_return = False
finally_return = None
for stmt in node.finalbody:
if isinstance(stmt, ast.Return):
finally_has_return = True
finally_return = stmt
break
if (try_has_return or except_has_return) and finally_has_return:
assert finally_return is not None, "hint for mypy"
errors.append(
(finally_return.lineno, finally_return.col_offset, SIM107)
)
return errors
def _get_sim108(node: ast.If) -> List[Tuple[int, int, str]]:
"""
Get a list of all if-elses which could be a ternary operator assignment.
If(
test=Name(id='a', ctx=Load()),
body=[
Assign(
targets=[Name(id='b', ctx=Store())],
value=Name(id='c', ctx=Load()),
type_comment=None,
),
],
orelse=[
Assign(
targets=[Name(id='b', ctx=Store())],
value=Name(id='d', ctx=Load()),
type_comment=None,
),
],
),
"""
errors: List[Tuple[int, int, str]] = []
if not (
len(node.body) == 1
and len(node.orelse) == 1
and isinstance(node.body[0], ast.Assign)
and isinstance(node.orelse[0], ast.Assign)
and len(node.body[0].targets) == 1
and len(node.orelse[0].targets) == 1
and isinstance(node.body[0].targets[0], ast.Name)
and isinstance(node.orelse[0].targets[0], ast.Name)
and node.body[0].targets[0].id == node.orelse[0].targets[0].id
):
return errors
assign = to_source(node.body[0].targets[0])
body = to_source(node.body[0].value)
cond = to_source(node.test)
orelse = to_source(node.orelse[0].value)
new_code = SIM108.format(
assign=assign, body=body, cond=cond, orelse=orelse
)
if len(new_code) > 79:
return errors
errors.append((node.lineno, node.col_offset, new_code))
return errors
def _get_sim109(node: ast.BoolOp) -> List[Tuple[int, int, str]]:
"""
Check if multiple equalities with the same value are combined via "or".
BoolOp(
op=Or(),
values=[
Compare(
left=Name(id='a', ctx=Load()),
ops=[Eq()],
comparators=[Name(id='b', ctx=Load())],
),
Compare(
left=Name(id='a', ctx=Load()),
ops=[Eq()],
comparators=[Name(id='c', ctx=Load())],
),
],
)
"""
errors: List[Tuple[int, int, str]] = []
if not isinstance(node.op, ast.Or):
return errors
equalities = [
value
for value in node.values
if isinstance(value, ast.Compare)
and len(value.ops) == 1
and isinstance(value.ops[0], ast.Eq)
]
id2vals: Dict[str, List[ast.Name]] = defaultdict(list)
for eq in equalities:
if (
isinstance(eq.left, ast.Name)
and len(eq.comparators) == 1
and isinstance(eq.comparators[0], ast.Name)
):
id2vals[eq.left.id].append(eq.comparators[0])
for value, values in id2vals.items():
if len(values) == 1:
continue
errors.append(
(
node.lineno,
node.col_offset,
SIM109.format(
or_op=to_source(node),
value=value,
values=f"({to_source(ast.Tuple(elts=values))})",
),
)
)
return errors
def _get_sim110_sim111(node: ast.For) -> List[Tuple[int, int, str]]:
"""
Check if any / all could be used.
For(
target=Name(id='x', ctx=Store()),
iter=Name(id='iterable', ctx=Load()),
body=[
If(
test=Call(
func=Name(id='check', ctx=Load()),
args=[Name(id='x', ctx=Load())],
keywords=[],
),
body=[
Return(
value=Constant(value=True, kind=None),
),
],
orelse=[],
),
],
orelse=[],
type_comment=None,
),
Return(value=Constant(value=False, kind=None))
"""
errors: List[Tuple[int, int, str]] = []
if not (
len(node.body) == 1
and isinstance(node.body[0], ast.If)
and len(node.body[0].body) == 1
and isinstance(node.body[0].body[0], ast.Return)
and isinstance(node.body[0].body[0].value, BOOL_CONST_TYPES)
):
return errors
if not hasattr(node.body[0].body[0].value, "value"):
return errors
if isinstance(node.next_sibling, ast.Raise): # type: ignore
return errors
check = to_source(node.body[0].test)
target = to_source(node.target)
iterable = to_source(node.iter)
if node.body[0].body[0].value.value is True:
errors.append(
(
node.lineno,
node.col_offset,
SIM110.format(check=check, target=target, iterable=iterable),
)
)
elif node.body[0].body[0].value.value is False:
is_compound_expression = " and " in check or " or " in check
if is_compound_expression:
check = f"not ({check})"
else:
if check.startswith("not "):
check = check[len("not ") :]
else:
check = f"not {check}"
errors.append(
(
node.lineno,
node.col_offset,
SIM111.format(check=check, target=target, iterable=iterable),
)
)
return errors
def _get_sim112(node: ast.Expr) -> List[Tuple[int, int, str]]:
"""
Find non-capitalized calls to environment variables.
os.environ["foo"]
Expr(
value=Subscript(
value=Attribute(
value=Name(id='os', ctx=Load()),
attr='environ',
ctx=Load(),
),
slice=Index(
value=Constant(value='foo', kind=None),
),
ctx=Load(),
),
),
"""
errors: List[Tuple[int, int, str]] = []
is_index_call = (
isinstance(node.value, ast.Subscript)
and isinstance(node.value.value, ast.Attribute)
and isinstance(node.value.value.value, ast.Name)
and node.value.value.value.id == "os"
and node.value.value.attr == "environ"
and (
(
isinstance(node.value.slice, ast.Index)
and isinstance(node.value.slice.value, STR_TYPES) # type: ignore # noqa
)
or isinstance(node.value.slice, ast.Constant)
)
)
if is_index_call:
subscript = node.value
assert isinstance(subscript, ast.Subscript), "hint for mypy" # noqa
slice_ = subscript.slice
if isinstance(slice_, ast.Index):
# Python < 3.9
string_part = slice_.value # type: ignore
assert isinstance(string_part, STR_TYPES), "hint for mypy" # noqa
env_name = to_source(string_part)
elif isinstance(slice_, ast.Constant):
# Python 3.9
env_name = to_source(slice_)
# Check if this has a change
has_change = env_name != env_name.upper()
is_get_call = (
isinstance(node.value, ast.Call)
and isinstance(node.value.func, ast.Attribute)
and isinstance(node.value.func.value, ast.Attribute)
and isinstance(node.value.func.value.value, ast.Name)
and node.value.func.value.value.id == "os"
and node.value.func.value.attr == "environ"
and node.value.func.attr == "get"
and len(node.value.args) in [1, 2]
and isinstance(node.value.args[0], STR_TYPES)
)
if is_get_call:
call = node.value
assert isinstance(call, ast.Call), "hint for mypy" # noqa
string_part = call.args[0]
assert isinstance(string_part, STR_TYPES), "hint for mypy" # noqa
env_name = to_source(string_part)
# Check if this has a change
has_change = env_name != env_name.upper()
if not (is_index_call or is_get_call) or not has_change:
return errors
if is_index_call:
original = to_source(node)
expected = f"os.environ[{env_name.upper()}]"
elif is_get_call:
original = to_source(node)
if len(node.value.args) == 1: # type: ignore
expected = f"os.environ.get({env_name.upper()})"
else:
assert isinstance(node.value, ast.Call), "hint for mypy" # noqa
default_value = to_source(node.value.args[1])
expected = f"os.environ.get({env_name.upper()}, {default_value})"
else:
return errors
errors.append(
(
node.lineno,
node.col_offset,
SIM112.format(original=original, expected=expected),
)
)
return errors
def _get_sim113(node: ast.For) -> List[Tuple[int, int, str]]:
"""
Find loops in which "enumerate" should be used.
For(
target=Name(id='el', ctx=Store()),
iter=Name(id='iterable', ctx=Load()),
body=[
Expr(
value=Constant(value=Ellipsis, kind=None),
),
AugAssign(
target=Name(id='idx', ctx=Store()),
op=Add(),
value=Constant(value=1, kind=None),
),
],
orelse=[],
type_comment=None,
),
"""
errors: List[Tuple[int, int, str]] = []
variable_candidates = []
if body_contains_continue(node.body):
return errors
for expression in node.body:
if (
isinstance(expression, ast.AugAssign)
and is_constant_increase(expression)
and isinstance(expression.target, ast.Name)
):
variable_candidates.append(expression.target)
for candidate in variable_candidates:
errors.append(
(
candidate.lineno,
candidate.col_offset,
SIM113.format(variable=to_source(candidate)),
)
)
return errors
def body_contains_continue(stmts: List[ast.stmt]) -> bool:
return any(
isinstance(stmt, ast.Continue)
or (isinstance(stmt, ast.If) and body_contains_continue(stmt.body))
for stmt in stmts
)
def _get_sim114(node: ast.If) -> List[Tuple[int, int, str]]:
"""
Find same bodys.
Examples
--------
If(
test=Name(id='a', ctx=Load()),
body=[
Expr(
value=Name(id='b', ctx=Load()),
),
],
orelse=[
If(
test=Name(id='c', ctx=Load()),
body=[
Expr(
value=Name(id='b', ctx=Load()),
),
],
orelse=[],
),
],
),
"""
errors: List[Tuple[int, int, str]] = []
if_body_pairs = get_if_body_pairs(node)
error_pairs = []
for i in range(len(if_body_pairs) - 1):
# It's not all combinations because of this:
# https://github.com/MartinThoma/flake8-simplify/issues/70
# #issuecomment-924074984
ifbody1 = if_body_pairs[i]
ifbody2 = if_body_pairs[i + 1]
if is_body_same(ifbody1[1], ifbody2[1]):
error_pairs.append((ifbody1, ifbody2))
for ifbody1, ifbody2 in error_pairs:
errors.append(
(
ifbody1[0].lineno,
ifbody1[0].col_offset,
SIM114.format(
cond1=to_source(ifbody1[0]), cond2=to_source(ifbody2[0])
),
)
)
return errors
def _get_sim115(node: Call) -> List[Tuple[int, int, str]]:
"""
Find places where open() is called without a context handler.
Example AST
-----------
Assign(
targets=[Name(id='f', ctx=Store())],
value=Call(
func=Name(id='open', ctx=Load()),
args=[Constant(value=Ellipsis, kind=None)],
keywords=[],
),
type_comment=None,
)
...
Expr(
value=Call(
func=Attribute(
value=Name(id='f', ctx=Load()),
attr='close',
ctx=Load(),
),
args=[],
keywords=[],
),
),
"""
errors: List[Tuple[int, int, str]] = []
if not (
isinstance(node.func, ast.Name)
and node.func.id == "open"
and not isinstance(node.parent, ast.withitem)
):
return errors
errors.append((node.lineno, node.col_offset, SIM115))
return errors
def _get_sim116(node: ast.If) -> List[Tuple[int, int, str]]:
"""
Find places where 3 or more consecutive if-statements with direct returns.
* Each if-statement must be a check for equality with the
same variable
* Each if-statement must just have a "return"
* Else must also just have a return
"""
errors: List[Tuple[int, int, str]] = []
if not (
isinstance(node.test, ast.Compare)
and isinstance(node.test.left, ast.Name)
and len(node.test.ops) == 1
and isinstance(node.test.ops[0], ast.Eq)
and len(node.test.comparators) == 1
and isinstance(node.test.comparators[0], AST_CONST_TYPES)
and len(node.body) == 1
and isinstance(node.body[0], ast.Return)
and len(node.orelse) == 1
and isinstance(node.orelse[0], ast.If)
):
return errors
variable = node.test.left
child: Optional[ast.If] = node.orelse[0]
assert isinstance(child, ast.If), "hint for mypy"
else_value: Optional[str] = None
key_value_pairs: Dict[Any, Any]
if isinstance(node.test.comparators[0], ast.Str):
value = to_source(node.body[0].value)
if value[0] == '"' and value[-1] == '"':
value = value[1:-1]
key_value_pairs = {node.test.comparators[0].s: value}
elif isinstance(node.test.comparators[0], ast.Num):
key_value_pairs = {
node.test.comparators[0].n: to_source(node.body[0].value)
}
else:
key_value_pairs = {
node.test.comparators[0].value: to_source(node.body[0].value)
}
while child:
if not (
isinstance(child.test, ast.Compare)
and isinstance(child.test.left, ast.Name)
and child.test.left.id == variable.id
and len(child.test.ops) == 1
and isinstance(child.test.ops[0], ast.Eq)
and len(child.test.comparators) == 1
and isinstance(child.test.comparators[0], AST_CONST_TYPES)
and len(child.body) == 1
and isinstance(child.body[0], ast.Return)
and len(child.orelse) <= 1
):
return errors
key: Any
if isinstance(child.test.comparators[0], ast.Str):
key = child.test.comparators[0].s
elif isinstance(child.test.comparators[0], ast.Num):
key = child.test.comparators[0].n
else:
key = child.test.comparators[0].value
value = to_source(child.body[0].value)
if value[0] == '"' and value[-1] == '"':
value = value[1:-1]
key_value_pairs[key] = value
if len(child.orelse) == 1:
if isinstance(child.orelse[0], ast.If):
child = child.orelse[0]
elif isinstance(child.orelse[0], ast.Return):
else_value = to_source(child.orelse[0].value)
child = None
else:
return errors
else:
child = None
if len(key_value_pairs) < 3:
return errors
if else_value:
ret = f"{key_value_pairs}.get({variable.id}, {else_value})"
else:
ret = f"{key_value_pairs}.get({variable.id})"
errors.append((node.lineno, node.col_offset, SIM116.format(ret=ret)))
return errors
def _get_sim117(node: ast.With) -> List[Tuple[int, int, str]]:
"""
Find multiple with-statements with same scope.
With(
items=[
withitem(
context_expr=Call(
func=Name(id='A', ctx=Load()),
args=[],
keywords=[],
),
optional_vars=Name(id='a', ctx=Store()),
),
],
body=[
With(
items=[
withitem(
context_expr=Call(
func=Name(id='B', ctx=Load()),
args=[],