Skip to content

Commit

Permalink
B012 Fix false positive with continue/break in loops in finally (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
João Eiras authored and cooperlees committed Jan 4, 2020
1 parent be0022d commit 04dd13b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
11 changes: 7 additions & 4 deletions bugbear.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,18 +285,21 @@ def check_for_b011(self, node):
self.errors.append(B011(node.lineno, node.col_offset))

def check_for_b012(self, node):
def _loop(node):
def _loop(node, bad_node_types):
if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):
return

if isinstance(node, (ast.Return, ast.Continue, ast.Break)):
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)
_loop(child, bad_node_types)

for child in node.finalbody:
_loop(child)
_loop(child, (ast.Return, ast.Continue, ast.Break))

def walk_function_body(self, node):
def _loop(parent, node):
Expand Down
12 changes: 12 additions & 0 deletions tests/b012.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,18 @@ def j():
continue # no warning


def k():
try:
pass
finally:
while True:
break # no warning
while True:
continue # no warning
while True:
return # warning


while True:
try:
pass
Expand Down
5 changes: 3 additions & 2 deletions tests/test_bugbear.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,9 @@ def test_b012(self):
B012(44, 20),
B012(66, 12),
B012(78, 12),
B012(89, 8),
B012(95, 8),
B012(94, 12),
B012(101, 8),
B012(107, 8),
]
self.assertEqual(errors, self.errors(*all_errors))

Expand Down

0 comments on commit 04dd13b

Please sign in to comment.