Skip to content

Commit 98829c3

Browse files
authored
Improve B018 further (#202)
Catch also useless expressions on the first node in a body if the node is not a string (docstring).
1 parent 2ca8d79 commit 98829c3

File tree

4 files changed

+14
-6
lines changed

4 files changed

+14
-6
lines changed

bugbear.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -578,8 +578,12 @@ def check_for_b903(self, node):
578578
self.errors.append(B903(node.lineno, node.col_offset))
579579

580580
def check_for_b018(self, node):
581-
for subnode in node.body[1:]:
582-
if isinstance(subnode, ast.Expr) and isinstance(
581+
for index, subnode in enumerate(node.body):
582+
if not isinstance(subnode, ast.Expr):
583+
continue
584+
if index == 0 and isinstance(subnode.value, ast.Str):
585+
continue # most likely a docstring
586+
if isinstance(
583587
subnode.value,
584588
(
585589
ast.Str,

tests/b018_classes.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""
22
Should emit:
3-
B018 - on lines 15-26, 31
3+
B018 - on lines 15-26, 30, 32
44
"""
55

66

@@ -27,5 +27,6 @@ class Foo2:
2727

2828

2929
class Foo3:
30+
123
3031
a = 2
3132
"str"

tests/b018_functions.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""
22
Should emit:
3-
B018 - on lines 14-25, 30
3+
B018 - on lines 14-25, 29, 31
44
"""
55

66

@@ -26,5 +26,6 @@ def foo2():
2626

2727

2828
def foo3():
29+
123
2930
a = 2
3031
"str"

tests/test_bugbear.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,8 @@ def test_b018_functions(self):
218218
errors = list(bbc.run())
219219

220220
expected = [B018(line, 4) for line in range(14, 26)]
221-
expected.append(B018(30, 4))
221+
expected.append(B018(29, 4))
222+
expected.append(B018(31, 4))
222223
self.assertEqual(errors, self.errors(*expected))
223224

224225
def test_b018_classes(self):
@@ -227,7 +228,8 @@ def test_b018_classes(self):
227228
errors = list(bbc.run())
228229

229230
expected = [B018(line, 4) for line in range(15, 27)]
230-
expected.append(B018(31, 4))
231+
expected.append(B018(30, 4))
232+
expected.append(B018(32, 4))
231233
self.assertEqual(errors, self.errors(*expected))
232234

233235
def test_b901(self):

0 commit comments

Comments
 (0)