Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[perflint] Implement try-except-in-loop (PERF203) #5166

Merged
merged 9 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions crates/ruff/resources/test/fixtures/perflint/PERF203.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
for i in range(10):
try: # PERF203
print(f"{i}")
except:
print("error")

try:
for i in range(10):
print(f"{i}")
except:
print("error")

i = 0
while i < 10: # PERF203
try:
print(f"{i}")
except:
print("error")

i += 1

try:
i = 0
while i < 10:
print(f"{i}")
i += 1
except:
print("error")
6 changes: 6 additions & 0 deletions crates/ruff/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1430,6 +1430,9 @@ where
if self.enabled(Rule::UselessElseOnLoop) {
pylint::rules::useless_else_on_loop(self, stmt, body, orelse);
}
if self.enabled(Rule::TryExceptInLoop) {
perflint::rules::try_except_in_loop(self, body);
}
}
Stmt::For(ast::StmtFor {
target,
Expand Down Expand Up @@ -1477,6 +1480,9 @@ where
if self.enabled(Rule::InDictKeys) {
flake8_simplify::rules::key_in_dict_for(self, target, iter);
}
if self.enabled(Rule::TryExceptInLoop) {
perflint::rules::try_except_in_loop(self, body);
}
}
if self.enabled(Rule::IncorrectDictIterator) {
perflint::rules::incorrect_dict_iterator(self, target, iter);
Expand Down
1 change: 1 addition & 0 deletions crates/ruff/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
// perflint
(Perflint, "101") => (RuleGroup::Unspecified, rules::perflint::rules::UnnecessaryListCast),
(Perflint, "102") => (RuleGroup::Unspecified, rules::perflint::rules::IncorrectDictIterator),
(Perflint, "203") => (RuleGroup::Unspecified, rules::perflint::rules::TryExceptInLoop),

// flake8-fixme
(Flake8Fixme, "001") => (RuleGroup::Unspecified, rules::flake8_fixme::rules::LineContainsFixme),
Expand Down
1 change: 1 addition & 0 deletions crates/ruff/src/rules/perflint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ mod tests {

#[test_case(Rule::UnnecessaryListCast, Path::new("PERF101.py"))]
#[test_case(Rule::IncorrectDictIterator, Path::new("PERF102.py"))]
#[test_case(Rule::TryExceptInLoop, Path::new("PERF203.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Expand Down
2 changes: 2 additions & 0 deletions crates/ruff/src/rules/perflint/rules/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
pub(crate) use incorrect_dict_iterator::*;
pub(crate) use try_except_in_loop::*;
pub(crate) use unnecessary_list_cast::*;

mod incorrect_dict_iterator;
mod try_except_in_loop;
mod unnecessary_list_cast;
74 changes: 74 additions & 0 deletions crates/ruff/src/rules/perflint/rules/try_except_in_loop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use rustpython_parser::ast::{self, Ranged, Stmt};

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};

use crate::checkers::ast::Checker;
use crate::settings::types::PythonVersion;

/// ## What it does
/// Checks for uses of except handling via `try`-`except` within `for` and
/// `while` loops.
///
/// ## Why is this bad?
/// Exception handling via `try`-`except` blocks incurs some performance
/// overhead, regardless of whether an exception is raised.
///
/// When possible, refactor your code to put the entire loop into the
/// `try`-`except` block, rather than wrapping each iteration in a separate
/// `try`-`except` block.
///
/// This rule is only enforced for Python versions prior to 3.11, which
/// introduced "zero cost" exception handling.
///
/// Note that, as with all `perflint` rules, this is only intended as a
/// micro-optimization, and will have a negligible impact on performance in
/// most cases.
///
/// ## Example
/// ```python
/// for i in range(10):
/// try:
/// print(i * i)
/// except:
/// break
/// ```
///
/// Use instead:
/// ```python
/// try:
/// for i in range(10):
/// print(i * i)
/// except:
/// break
/// ```
///
/// ## Options
/// - `target-version`
#[violation]
pub struct TryExceptInLoop;

impl Violation for TryExceptInLoop {
#[derive_message_formats]
fn message(&self) -> String {
format!("`try`-`except` within a loop incurs performance overhead")
}
}

/// PERF203
pub(crate) fn try_except_in_loop(checker: &mut Checker, body: &[Stmt]) {
if checker.settings.target_version >= PythonVersion::Py311 {
return;
}

checker.diagnostics.extend(body.iter().filter_map(|stmt| {
if let Stmt::Try(ast::StmtTry { handlers, .. }) = stmt {
handlers
.iter()
.next()
.map(|handler| Diagnostic::new(TryExceptInLoop, handler.range()))
} else {
None
}
}));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
source: crates/ruff/src/rules/perflint/mod.rs
---
PERF203.py:4:5: PERF203 `try`-`except` within a loop incurs performance overhead
|
2 | try: # PERF203
3 | print(f"{i}")
4 | except:
| _____^
5 | | print("error")
| |______________________^ PERF203
6 |
7 | try:
|

PERF203.py:17:5: PERF203 `try`-`except` within a loop incurs performance overhead
|
15 | try:
16 | print(f"{i}")
17 | except:
| _____^
18 | | print("error")
| |______________________^ PERF203
19 |
20 | i += 1
|


3 changes: 3 additions & 0 deletions ruff.schema.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions scripts/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ ignore = [
"G", # flake8-logging
"T", # flake8-print
"FBT", # flake8-boolean-trap
"PERF", # perflint
]

[tool.ruff.isort]
Expand Down
Loading