forked from PyCQA/flake8-bugbear
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bugbear.py
1932 lines (1684 loc) · 68.3 KB
/
bugbear.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
import ast
import builtins
import itertools
import logging
import math
import re
import sys
import warnings
from collections import namedtuple
from contextlib import suppress
from functools import lru_cache, partial
from keyword import iskeyword
from typing import Dict, List, Set, Union
import attr
import pycodestyle
__version__ = "23.9.16"
LOG = logging.getLogger("flake8.bugbear")
CONTEXTFUL_NODES = (
ast.Module,
ast.ClassDef,
ast.AsyncFunctionDef,
ast.FunctionDef,
ast.Lambda,
ast.ListComp,
ast.SetComp,
ast.DictComp,
ast.GeneratorExp,
)
FUNCTION_NODES = (ast.AsyncFunctionDef, ast.FunctionDef, ast.Lambda)
B908_pytest_functions = {"raises", "warns"}
B908_unittest_methods = {
"assertRaises",
"assertRaisesRegex",
"assertRaisesRegexp",
"assertWarns",
"assertWarnsRegex",
}
B902_default_decorators = {"classmethod", "validator", "root_validator"}
Context = namedtuple("Context", ["node", "stack"])
@attr.s(hash=False)
class BugBearChecker:
name = "flake8-bugbear"
version = __version__
tree = attr.ib(default=None)
filename = attr.ib(default="(none)")
lines = attr.ib(default=None)
max_line_length = attr.ib(default=79)
visitor = attr.ib(init=False, default=attr.Factory(lambda: BugBearVisitor))
options = attr.ib(default=None)
def run(self):
if not self.tree or not self.lines:
self.load_file()
if self.options and hasattr(self.options, "extend_immutable_calls"):
b008_extend_immutable_calls = set(self.options.extend_immutable_calls)
else:
b008_extend_immutable_calls = set()
b902_classmethod_decorators: set[str] = B902_default_decorators
if self.options and hasattr(self.options, "classmethod_decorators"):
b902_classmethod_decorators = set(self.options.classmethod_decorators)
visitor = self.visitor(
filename=self.filename,
lines=self.lines,
b008_extend_immutable_calls=b008_extend_immutable_calls,
b902_classmethod_decorators=b902_classmethod_decorators,
)
visitor.visit(self.tree)
for e in itertools.chain(visitor.errors, self.gen_line_based_checks()):
if self.should_warn(e.message[:4]):
yield self.adapt_error(e)
def gen_line_based_checks(self):
"""gen_line_based_checks() -> (error, error, error, ...)
The following simple checks are based on the raw lines, not the AST.
"""
noqa_type_ignore_regex = re.compile(r"#\s*(noqa|type:\s*ignore)[^#\r\n]*$")
for lineno, line in enumerate(self.lines, start=1):
# Special case: ignore long shebang (following pycodestyle).
if lineno == 1 and line.startswith("#!"):
continue
# At first, removing noqa and type: ignore trailing comments"
no_comment_line = noqa_type_ignore_regex.sub("", line)
if no_comment_line != line:
no_comment_line = noqa_type_ignore_regex.sub("", no_comment_line)
length = len(no_comment_line) - 1
if length > 1.1 * self.max_line_length and no_comment_line.strip():
# Special case long URLS and paths to follow pycodestyle.
# Would use the `pycodestyle.maximum_line_length` directly but
# need to supply it arguments that are not available so chose
# to replicate instead.
chunks = no_comment_line.split()
is_line_comment_url_path = len(chunks) == 2 and chunks[0] == "#"
just_long_url_path = len(chunks) == 1
num_leading_whitespaces = len(no_comment_line) - len(chunks[-1])
too_many_leading_white_spaces = (
num_leading_whitespaces >= self.max_line_length - 7
)
skip = is_line_comment_url_path or just_long_url_path
if skip and not too_many_leading_white_spaces:
continue
yield B950(lineno, length, vars=(length, self.max_line_length))
@classmethod
def adapt_error(cls, e):
"""Adapts the extended error namedtuple to be compatible with Flake8."""
return e._replace(message=e.message.format(*e.vars))[:4]
def load_file(self):
"""Loads the file in a way that auto-detects source encoding and deals
with broken terminal encodings for stdin.
Stolen from flake8_import_order because it's good.
"""
if self.filename in ("stdin", "-", None):
self.filename = "stdin"
self.lines = pycodestyle.stdin_get_value().splitlines(True)
else:
self.lines = pycodestyle.readlines(self.filename)
if not self.tree:
self.tree = ast.parse("".join(self.lines))
@staticmethod
def add_options(optmanager):
"""Informs flake8 to ignore B9xx by default."""
optmanager.extend_default_ignore(disabled_by_default)
optmanager.add_option(
"--extend-immutable-calls",
comma_separated_list=True,
parse_from_config=True,
default=[],
help="Skip B008 test for additional immutable calls.",
)
# you cannot register the same option in two different plugins, so we
# only register --classmethod-decorators if pep8-naming is not installed
if "pep8ext_naming" not in sys.modules.keys():
optmanager.add_option(
"--classmethod-decorators",
comma_separated_list=True,
parse_from_config=True,
default=B902_default_decorators,
help=(
"List of method decorators that should be treated as classmethods"
" by B902"
),
)
@lru_cache # noqa: B019
def should_warn(self, code):
"""Returns `True` if Bugbear should emit a particular warning.
flake8 overrides default ignores when the user specifies
`ignore = ` in configuration. This is problematic because it means
specifying anything in `ignore = ` implicitly enables all optional
warnings. This function is a workaround for this behavior.
As documented in the README, the user is expected to explicitly select
the warnings.
NOTE: This method is deprecated and will be removed in a future release. It is
recommended to use `extend-ignore` and `extend-select` in your flake8
configuration to avoid implicitly altering selected and ignored codes.
"""
if code[:2] != "B9":
# Normal warnings are safe for emission.
return True
if self.options is None:
# Without options configured, Bugbear will emit B9 but flake8 will ignore
LOG.info(
"Options not provided to Bugbear, optional warning %s selected.", code
)
return True
for i in range(2, len(code) + 1):
if self.options.select and code[:i] in self.options.select:
return True
# flake8 >=4.0: Also check for codes in extend_select
if (
hasattr(self.options, "extend_select")
and self.options.extend_select
and code[:i] in self.options.extend_select
):
return True
LOG.info(
"Optional warning %s not present in selected warnings: %r. Not "
"firing it at all.",
code,
self.options.select,
)
return False
def _is_identifier(arg):
# Return True if arg is a valid identifier, per
# https://docs.python.org/2/reference/lexical_analysis.html#identifiers
if not isinstance(arg, ast.Constant) or not isinstance(arg.value, str):
return False
return re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", arg.value) is not None
def _flatten_excepthandler(node):
if not isinstance(node, ast.Tuple):
yield node
return
expr_list = node.elts.copy()
while len(expr_list):
expr = expr_list.pop(0)
if isinstance(expr, ast.Starred) and isinstance(
expr.value, (ast.List, ast.Tuple)
):
expr_list.extend(expr.value.elts)
continue
yield expr
def _check_redundant_excepthandlers(names, node):
# See if any of the given exception names could be removed, e.g. from:
# (MyError, MyError) # duplicate names
# (MyError, BaseException) # everything derives from the Base
# (Exception, TypeError) # builtins where one subclasses another
# (IOError, OSError) # IOError is an alias of OSError since Python3.3
# but note that other cases are impractical to handle from the AST.
# We expect this is mostly useful for users who do not have the
# builtin exception hierarchy memorised, and include a 'shadowed'
# subtype without realising that it's redundant.
good = sorted(set(names), key=names.index)
if "BaseException" in good:
good = ["BaseException"]
# Remove redundant exceptions that the automatic system either handles
# poorly (usually aliases) or can't be checked (e.g. it's not an
# built-in exception).
for primary, equivalents in B014.redundant_exceptions.items():
if primary in good:
good = [g for g in good if g not in equivalents]
for name, other in itertools.permutations(tuple(good), 2):
if _typesafe_issubclass(
getattr(builtins, name, type), getattr(builtins, other, ())
):
if name in good:
good.remove(name)
if good != names:
desc = good[0] if len(good) == 1 else "({})".format(", ".join(good))
as_ = " as " + node.name if node.name is not None else ""
return B014(
node.lineno,
node.col_offset,
vars=(", ".join(names), as_, desc),
)
return None
def _to_name_str(node):
# Turn Name and Attribute nodes to strings, e.g "ValueError" or
# "pkg.mod.error", handling any depth of attribute accesses.
# Return None for unrecognized nodes.
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.Call):
return _to_name_str(node.func)
elif isinstance(node, ast.Attribute):
inner = _to_name_str(node.value)
if inner is None:
return None
return f"{inner}.{node.attr}"
else:
return None
def names_from_assignments(assign_target):
if isinstance(assign_target, ast.Name):
yield assign_target.id
elif isinstance(assign_target, ast.Starred):
yield from names_from_assignments(assign_target.value)
elif isinstance(assign_target, (ast.List, ast.Tuple)):
for child in assign_target.elts:
yield from names_from_assignments(child)
def children_in_scope(node):
yield node
if not isinstance(node, FUNCTION_NODES):
for child in ast.iter_child_nodes(node):
yield from children_in_scope(child)
def walk_list(nodes):
for node in nodes:
yield from ast.walk(node)
def _typesafe_issubclass(cls, class_or_tuple):
try:
return issubclass(cls, class_or_tuple)
except TypeError:
# User code specifies a type that is not a type in our current run. Might be
# their error, might be a difference in our environments. We don't know so we
# ignore this
return False
@attr.s
class BugBearVisitor(ast.NodeVisitor):
filename = attr.ib()
lines = attr.ib()
b008_extend_immutable_calls = attr.ib(default=attr.Factory(set))
b902_classmethod_decorators = attr.ib(default=attr.Factory(set))
node_window = attr.ib(default=attr.Factory(list))
errors = attr.ib(default=attr.Factory(list))
futures = attr.ib(default=attr.Factory(set))
contexts = attr.ib(default=attr.Factory(list))
NODE_WINDOW_SIZE = 4
_b023_seen = attr.ib(factory=set, init=False)
_b005_imports = attr.ib(factory=set, init=False)
if False:
# Useful for tracing what the hell is going on.
def __getattr__(self, name):
print(name)
return self.__getattribute__(name)
@property
def node_stack(self):
if len(self.contexts) == 0:
return []
context, stack = self.contexts[-1]
return stack
def visit(self, node):
is_contextful = isinstance(node, CONTEXTFUL_NODES)
if is_contextful:
context = Context(node, [])
self.contexts.append(context)
self.node_stack.append(node)
self.node_window.append(node)
self.node_window = self.node_window[-self.NODE_WINDOW_SIZE :]
super().visit(node)
self.node_stack.pop()
if is_contextful:
self.contexts.pop()
def visit_ExceptHandler(self, node):
if node.type is None:
self.errors.append(B001(node.lineno, node.col_offset))
self.generic_visit(node)
return
handlers = _flatten_excepthandler(node.type)
names = []
bad_handlers = []
ignored_handlers = []
for handler in handlers:
if isinstance(handler, (ast.Name, ast.Attribute)):
name = _to_name_str(handler)
if name is None:
ignored_handlers.append(handler)
else:
names.append(name)
elif isinstance(handler, (ast.Call, ast.Starred)):
ignored_handlers.append(handler)
else:
bad_handlers.append(handler)
if bad_handlers:
self.errors.append(B030(node.lineno, node.col_offset))
if len(names) == 0 and not bad_handlers and not ignored_handlers:
self.errors.append(B029(node.lineno, node.col_offset))
elif (
len(names) == 1
and not bad_handlers
and not ignored_handlers
and isinstance(node.type, ast.Tuple)
):
self.errors.append(B013(node.lineno, node.col_offset, vars=names))
else:
maybe_error = _check_redundant_excepthandlers(names, node)
if maybe_error is not None:
self.errors.append(maybe_error)
self.generic_visit(node)
def visit_UAdd(self, node):
trailing_nodes = list(map(type, self.node_window[-4:]))
if trailing_nodes == [ast.UnaryOp, ast.UAdd, ast.UnaryOp, ast.UAdd]:
originator = self.node_window[-4]
self.errors.append(B002(originator.lineno, originator.col_offset))
self.generic_visit(node)
def visit_Call(self, node):
if isinstance(node.func, ast.Attribute):
self.check_for_b005(node)
else:
with suppress(AttributeError, IndexError):
if (
node.func.id in ("getattr", "hasattr")
and node.args[1].value == "__call__"
):
self.errors.append(B004(node.lineno, node.col_offset))
if (
node.func.id == "getattr"
and len(node.args) == 2
and _is_identifier(node.args[1])
and not iskeyword(node.args[1].value)
):
self.errors.append(B009(node.lineno, node.col_offset))
elif (
not any(isinstance(n, ast.Lambda) for n in self.node_stack)
and node.func.id == "setattr"
and len(node.args) == 3
and _is_identifier(node.args[1])
and not iskeyword(node.args[1].value)
):
self.errors.append(B010(node.lineno, node.col_offset))
self.check_for_b026(node)
self.check_for_b028(node)
self.check_for_b034(node)
self.check_for_b905(node)
self.generic_visit(node)
def visit_Module(self, node):
self.check_for_b018(node)
self.generic_visit(node)
def visit_Assign(self, node):
if len(node.targets) == 1:
t = node.targets[0]
if isinstance(t, ast.Attribute) and isinstance(t.value, ast.Name):
if (t.value.id, t.attr) == ("os", "environ"):
self.errors.append(B003(node.lineno, node.col_offset))
self.generic_visit(node)
def visit_For(self, node):
self.check_for_b007(node)
self.check_for_b020(node)
self.check_for_b023(node)
self.check_for_b031(node)
self.generic_visit(node)
def visit_AsyncFor(self, node):
self.check_for_b023(node)
self.generic_visit(node)
def visit_While(self, node):
self.check_for_b023(node)
self.generic_visit(node)
def visit_ListComp(self, node):
self.check_for_b023(node)
self.generic_visit(node)
def visit_SetComp(self, node):
self.check_for_b023(node)
self.generic_visit(node)
def visit_DictComp(self, node):
self.check_for_b023(node)
self.generic_visit(node)
def visit_GeneratorExp(self, node):
self.check_for_b023(node)
self.generic_visit(node)
def visit_Assert(self, node):
self.check_for_b011(node)
self.generic_visit(node)
def visit_AsyncFunctionDef(self, node):
self.check_for_b902(node)
self.check_for_b006_and_b008(node)
self.generic_visit(node)
def visit_FunctionDef(self, node):
self.check_for_b901(node)
self.check_for_b902(node)
self.check_for_b006_and_b008(node)
self.check_for_b018(node)
self.check_for_b019(node)
self.check_for_b021(node)
self.check_for_b906(node)
self.generic_visit(node)
def visit_ClassDef(self, node):
self.check_for_b903(node)
self.check_for_b018(node)
self.check_for_b021(node)
self.check_for_b024_and_b027(node)
self.generic_visit(node)
def visit_Try(self, node):
self.check_for_b012(node)
self.check_for_b025(node)
self.generic_visit(node)
def visit_Compare(self, node):
self.check_for_b015(node)
self.generic_visit(node)
def visit_Raise(self, node):
self.check_for_b016(node)
self.check_for_b904(node)
self.generic_visit(node)
def visit_With(self, node):
self.check_for_b017(node)
self.check_for_b022(node)
self.check_for_b908(node)
self.generic_visit(node)
def visit_JoinedStr(self, node):
self.check_for_b907(node)
self.generic_visit(node)
def visit_AnnAssign(self, node):
self.check_for_b032(node)
self.generic_visit(node)
def visit_Import(self, node):
self.check_for_b005(node)
self.generic_visit(node)
def visit_Set(self, node):
self.check_for_b033(node)
self.generic_visit(node)
def check_for_b005(self, node):
if isinstance(node, ast.Import):
for name in node.names:
self._b005_imports.add(name.asname or name.name)
elif isinstance(node, ast.Call):
if node.func.attr not in B005.methods:
return # method name doesn't match
if (
isinstance(node.func.value, ast.Name)
and node.func.value.id in self._b005_imports
):
return # method is being run on an imported module
if (
len(node.args) != 1
or not isinstance(node.args[0], ast.Constant)
or not isinstance(node.args[0].value, str)
):
return # used arguments don't match the builtin strip
call_path = ".".join(compose_call_path(node.func.value))
if call_path in B005.valid_paths:
return # path is exempt
value = node.args[0].value
if len(value) == 1:
return # stripping just one character
if len(value) == len(set(value)):
return # no characters appear more than once
self.errors.append(B005(node.lineno, node.col_offset))
def check_for_b006_and_b008(self, node):
visitor = FuntionDefDefaultsVisitor(self.b008_extend_immutable_calls)
visitor.visit(node.args.defaults + node.args.kw_defaults)
self.errors.extend(visitor.errors)
def check_for_b007(self, node):
targets = NameFinder()
targets.visit(node.target)
ctrl_names = set(filter(lambda s: not s.startswith("_"), targets.names))
body = NameFinder()
for expr in node.body:
body.visit(expr)
used_names = set(body.names)
for name in sorted(ctrl_names - used_names):
n = targets.names[name][0]
self.errors.append(B007(n.lineno, n.col_offset, vars=(name,)))
def check_for_b011(self, node):
if isinstance(node.test, ast.Constant) and node.test.value is False:
self.errors.append(B011(node.lineno, node.col_offset))
def check_for_b012(self, node):
def _loop(node, bad_node_types):
if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):
return
if isinstance(node, (ast.While, ast.For)):
bad_node_types = (ast.Return,)
elif isinstance(node, bad_node_types):
self.errors.append(B012(node.lineno, node.col_offset))
for child in ast.iter_child_nodes(node):
_loop(child, bad_node_types)
for child in node.finalbody:
_loop(child, (ast.Return, ast.Continue, ast.Break))
def check_for_b015(self, node):
if isinstance(self.node_stack[-2], ast.Expr):
self.errors.append(B015(node.lineno, node.col_offset))
def check_for_b016(self, node):
if isinstance(node.exc, ast.JoinedStr) or (
isinstance(node.exc, ast.Constant)
and (
isinstance(node.exc.value, (int, float, complex, str, bool))
or node.exc.value is None
)
):
self.errors.append(B016(node.lineno, node.col_offset))
def check_for_b017(self, node):
"""Checks for use of the evil syntax 'with assertRaises(Exception):'
or 'with pytest.raises(Exception)'.
This form of assertRaises will catch everything that subclasses
Exception, which happens to be the vast majority of Python internal
errors, including the ones raised when a non-existing method/function
is called, or a function is called with an invalid dictionary key
lookup.
"""
item = node.items[0]
item_context = item.context_expr
if (
hasattr(item_context, "func")
and isinstance(item_context.func, ast.Attribute)
and (
item_context.func.attr == "assertRaises"
or (
item_context.func.attr == "raises"
and isinstance(item_context.func.value, ast.Name)
and item_context.func.value.id == "pytest"
and "match" not in [kwd.arg for kwd in item_context.keywords]
)
)
and len(item_context.args) == 1
and isinstance(item_context.args[0], ast.Name)
and item_context.args[0].id == "Exception"
and not item.optional_vars
):
self.errors.append(B017(node.lineno, node.col_offset))
def check_for_b019(self, node):
if (
len(node.decorator_list) == 0
or len(self.contexts) < 2
or not isinstance(self.contexts[-2].node, ast.ClassDef)
):
return
# Preserve decorator order so we can get the lineno from the decorator node
# rather than the function node (this location definition changes in Python 3.8)
resolved_decorators = (
".".join(compose_call_path(decorator)) for decorator in node.decorator_list
)
for idx, decorator in enumerate(resolved_decorators):
if decorator in {"classmethod", "staticmethod"}:
return
if decorator in B019.caches:
self.errors.append(
B019(
node.decorator_list[idx].lineno,
node.decorator_list[idx].col_offset,
)
)
return
def check_for_b020(self, node):
targets = NameFinder()
targets.visit(node.target)
ctrl_names = set(targets.names)
iterset = B020NameFinder()
iterset.visit(node.iter)
iterset_names = set(iterset.names)
for name in sorted(ctrl_names):
if name in iterset_names:
n = targets.names[name][0]
self.errors.append(B020(n.lineno, n.col_offset, vars=(name,)))
def check_for_b023(self, loop_node): # noqa: C901
"""Check that functions (including lambdas) do not use loop variables.
https://docs.python-guide.org/writing/gotchas/#late-binding-closures from
functions - usually but not always lambdas - defined inside a loop are a
classic source of bugs.
For each use of a variable inside a function defined inside a loop, we
emit a warning if that variable is reassigned on each loop iteration
(outside the function). This includes but is not limited to explicit
loop variables like the `x` in `for x in range(3):`.
"""
# Because most loops don't contain functions, it's most efficient to
# implement this "backwards": first we find all the candidate variable
# uses, and then if there are any we check for assignment of those names
# inside the loop body.
safe_functions = []
suspicious_variables = []
for node in ast.walk(loop_node):
# check if function is immediately consumed to avoid false alarm
if isinstance(node, ast.Call):
# check for filter&reduce
if (
isinstance(node.func, ast.Name)
and node.func.id in ("filter", "reduce", "map")
) or (
isinstance(node.func, ast.Attribute)
and node.func.attr == "reduce"
and isinstance(node.func.value, ast.Name)
and node.func.value.id == "functools"
):
for arg in node.args:
if isinstance(arg, FUNCTION_NODES):
safe_functions.append(arg)
# check for key=
for keyword in node.keywords:
if keyword.arg == "key" and isinstance(
keyword.value, FUNCTION_NODES
):
safe_functions.append(keyword.value)
# mark `return lambda: x` as safe
# does not (currently) check inner lambdas in a returned expression
# e.g. `return (lambda: x, )
if isinstance(node, ast.Return):
if isinstance(node.value, FUNCTION_NODES):
safe_functions.append(node.value)
# find unsafe functions
if isinstance(node, FUNCTION_NODES) and node not in safe_functions:
argnames = {
arg.arg for arg in ast.walk(node.args) if isinstance(arg, ast.arg)
}
if isinstance(node, ast.Lambda):
body_nodes = ast.walk(node.body)
else:
body_nodes = itertools.chain.from_iterable(map(ast.walk, node.body))
errors = []
for name in body_nodes:
if isinstance(name, ast.Name) and name.id not in argnames:
if isinstance(name.ctx, ast.Load):
errors.append(
B023(name.lineno, name.col_offset, vars=(name.id,))
)
elif isinstance(name.ctx, ast.Store):
argnames.add(name.id)
for err in errors:
if err.vars[0] not in argnames and err not in self._b023_seen:
self._b023_seen.add(err) # dedupe across nested loops
suspicious_variables.append(err)
if suspicious_variables:
reassigned_in_loop = set(self._get_assigned_names(loop_node))
for err in sorted(suspicious_variables):
if reassigned_in_loop.issuperset(err.vars):
self.errors.append(err)
def check_for_b024_and_b027(self, node: ast.ClassDef): # noqa: C901
"""Check for inheritance from abstract classes in abc and lack of
any methods decorated with abstract*"""
def is_abc_class(value, name="ABC"):
# class foo(metaclass = [abc.]ABCMeta)
if isinstance(value, ast.keyword):
return value.arg == "metaclass" and is_abc_class(value.value, "ABCMeta")
# class foo(ABC)
# class foo(abc.ABC)
return (isinstance(value, ast.Name) and value.id == name) or (
isinstance(value, ast.Attribute)
and value.attr == name
and isinstance(value.value, ast.Name)
and value.value.id == "abc"
)
def is_abstract_decorator(expr):
return (isinstance(expr, ast.Name) and expr.id[:8] == "abstract") or (
isinstance(expr, ast.Attribute) and expr.attr[:8] == "abstract"
)
def is_overload(expr):
return (isinstance(expr, ast.Name) and expr.id == "overload") or (
isinstance(expr, ast.Attribute) and expr.attr == "overload"
)
def empty_body(body) -> bool:
def is_str_or_ellipsis(node):
return isinstance(node, ast.Constant) and (
node.value is Ellipsis or isinstance(node.value, str)
)
# Function body consist solely of `pass`, `...`, and/or (doc)string literals
return all(
isinstance(stmt, ast.Pass)
or (isinstance(stmt, ast.Expr) and is_str_or_ellipsis(stmt.value))
for stmt in body
)
# don't check multiple inheritance
# https://github.com/PyCQA/flake8-bugbear/issues/277
if len(node.bases) + len(node.keywords) > 1:
return
# only check abstract classes
if not any(map(is_abc_class, (*node.bases, *node.keywords))):
return
has_method = False
has_abstract_method = False
for stmt in node.body:
# https://github.com/PyCQA/flake8-bugbear/issues/293
# Ignore abc's that declares a class attribute that must be set
if isinstance(stmt, (ast.AnnAssign, ast.Assign)):
has_abstract_method = True
continue
# only check function defs
if not isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
has_method = True
has_abstract_decorator = any(
map(is_abstract_decorator, stmt.decorator_list)
)
has_abstract_method |= has_abstract_decorator
if (
not has_abstract_decorator
and empty_body(stmt.body)
and not any(map(is_overload, stmt.decorator_list))
):
self.errors.append(
B027(stmt.lineno, stmt.col_offset, vars=(stmt.name,))
)
if has_method and not has_abstract_method:
self.errors.append(B024(node.lineno, node.col_offset, vars=(node.name,)))
def check_for_b026(self, call: ast.Call):
if not call.keywords:
return
starreds = [arg for arg in call.args if isinstance(arg, ast.Starred)]
if not starreds:
return
first_keyword = call.keywords[0].value
for starred in starreds:
if (starred.lineno, starred.col_offset) > (
first_keyword.lineno,
first_keyword.col_offset,
):
self.errors.append(B026(starred.lineno, starred.col_offset))
def check_for_b031(self, loop_node): # noqa: C901
"""Check that `itertools.groupby` isn't iterated over more than once.
We emit a warning when the generator returned by `groupby()` is used
more than once inside a loop body or when it's used in a nested loop.
"""
# for <loop_node.target> in <loop_node.iter>: ...
if isinstance(loop_node.iter, ast.Call):
node = loop_node.iter
if (isinstance(node.func, ast.Name) and node.func.id in ("groupby",)) or (
isinstance(node.func, ast.Attribute)
and node.func.attr == "groupby"
and isinstance(node.func.value, ast.Name)
and node.func.value.id == "itertools"
):
# We have an invocation of groupby which is a simple unpacking
if isinstance(loop_node.target, ast.Tuple) and isinstance(
loop_node.target.elts[1], ast.Name
):
group_name = loop_node.target.elts[1].id
else:
# Ignore any `groupby()` invocation that isn't unpacked
return
num_usages = 0
for node in walk_list(loop_node.body):
# Handled nested loops
if isinstance(node, ast.For):
for nested_node in walk_list(node.body):
assert nested_node != node
if (
isinstance(nested_node, ast.Name)
and nested_node.id == group_name
):
self.errors.append(
B031(
nested_node.lineno,
nested_node.col_offset,
vars=(nested_node.id,),
)
)
# Handle multiple uses
if isinstance(node, ast.Name) and node.id == group_name:
num_usages += 1
if num_usages > 1:
self.errors.append(
B031(node.lineno, node.col_offset, vars=(node.id,))
)
def _get_assigned_names(self, loop_node):
loop_targets = (ast.For, ast.AsyncFor, ast.comprehension)
for node in children_in_scope(loop_node):
if isinstance(node, (ast.Assign)):
for child in node.targets:
yield from names_from_assignments(child)
if isinstance(node, loop_targets + (ast.AnnAssign, ast.AugAssign)):
yield from names_from_assignments(node.target)
def check_for_b904(self, node):
"""Checks `raise` without `from` inside an `except` clause.
In these cases, you should use explicit exception chaining from the
earlier error, or suppress it with `raise ... from None`. See
https://docs.python.org/3/tutorial/errors.html#exception-chaining
"""
if (
node.cause is None
and node.exc is not None
and not (isinstance(node.exc, ast.Name) and node.exc.id.islower())
and any(isinstance(n, ast.ExceptHandler) for n in self.node_stack)
):
self.errors.append(B904(node.lineno, node.col_offset))
def walk_function_body(self, node):
def _loop(parent, node):
if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):
return
yield parent, node
for child in ast.iter_child_nodes(node):
yield from _loop(node, child)
for child in node.body:
yield from _loop(node, child)
def check_for_b901(self, node):
if node.name == "__await__":
return
has_yield = False
return_node = None
for parent, x in self.walk_function_body(node):
# Only consider yield when it is part of an Expr statement.
if isinstance(parent, ast.Expr) and isinstance(
x, (ast.Yield, ast.YieldFrom)
):
has_yield = True
if isinstance(x, ast.Return) and x.value is not None:
return_node = x
if has_yield and return_node is not None:
self.errors.append(B901(return_node.lineno, return_node.col_offset))
break
# taken from pep8-naming
@classmethod
def find_decorator_name(cls, d):
if isinstance(d, ast.Name):
return d.id