Repository navigation
Expand file tree
/
Copy pathbugbear.py
More file actions
4113 lines (3664 loc) · 156 KB
/
Copy pathbugbear.py
File metadata and controls
4113 lines (3664 loc) · 156 KB
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
from __future__ import annotations
import ast
import builtins
import io
import itertools
import logging
import math
import re
import symtable
import sys
import tokenize
import warnings
from collections import Counter, defaultdict
from contextlib import suppress
from functools import lru_cache
from keyword import iskeyword
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
NamedTuple,
Protocol,
Sequence,
cast,
)
import attr # type: ignore
import pycodestyle # type: ignore
from flake8.exceptions import PluginExecutionFailed
__version__ = "26.9.30"
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)
EAGER_COMPREHENSION_NODES = (ast.ListComp, ast.SetComp, ast.DictComp)
FUNCTIONS_WITHOUT_SIDE_EFFECTS = (
"all",
"any",
"dict",
"frozenset",
"isinstance",
"issubclass",
"len",
"max",
"min",
"repr",
"set",
"sorted",
"str",
"tuple",
)
# Arithmetic operators whose result is all a statement like `a * b` produces.
# Shifts, bitwise operators and `@` are left out: libraries overload them for
# their side effects, such as Airflow's `task1 >> task2`.
B018_ARITHMETIC_OPERATORS = (
ast.Add,
ast.Sub,
ast.Mult,
ast.Div,
ast.FloorDiv,
ast.Mod,
ast.Pow,
)
# Builtins that return a lazy iterator, so `map(print, items)` as a statement
# never calls `print`. `iter` is left out: `iter(x)` calls `x.__iter__()` right
# away, which is what a bare `iter(x)` is usually for.
B018_LAZY_FUNCTIONS = ("enumerate", "filter", "map", "reversed", "zip")
B018_RAISING_BLOCKS: tuple[type[ast.stmt], ...] = (ast.Try, ast.With, ast.AsyncWith)
if sys.version_info >= (3, 11):
B018_RAISING_BLOCKS += (ast.TryStar,)
B908_pytest_functions = {"raises", "warns"}
B908_unittest_methods = {
"assertRaises",
"assertRaisesRegex",
"assertRaisesRegexp",
"assertWarns",
"assertWarnsRegex",
}
B902_default_decorators = {"classmethod"}
class Context(NamedTuple):
node: ast.AST
stack: list[ast.AST]
def _defines_a_generator(function_node: ast.FunctionDef) -> bool:
"""Does this function's own body contain a yield? (nested ones do not count)"""
stack = list(function_node.body)
while stack:
node = stack.pop()
if isinstance(node, (ast.Yield, ast.YieldFrom)):
return True
if isinstance(node, FUNCTION_NODES):
continue
stack.extend(ast.iter_child_nodes(node))
return False
def _is_rebound(
name: str, names_used: dict[str, list[ast.Name]], parents: dict[int, ast.AST]
) -> bool:
"""Is `name` bound anywhere in this scope other than by the definition?"""
return any(
isinstance(reference.ctx, (ast.Store, ast.Del))
for reference in names_used.get(name, ())
)
@attr.s(unsafe_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, factory=lambda: BugBearVisitor)
options = attr.ib(default=None)
def run(self) -> Iterable[tuple[int, int, str, type]]:
if not self.tree or not self.lines:
self.load_file()
if self.options and hasattr(self.options, "extend_immutable_calls"):
b008_b039_extend_immutable_calls = set(self.options.extend_immutable_calls)
else:
b008_b039_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_b039_extend_immutable_calls=b008_b039_extend_immutable_calls,
b902_classmethod_decorators=b902_classmethod_decorators,
)
try:
visitor.visit(self.tree)
except RecursionError as exc:
raise PluginExecutionFailed(self.filename, self.name, exc) from exc
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 _doc_line_numbers(self) -> set[int]:
"""Return the line numbers that pycodestyle's W505 treats as documentation.
These are lines holding only a comment and lines of a string or bytes literal
that is a statement on its own (docstrings), but not trailing comments or
strings that are part of code, even code after a `;` on the same line.
"""
doc_lines: set[int] = set()
for node in ast.walk(self.tree):
if (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, (str, bytes))
and not self.lines[node.lineno - 1][: node.col_offset].strip()
and self._only_comment_after(node)
):
doc_lines.update(range(node.lineno, (node.end_lineno or 0) + 1))
with suppress(tokenize.TokenError, SyntaxError):
for token in tokenize.generate_tokens(
io.StringIO("".join(self.lines)).readline
):
if (
token.type == tokenize.COMMENT
and not token.line[: token.start[1]].strip()
):
doc_lines.add(token.start[0])
return doc_lines
def _only_comment_after(self, node: ast.expr) -> bool:
"""Whether nothing but a comment follows `node` on its last line."""
line = self.lines[(node.end_lineno or node.lineno) - 1].encode()
rest = line[node.end_col_offset or 0 :].decode(errors="replace").strip()
return not rest or rest.startswith("#")
def gen_line_based_checks(self) -> Iterator["error"]:
"""gen_line_based_checks() -> (error, error, error, ...)
The following simple checks are based on the raw lines, not the AST.
"""
# Only when `max-doc-length` is configured are docstring and comment lines
# measured against it instead of `max-line-length`.
max_doc_length: int | None = getattr(self.options, "max_doc_length", None)
doc_lines = self._doc_line_numbers() if max_doc_length is not None else set()
noqa_type_ignore_regex = re.compile(
r"#\s*(noqa|type:\s*ignore|pragma:)[^#\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)
max_length = self.max_line_length
if max_doc_length is not None and lineno in doc_lines:
max_length = max_doc_length
length = len(no_comment_line) - 1
if length > 1.1 * max_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 >= max_length - 7
)
skip = is_line_comment_url_path or just_long_url_path
if skip and not too_many_leading_white_spaces:
continue
yield error_codes["B950"](lineno, length, vars=(length, max_length))
@classmethod
def adapt_error(cls, e: error) -> tuple[int, int, str, type]:
"""Adapts the extended error namedtuple to be compatible with Flake8."""
return e._replace(message=e.message.format(*e.vars))[:4]
def load_file(self) -> None:
"""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: Any) -> None:
"""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: str) -> bool:
"""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) -> bool:
# 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: ast.expr | None) -> Iterator[ast.expr | None]:
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: Sequence[str], node: ast.ExceptHandler, in_trystar: str
):
# 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 error_codes["B014"](
node.lineno,
node.col_offset,
vars=(", ".join(names), as_, desc, in_trystar),
)
return None
def _to_name_str(node: ast.expr | None) -> str | None:
# 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 _truthy_constant_kind(node: ast.expr) -> str | None:
"""Describe a constant that is always truthy, like `"x"` or `-1`."""
if (
isinstance(node, ast.UnaryOp)
and isinstance(node.op, (ast.UAdd, ast.USub))
and isinstance(node.operand, ast.Constant)
and not isinstance(node.operand.value, (str, bytes))
):
node = node.operand
if not isinstance(node, ast.Constant) or not node.value:
return None
if isinstance(node.value, str):
return "non-empty string"
if isinstance(node.value, bytes):
return "non-empty bytes"
# `assert False` is B011, and `assert True` is left alone on purpose
if isinstance(node.value, (int, float, complex)) and not isinstance(
node.value, bool
):
return "non-zero number"
return None
def names_from_assignments(assign_target: ast.expr) -> Iterator[str]:
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 _nested_tables(table: Any, deep: bool) -> Iterator[Any]:
"""Tables of the functions nested in `table`, looking through class bodies and
the annotation and type parameter scopes of Python 3.12+."""
for child in table.get_children() if table else ():
is_function = isinstance(child, symtable.Function)
if is_function:
yield child
if deep or not is_function:
yield from _nested_tables(child, deep)
def children_in_scope(node: ast.AST) -> Iterator[ast.AST]:
yield node
if not isinstance(node, FUNCTION_NODES):
for child in ast.iter_child_nodes(node):
yield from children_in_scope(child)
def _typesafe_issubclass(cls: type, class_or_tuple: type | tuple[type, ...]) -> bool:
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
class ExceptBaseExceptionVisitor(ast.NodeVisitor):
def __init__(self, except_node: ast.ExceptHandler) -> None:
super().__init__()
self.root = except_node
self._re_raised = False
def re_raised(self) -> bool:
self.visit(self.root)
return self._re_raised
def visit_Raise(self, node: ast.Raise) -> None:
"""If we find a corresponding `raise` or `raise e` where e was from
`except BaseException as e:` then we mark re_raised as True and can
stop scanning."""
if node.exc is None or (
isinstance(node.exc, ast.Name) and node.exc.id == self.root.name
):
self._re_raised = True
return
return super().generic_visit(node)
def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
if node is not self.root:
return # entered a nested except - stop searching
return super().generic_visit(node)
@attr.define
class B040CaughtException:
name: str
has_note: bool
class B041UnhandledKeyType:
"""
A dictionary key of a type that we do not check for duplicates.
"""
@attr.define(frozen=True)
class B041VariableKeyType:
name: str
class AstPositionNode(Protocol):
lineno: int
col_offset: int
def _b906_is_libcst_module(module: str | None, level: int) -> bool:
return (
level == 0
and module is not None
and (module == "libcst" or module.startswith("libcst."))
)
def _b906_import_binding(alias: ast.alias) -> tuple[str, str | None]:
"""``(bound name, libcst kind)`` for an ``import`` alias; kind is
``"module"`` for ``import libcst[.sub] [as x]``, else ``None``."""
bound = alias.asname or alias.name.partition(".")[0]
kind = "module" if _b906_is_libcst_module(alias.name, 0) else None
return bound, kind
def _b906_importfrom_binding(
node: ast.ImportFrom, alias: ast.alias
) -> tuple[str, str | None]:
kind = "name" if _b906_is_libcst_module(node.module, node.level) else None
return alias.asname or alias.name, kind
def _b906_named_binding(node: ast.AST) -> str:
"""Name bound by a ``match``/``except`` node itself ('' if none)."""
if isinstance(node, (ast.MatchAs, ast.MatchStar, ast.ExceptHandler)):
return node.name or ""
if isinstance(node, ast.MatchMapping):
return node.rest or ""
return ""
def _b906_scope_bindings( # noqa: C901
statements: list[ast.stmt], cutoff: ast.AST, base: dict[str, str | None]
) -> dict[str, str | None]:
"""Resolve names in one scope body up to (excluding) ``cutoff``.
Walks one scope's statements in order without descending into nested
function/class/lambda/comprehension scopes (their bindings are their
own; eager comprehensions only leak walruses, handled explicitly).
Each name maps to ``"module"``/``"name"`` if its latest binding is a
libcst import (see :func:`_b906_import_binding`), else ``None``. Uses
latest binding wins, so a rebinding shadows an earlier import and a
later import shadows an earlier rebinding. Bare annotations
(``x: T``) do not bind. ``global``/``nonlocal`` are not modelled:
they only occur inside functions, whose scopes are never resolved.
"""
result = dict(base)
def bind(name: str, kind: str | None) -> None:
result[name] = kind
def visit_definition(
node: ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda,
) -> None:
# Only the parts evaluated in this scope, then the name binding.
# Lambdas bind no name in this scope (handled by the caller).
name: str | None = None
if isinstance(node, ast.ClassDef):
parts: list[ast.AST] = [
*node.decorator_list,
*node.bases,
*node.keywords,
]
name = node.name
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
parts = list(_b906_definition_exprs(node))
name = node.name
else:
parts = list(_b906_definition_exprs(node))
for part in parts:
visit(part)
if name is not None:
bind(name, None)
def visit_comprehension(
node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp,
) -> None:
# Targets are comprehension-local; only walruses in the iterated/
# element expressions bind in this scope.
for generator in node.generators:
visit(generator.iter)
for condition in generator.ifs:
visit(condition)
if isinstance(node, ast.DictComp):
if node.key is not None:
visit(node.key)
visit(node.value)
else:
visit(node.elt)
def visit(node: ast.AST) -> None:
if node is cutoff:
return
if isinstance(node, FUNCTION_NODES + (ast.ClassDef,)):
visit_definition(node)
return
if isinstance(
node, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
):
visit_comprehension(node)
return
if isinstance(node, ast.Import):
for alias in node.names:
bound, kind = _b906_import_binding(alias)
bind(bound, kind)
return
if isinstance(node, ast.ImportFrom):
for alias in node.names:
if alias.name == "*":
continue
bound, kind = _b906_importfrom_binding(node, alias)
bind(bound, kind)
return
if isinstance(node, ast.AnnAssign) and node.value is None:
visit(node.annotation)
if not isinstance(node.target, ast.Name):
visit(node.target)
return
if isinstance(node, ast.NamedExpr) and isinstance(node.target, ast.Name):
visit(node.value)
bind(node.target.id, None)
return
if isinstance(node, ast.Name):
if isinstance(node.ctx, (ast.Store, ast.Del)):
bind(node.id, None)
return
if isinstance(
node, (ast.ExceptHandler, ast.MatchAs, ast.MatchStar, ast.MatchMapping)
):
bound = _b906_named_binding(node)
if bound:
bind(bound, None)
for child in ast.iter_child_nodes(node):
visit(child)
return
for child in ast.iter_child_nodes(node):
visit(child)
for stmt in statements:
if stmt is cutoff:
break
visit(stmt)
return result
def _b906_definition_exprs(
node: ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda,
) -> list[ast.expr]:
"""Expressions of a function/lambda evaluated in the enclosing scope."""
if isinstance(node, ast.Lambda):
return [
default
for default in (*node.args.defaults, *node.args.kw_defaults)
if default is not None
]
exprs: list[ast.expr] = list(node.decorator_list)
args = [
*node.args.posonlyargs,
*node.args.args,
*node.args.kwonlyargs,
]
if node.args.vararg is not None:
args.append(node.args.vararg)
if node.args.kwarg is not None:
args.append(node.args.kwarg)
exprs.extend(arg.annotation for arg in args if arg.annotation is not None)
exprs.extend(
default
for default in (*node.args.defaults, *node.args.kw_defaults)
if default is not None
)
if node.returns is not None:
exprs.append(node.returns)
return exprs
def _b031_module_groupby_is_itertools(module: ast.Module) -> bool:
"""Whether a bare ``groupby`` is ``itertools.groupby`` or never bound.
Whole-module ``ast.walk``; nested scopes are intentionally not modeled.
"""
from_itertools = False
other = False
for node in ast.walk(module):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
if node.name == "groupby":
other = True
elif isinstance(node, (ast.Import, ast.ImportFrom)):
for alias in node.names:
# Absolute ``from itertools import *`` binds ``groupby``.
# Other star imports do not. ``import groupby.sub`` does.
if alias.name == "*":
if (
isinstance(node, ast.ImportFrom)
and node.level == 0
and node.module == "itertools"
):
from_itertools = True
continue
bound = alias.asname or alias.name.split(".", 1)[0]
if bound != "groupby":
continue
if (
isinstance(node, ast.ImportFrom)
and node.level == 0
and node.module == "itertools"
and alias.name == "groupby"
):
from_itertools = True
else:
other = True
elif (
isinstance(node, ast.Name)
and node.id == "groupby"
and isinstance(node.ctx, ast.Store)
):
other = True
elif (
isinstance(node, (ast.MatchAs, ast.MatchStar, ast.ExceptHandler))
and node.name == "groupby"
) or (isinstance(node, ast.MatchMapping) and node.rest == "groupby"):
other = True
return from_itertools or not other
@attr.s
class BugBearVisitor(ast.NodeVisitor):
filename = attr.ib()
lines = attr.ib()
b008_b039_extend_immutable_calls: set[str] = attr.ib(factory=set)
b902_classmethod_decorators: set[str] = attr.ib(factory=set)
node_window: list[ast.AST] = attr.ib(factory=list)
errors: list[error] = attr.ib(factory=list)
contexts: list[Context] = attr.ib(factory=list)
b040_caught_exception: B040CaughtException | None = attr.ib(default=None)
NODE_WINDOW_SIZE = 4
_b023_seen: set[ast.Name] = attr.ib(factory=set, init=False)
_closure_reads_cache: dict[int, set[str]] = attr.ib(factory=dict, init=False)
_symtable_root: Any = attr.ib(default=False, init=False)
_b023_scopes: dict[int, tuple] = attr.ib(factory=dict, init=False)
_b005_imports: set[str] = attr.ib(factory=set, init=False)
# Module-scope libcst bindings from `_b906_scope_bindings` (name ->
# ``"module"``/``"name"``/``None``), resolved lazily per class so the
# position cutoff is the class being checked; ``None`` until known.
_b906_module_libcst: Callable[[ast.AST], dict[str, str | None]] | None = attr.ib(
default=None, init=False
)
# None marks an imported name that has since been rebound at module scope.
_b008_imports: dict[str, str | None] = attr.ib(factory=dict, init=False)
_b008_class_imports: list[dict[str, str | None]] = attr.ib(factory=list, init=False)
_b008_class_globals: list[set[str]] = attr.ib(factory=list, init=False)
# None until the enclosing module has been scanned for bindings of groupby.
_b031_bare_groupby_is_itertools: bool | None = attr.ib(default=None, init=False)
# set to "*" when inside a try/except*, for correctly printing errors
in_trystar: str = attr.ib(default="")
if False:
# Useful for tracing what the hell is going on.
def __getattr__(self, name: str): # type: ignore[unreachable]
print(name)
return self.__getattribute__(name)
def add_error(self, code: str, node: AstPositionNode, *vars: object) -> None:
self.errors.append(error_codes[code](node.lineno, node.col_offset, vars=vars))
@property
def node_stack(self) -> list[ast.AST]:
if len(self.contexts) == 0:
return []
context, stack = self.contexts[-1]
return stack
def _b008_shadow_imports(
self,
names: Iterable[str],
imports: dict[str, str | None] | None = None,
) -> None:
if imports is None:
imports = self._b008_imports
for name in names:
if imports.get(name) is not None:
imports[name] = None
def _b008_shadow_bindings(
self,
names: Iterable[str],
imports: dict[str, str | None] | None = None,
) -> None:
names = tuple(names)
self._b008_shadow_imports(names, imports)
if (
imports is not None
and self._b008_class_imports
and imports is self._b008_class_imports[-1]
and self._b008_class_globals
):
global_names = self._b008_class_globals[-1].intersection(names)
self._b008_shadow_imports(global_names)
def _b008_shadow_named_expr_targets(
self,
nodes: Iterable[ast.AST],
imports: dict[str, str | None] | None = None,
) -> None:
finder = B008NamedExprFinder()
finder.visit(list(nodes))
self._b008_shadow_bindings(finder.names, imports)
def _b008_in_module_scope(self) -> bool:
return len(self.contexts) == 1 and isinstance(self.contexts[0].node, ast.Module)
def _b008_is_direct_module_statement(self) -> bool:
return self._b008_in_module_scope() and len(self.node_stack) == 2
def _b008_in_module_child(self) -> bool:
return len(self.contexts) == 2 and isinstance(self.contexts[0].node, ast.Module)
def _b008_in_direct_module_child(self) -> bool:
return self._b008_in_module_child() and len(self.contexts[0].stack) == 1
def _b008_in_direct_module_class_scope(self) -> bool:
return self._b008_in_direct_module_child() and isinstance(
self.contexts[-1].node, ast.ClassDef
)
def _b008_in_direct_module_class_child(self) -> bool:
return (
len(self.contexts) == 3
and isinstance(self.contexts[0].node, ast.Module)
and isinstance(self.contexts[1].node, ast.ClassDef)
and len(self.contexts[1].stack) == 1
)
def _b008_binding_imports(self) -> dict[str, str | None] | None:
if self._b008_in_module_scope():
return self._b008_imports
if self._b008_in_direct_module_class_scope() and self._b008_class_imports:
return self._b008_class_imports[-1]
return None
def _b008_function_imports(self) -> dict[str, str | None] | None:
if self._b008_in_direct_module_child():
return self._b008_imports
if self._b008_in_direct_module_class_child() and self._b008_class_imports:
return self._b008_class_imports[-1]
return None
@staticmethod
def _b008_function_annotations(
node: ast.FunctionDef | ast.AsyncFunctionDef,
) -> list[ast.expr]:
arguments = [
*node.args.posonlyargs,
*node.args.args,
*node.args.kwonlyargs,
]
if node.args.vararg is not None:
arguments.append(node.args.vararg)
if node.args.kwarg is not None:
arguments.append(node.args.kwarg)
annotations = [argument.annotation for argument in arguments]
if node.returns is not None:
annotations.append(node.returns)
return [annotation for annotation in annotations if annotation is not None]
def in_class_init(self) -> bool:
return (
len(self.contexts) >= 2
and isinstance(self.contexts[-2].node, ast.ClassDef)
and isinstance(self.contexts[-1].node, ast.FunctionDef)
and self.contexts[-1].node.name == "__init__"
)
def visit_Return(self, node: ast.Return) -> None:
if self.in_class_init():
if node.value is not None:
self.add_error("B037", node)
self.generic_visit(node)
def visit_Yield(self, node: ast.Yield) -> None:
if self.in_class_init():
self.add_error("B037", node)
self.generic_visit(node)
def visit_YieldFrom(self, node: ast.YieldFrom) -> None:
if self.in_class_init():
self.add_error("B037", node)
self.generic_visit(node)
def visit(self, node: ast.AST) -> None:
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()
self.check_for_b018(node)
def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
if node.type is None:
self.add_error("B001", node)
self.generic_visit(node)
return
old_b040_caught_exception = self.b040_caught_exception
if node.name is None:
self.b040_caught_exception = None
else:
self.b040_caught_exception = B040CaughtException(node.name, False) # type: ignore[call-arg]
names = self.check_for_b013_b014_b029_b030(node)
if (
"BaseException" in names
and not ExceptBaseExceptionVisitor(node).re_raised()
):
self.add_error("B036", node)
self.generic_visit(node)
if (
self.b040_caught_exception is not None
and self.b040_caught_exception.has_note
):
self.add_error("B040", node)
self.b040_caught_exception = old_b040_caught_exception
imports = self._b008_binding_imports()
if imports is not None and node.name is not None:
self._b008_shadow_bindings((node.name,), imports)
def visit_UAdd(self, node: ast.UAdd) -> None:
trailing_nodes = list(map(type, self.node_window[-4:]))
if trailing_nodes == [ast.UnaryOp, ast.UAdd, ast.UnaryOp, ast.UAdd]:
originator = cast(ast.UnaryOp, self.node_window[-4])
self.add_error("B002", originator)
self.generic_visit(node)
def visit_Call(self, node: ast.Call) -> None:
is_b040_add_note = False
if isinstance(node.func, ast.Attribute):
self.check_for_b005(node)
is_b040_add_note = self.check_for_b040_add_note(node.func)
elif isinstance(node.func, ast.Name):
# Check for getattr/setattr/delattr with constant attribute names
with suppress(AttributeError, IndexError):
if (
node.func.id in ("getattr", "hasattr")
and isinstance(node.args[1], ast.Constant)
and node.args[1].value == "__call__"
):
self.add_error("B004", node)
if (
node.func.id == "getattr"
and len(node.args) == 2