mirror of https://github.com/astral-sh/ruff
[`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:
parent
b0731ef9cb
commit
8848eca3c6
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
||||
|
|
|
|||
Loading…
Reference in New Issue