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

Mark PLE1141 fix as unsafe #13629

Merged
merged 3 commits into from
Oct 4, 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 @@ -33,7 +33,22 @@ use crate::checkers::ast::Checker;
///
/// for city, population in data.items():
/// print(f"{city} has population {population}.")
///
/// ## Known problems
/// If the dictionary key is a tuple, e.g.:
///
/// ```python
/// d = {(1, 2): 3, (3, 4): 5}
/// for x, y in d:
/// print(x, y)
/// ```
///
/// The tuple key is unpacked into `x` and `y` instead of the key and values. This means that
/// the suggested fix of using `d.items()` would result in different runtime behavior. Ruff
/// cannot consistently infer the type of a dictionary's keys.
///
/// ## Fix safety
/// Due to the known problem with tuple keys, this fix is unsafe.
#[violation]
pub struct DictIterMissingItems;

Expand All @@ -48,6 +63,7 @@ impl AlwaysFixableViolation for DictIterMissingItems {
}
}

/// PLE1141
pub(crate) fn dict_iter_missing_items(checker: &mut Checker, target: &Expr, iter: &Expr) {
let Expr::Tuple(tuple) = target else {
return;
Expand Down Expand Up @@ -78,7 +94,7 @@ pub(crate) fn dict_iter_missing_items(checker: &mut Checker, target: &Expr, iter
}

let mut diagnostic = Diagnostic::new(DictIterMissingItems, iter.range());
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
format!("{}.items()", name.id),
iter.range(),
)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ dict_iter_missing_items.py:13:13: PLE1141 [*] Unpacking a dictionary in iteratio
|
= help: Add a call to `.items()`

Safe fix
Unsafe fix
10 10 | s2 = {1, 2, 3}
11 11 |
12 12 | # Errors
Expand All @@ -30,14 +30,12 @@ dict_iter_missing_items.py:16:13: PLE1141 [*] Unpacking a dictionary in iteratio
|
= help: Add a call to `.items()`

Safe fix
Unsafe fix
13 13 | for k, v in d:
14 14 | pass
15 15 |
16 |-for k, v in d_tuple_incorrect_tuple:
16 |+for k, v in d_tuple_incorrect_tuple.items():
17 17 | pass
18 18 |
19 19 |


19 19 |
Loading