Skip to content

Commit e7137ec

Browse files
authored
B906: ignore functions whose _fields attribute can't contain ast.AST subnodes (#335)
1 parent 4435548 commit e7137ec

File tree

3 files changed

+56
-4
lines changed

3 files changed

+56
-4
lines changed

README.rst

+5
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,11 @@ MIT
308308
Change Log
309309
----------
310310

311+
Future
312+
~~~~~~~~~
313+
314+
* B906: Ignore ``visit_`` functions with a ``_fields`` attribute that can't contain ast.AST subnodes. (#330)
315+
311316
23.1.17
312317
~~~~~~~~~
313318

bugbear.py

+21-4
Original file line numberDiff line numberDiff line change
@@ -997,12 +997,29 @@ def check_for_b906(self, node: ast.FunctionDef):
997997
if not node.name.startswith("visit_"):
998998
return
999999

1000-
# extract what's visited, only error if it's a valid ast subclass
1001-
# with a non-empty _fields attribute - which is what's iterated over in
1002-
# ast.NodeVisitor.generic_visit
1000+
# extract what's visited
10031001
class_name = node.name[len("visit_") :]
10041002
class_type = getattr(ast, class_name, None)
1005-
if class_type is None or not getattr(class_type, "_fields", None):
1003+
1004+
if (
1005+
# not a valid ast subclass
1006+
class_type is None
1007+
# doesn't have a non-empty '_fields' attribute - which is what's
1008+
# iterated over in ast.NodeVisitor.generic_visit
1009+
or not getattr(class_type, "_fields", None)
1010+
# or can't contain any ast subnodes that could be visited
1011+
# See https://docs.python.org/3/library/ast.html#abstract-grammar
1012+
or class_type.__name__
1013+
in (
1014+
"alias",
1015+
"Constant",
1016+
"Global",
1017+
"MatchSingleton",
1018+
"MatchStar",
1019+
"Nonlocal",
1020+
"TypeIgnore",
1021+
)
1022+
):
10061023
return
10071024

10081025
for n in itertools.chain.from_iterable(ast.walk(nn) for nn in node.body):

tests/b906.py

+30
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,33 @@ def a():
5454

5555
def visit_():
5656
...
57+
58+
59+
# Check exceptions for ast types that only contain ADSL builtin types
60+
# i.e. don't contain any ast.AST subnodes and therefore don't need a generic_visit
61+
def visit_alias():
62+
...
63+
64+
65+
def visit_Constant():
66+
...
67+
68+
69+
def visit_Global():
70+
...
71+
72+
73+
def visit_MatchSingleton():
74+
...
75+
76+
77+
def visit_MatchStar():
78+
...
79+
80+
81+
def visit_Nonlocal():
82+
...
83+
84+
85+
def visit_TypeIgnore():
86+
...

0 commit comments

Comments
 (0)