Skip to content

Commit

Permalink
Add a fix for DictIterMissingItems
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielNoord committed Feb 6, 2024
1 parent 2e496dc commit 9ddbc95
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use ruff_python_ast::{Expr, ExprTuple};

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_semantic::analyze::typing::is_dict;
use ruff_text_size::Ranged;
Expand Down Expand Up @@ -30,11 +30,15 @@ use crate::checkers::ast::Checker;
#[violation]
pub struct DictIterMissingItems;

impl Violation for DictIterMissingItems {
impl AlwaysFixableViolation for DictIterMissingItems {
#[derive_message_formats]
fn message(&self) -> String {
format!("Call `items()` when unpacking a dictionary for iteration")
}

fn fix_title(&self) -> String {
format!("Add a call to `.items()`")
}
}

pub(crate) fn dict_iter_missing_items(checker: &mut Checker, target: &Expr, iter: &Expr) {
Expand All @@ -61,7 +65,10 @@ pub(crate) fn dict_iter_missing_items(checker: &mut Checker, target: &Expr, iter
return;
}

checker
.diagnostics
.push(Diagnostic::new(DictIterMissingItems, iter.range()));
let mut diagnostic = Diagnostic::new(DictIterMissingItems, iter.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
format!("{}.items()", name.id.to_string()),
iter.range(),
)));
checker.diagnostics.push(diagnostic);
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,42 @@
---
source: crates/ruff_linter/src/rules/pylint/mod.rs
---
dict_iter_missing_items.py:8:13: PLE1141 Call `items()` when unpacking a dictionary for iteration
dict_iter_missing_items.py:8:13: PLE1141 [*] Call `items()` when unpacking a dictionary for iteration
|
7 | # Errors
8 | for k, v in d:
| ^ PLE1141
9 | pass
|
= help: Add a call to `.items()`

dict_iter_missing_items.py:12:13: PLE1141 Call `items()` when unpacking a dictionary for iteration
Safe fix
5 5 | s2 = {1, 2, 3}
6 6 |
7 7 | # Errors
8 |-for k, v in d:
8 |+for k, v in d.items():
9 9 | pass
10 10 |
11 11 | # False positive, since the keys are all tuples this is valid

dict_iter_missing_items.py:12:13: PLE1141 [*] Call `items()` when unpacking a dictionary for iteration
|
11 | # False positive, since the keys are all tuples this is valid
12 | for a, b in d_tuple:
| ^^^^^^^ PLE1141
13 | pass
|
= help: Add a call to `.items()`

Safe fix
9 9 | pass
10 10 |
11 11 | # False positive, since the keys are all tuples this is valid
12 |-for a, b in d_tuple:
12 |+for a, b in d_tuple.items():
13 13 | pass
14 14 |
15 15 | # Non errors


0 comments on commit 9ddbc95

Please sign in to comment.