diff --git a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs index dd8a2124f25d60..0cf1575dbc52a7 100644 --- a/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs +++ b/crates/ruff_linter/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs @@ -12,9 +12,8 @@ use crate::rules::flake8_comprehensions::fixes; /// Checks for unnecessary `dict`, `list`, and `set` comprehension. /// /// ## Why is this bad? -/// It's unnecessary to use a `dict`/`list`/`set` comprehension to build a -/// data structure if the elements are unchanged. Wrap the iterable with -/// `dict()`, `list()`, or `set()` instead. +/// It's unnecessary to use a `dict`/`list`/`set` comprehension to build a data structure if the +/// elements are unchanged. Wrap the iterable with `dict()`, `list()`, or `set()` instead. /// /// ## Examples /// ```python @@ -30,10 +29,32 @@ use crate::rules::flake8_comprehensions::fixes; /// set(iterable) /// ``` /// +/// ## Known problems +/// +/// This rule may produce false positives for dictionary comprehensions that iterate over a mapping. +/// The `dict` constructor behaves differently depending on if it receives a sequence (e.g., a +/// `list`) or a mapping (e.g., a `dict`). When the comprension iterates over the keys of a mapping, +/// replacing it with a `dict` constructor will give a different result. +/// +/// For example: +/// +/// ```pycon +/// >>> d1 = {(1, 2): 3, (4, 5): 6} +/// >>> {x: y for x, y in d1} # Iterates over the keys of a mapping +/// {1: 2, 4: 5} +/// >>> dict(d1) # Ruff's incorrect suggested fix +/// (1, 2): 3, (4, 5): 6} +/// >>> dict(d1.keys()) # Correct fix +/// {1: 2, 4: 5} +/// ``` +/// +/// When the comprehension iterates over a sequence, Ruff's suggested fix is correct. However, Ruff +/// cannot consistently infer if the iterable type is a sequence or a mapping. +/// /// ## Fix safety -/// This rule's fix is marked as unsafe, as it may occasionally drop comments -/// when rewriting the comprehension. In most cases, though, comments will be -/// preserved. +/// Due to the known problem with dictionary comprehensions, this fix is marked as unsafe. +/// +/// Additionally, this fix may drop comments when rewriting the comprehension. #[violation] pub struct UnnecessaryComprehension { obj_type: String,