[`pylint`] Remove `try` body from branch counting (#11487)

## Summary

Matching Pylint, we now omit the `try` body itself from branch counting.
Each `except` counts as a branch, as does the `else` and the `finally`.

Closes https://github.com/astral-sh/ruff/issues/11205.
This commit is contained in:
Charlie Marsh 2024-05-21 23:38:51 -04:00 committed by GitHub
parent b0731ef9cb
commit 8848eca3c6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 57 additions and 8 deletions

View File

@ -21,6 +21,8 @@ def wrong(): # [too-many-branches]
pass
try:
pass
except Exception:
pass
finally:
pass
if 2:
@ -56,6 +58,8 @@ def good():
pass
try:
pass
except Exception:
pass
finally:
pass
if 1:
@ -90,6 +94,8 @@ def with_statement_wrong():
pass
try:
pass
except Exception:
pass
finally:
pass
if 2:

View File

@ -199,7 +199,9 @@ fn num_branches(stmts: &[Stmt]) -> usize {
finalbody,
..
}) => {
1 + num_branches(body)
// Count each `except` clause as a branch; the `else` and `finally` clauses also
// count, but the `try` clause itself does not.
num_branches(body)
+ (if orelse.is_empty() {
0
} else {
@ -323,6 +325,47 @@ return 1
Ok(())
}
#[test]
fn try_except() -> Result<()> {
let source: &str = r"
try:
pass
except:
pass
";
test_helper(source, 1)?;
Ok(())
}
#[test]
fn try_except_else() -> Result<()> {
let source: &str = r"
try:
pass
except:
pass
else:
pass
";
test_helper(source, 2)?;
Ok(())
}
#[test]
fn try_finally() -> Result<()> {
let source: &str = r"
try:
pass
finally:
pass
";
test_helper(source, 1)?;
Ok(())
}
#[test]
fn try_except_except_else_finally() -> Result<()> {
let source: &str = r"
@ -338,7 +381,7 @@ finally:
pass
";
test_helper(source, 5)?;
test_helper(source, 4)?;
Ok(())
}

View File

@ -10,12 +10,12 @@ too_many_branches.py:8:5: PLR0912 Too many branches (13 > 12)
10 | if 1:
|
too_many_branches.py:76:5: PLR0912 Too many branches (13 > 12)
too_many_branches.py:80:5: PLR0912 Too many branches (13 > 12)
|
74 | pass
75 |
76 | def with_statement_wrong():
78 | pass
79 |
80 | def with_statement_wrong():
| ^^^^^^^^^^^^^^^^^^^^ PLR0912
77 | """statements inside the with statement should get counted"""
78 | with suppress(Exception):
81 | """statements inside the with statement should get counted"""
82 | with suppress(Exception):
|