From 98829c3842c05b5b24305e275c5c5be7c782333c Mon Sep 17 00:00:00 2001 From: kasium <15907922+kasium@users.noreply.github.com> Date: Mon, 22 Nov 2021 18:02:53 +0100 Subject: [PATCH] Improve B018 further (#202) Catch also useless expressions on the first node in a body if the node is not a string (docstring). --- bugbear.py | 8 ++++++-- tests/b018_classes.py | 3 ++- tests/b018_functions.py | 3 ++- tests/test_bugbear.py | 6 ++++-- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/bugbear.py b/bugbear.py index efab5ab..d9d55a3 100644 --- a/bugbear.py +++ b/bugbear.py @@ -578,8 +578,12 @@ def check_for_b903(self, node): self.errors.append(B903(node.lineno, node.col_offset)) def check_for_b018(self, node): - for subnode in node.body[1:]: - if isinstance(subnode, ast.Expr) and isinstance( + for index, subnode in enumerate(node.body): + if not isinstance(subnode, ast.Expr): + continue + if index == 0 and isinstance(subnode.value, ast.Str): + continue # most likely a docstring + if isinstance( subnode.value, ( ast.Str, diff --git a/tests/b018_classes.py b/tests/b018_classes.py index 8a815d7..12195c0 100644 --- a/tests/b018_classes.py +++ b/tests/b018_classes.py @@ -1,6 +1,6 @@ """ Should emit: -B018 - on lines 15-26, 31 +B018 - on lines 15-26, 30, 32 """ @@ -27,5 +27,6 @@ class Foo2: class Foo3: + 123 a = 2 "str" diff --git a/tests/b018_functions.py b/tests/b018_functions.py index afb7d26..9764274 100644 --- a/tests/b018_functions.py +++ b/tests/b018_functions.py @@ -1,6 +1,6 @@ """ Should emit: -B018 - on lines 14-25, 30 +B018 - on lines 14-25, 29, 31 """ @@ -26,5 +26,6 @@ def foo2(): def foo3(): + 123 a = 2 "str" diff --git a/tests/test_bugbear.py b/tests/test_bugbear.py index 0ec95c4..0573e11 100644 --- a/tests/test_bugbear.py +++ b/tests/test_bugbear.py @@ -218,7 +218,8 @@ def test_b018_functions(self): errors = list(bbc.run()) expected = [B018(line, 4) for line in range(14, 26)] - expected.append(B018(30, 4)) + expected.append(B018(29, 4)) + expected.append(B018(31, 4)) self.assertEqual(errors, self.errors(*expected)) def test_b018_classes(self): @@ -227,7 +228,8 @@ def test_b018_classes(self): errors = list(bbc.run()) expected = [B018(line, 4) for line in range(15, 27)] - expected.append(B018(31, 4)) + expected.append(B018(30, 4)) + expected.append(B018(32, 4)) self.assertEqual(errors, self.errors(*expected)) def test_b901(self):