Skip to content

Commit

Permalink
Consider with statements for too many branches lint (#11321)
Browse files Browse the repository at this point in the history
Resolves #11313

## Summary

PLR0912(too-many-branches) did not count branches inside with: blocks.
With this fix, the branches inside with statements are also counted.

## Test Plan

Added a new test case.
  • Loading branch information
blueraft authored May 8, 2024
1 parent 29f2bc0 commit 8591adb
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Test for too many branches.
Taken from the pylint source 2023-02-03
"""
from contextlib import suppress

# pylint: disable=using-constant-test
def wrong(): # [too-many-branches]
""" Has too many branches. """
Expand Down Expand Up @@ -70,3 +72,33 @@ def nested_1():
pass
elif 7:
pass

def with_statement_wrong():
"""statements inside the with statement should get counted"""
with suppress(Exception):
if 1:
pass
elif 1:
pass
elif 1:
pass
elif 1:
pass
elif 1:
pass
elif 1:
pass
try:
pass
finally:
pass
if 2:
pass
while True:
pass
if 1:
pass
elif 2:
pass
elif 3:
pass
16 changes: 16 additions & 0 deletions crates/ruff_linter/src/rules/pylint/rules/too_many_branches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ fn num_branches(stmts: &[Stmt]) -> usize {
.map(|case| num_branches(&case.body))
.sum::<usize>()
}
Stmt::With(ast::StmtWith { body, .. }) => num_branches(body), // The `with` statement
// is not considered a branch but the statements inside the `with` should be counted
Stmt::For(ast::StmtFor { body, orelse, .. })
| Stmt::While(ast::StmtWhile { body, orelse, .. }) => {
1 + num_branches(body)
Expand Down Expand Up @@ -265,4 +267,18 @@ finally:
test_helper(source, 5)?;
Ok(())
}

#[test]
fn with_statement() -> Result<()> {
let source: &str = r"
with suppress(Exception):
if x == 0: # 2
return
else:
return
";

test_helper(source, 2)?;
Ok(())
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
---
source: crates/ruff_linter/src/rules/pylint/mod.rs
---
too_many_branches.py:6:5: PLR0912 Too many branches (13 > 12)
|
4 | """
5 | # pylint: disable=using-constant-test
6 | def wrong(): # [too-many-branches]
| ^^^^^ PLR0912
7 | """ Has too many branches. """
8 | if 1:
|

too_many_branches.py:8:5: PLR0912 Too many branches (13 > 12)
|
7 | # pylint: disable=using-constant-test
8 | def wrong(): # [too-many-branches]
| ^^^^^ PLR0912
9 | """ Has too many branches. """
10 | if 1:
|

too_many_branches.py:76:5: PLR0912 Too many branches (13 > 12)
|
74 | pass
75 |
76 | def with_statement_wrong():
| ^^^^^^^^^^^^^^^^^^^^ PLR0912
77 | """statements inside the with statement should get counted"""
78 | with suppress(Exception):
|

0 comments on commit 8591adb

Please sign in to comment.