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

[pylint] - restrict iteration-over-set to only work on sets of literals (PLC0208) #13731

Merged
merged 4 commits into from
Oct 21, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,13 @@

for item in {*numbers_set, 4, 5, 6}: # set unpacking is fine
print(f"I like {item}.")

for item in {1, 2, 3, 4, 5, 6, 2 // 1}: # operations in set literals are fine
print(f"I like {item}.")

for item in {1, 2, 3, 4, 5, 6, int("7")}: # calls in set literals are fine
print(f"I like {item}.")

for item in {1, 2, 2}: # duplicate literals will be ignored
# B033 catches this
print(f"I like {item}.")
18 changes: 15 additions & 3 deletions crates/ruff_linter/src/rules/pylint/rules/iteration_over_set.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::Expr;
use ruff_python_ast::{comparable::ComparableExpr, Expr};
use ruff_text_size::Ranged;
use rustc_hash::{FxBuildHasher, FxHashSet};

use crate::checkers::ast::Checker;

/// ## What it does
/// Checks for iterations over `set` literals.
/// Checks for iteration over a `set` literal where each element in the set is
/// itself a literal value.
///
/// ## Why is this bad?
/// Iterating over a `set` is less efficient than iterating over a sequence
Expand Down Expand Up @@ -46,10 +48,20 @@ pub(crate) fn iteration_over_set(checker: &mut Checker, expr: &Expr) {
return;
};

if set.iter().any(Expr::is_starred_expr) {
if set.iter().any(|value| !value.is_literal_expr()) {
return;
}

let mut seen_values = FxHashSet::with_capacity_and_hasher(set.len(), FxBuildHasher);
for value in set {
let comparable_value = ComparableExpr::from(value);
if !seen_values.insert(comparable_value) {
// if the set contains a duplicate literal value, early exit.
// rule `B033` can catch that.
return;
}
}

let mut diagnostic = Diagnostic::new(IterationOverSet, expr.range());

let tuple = if let [elt] = set.elts.as_slice() {
Expand Down
Loading