-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
Simplify key in dct and dct[key]
to dct.get(key)
#7895
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b17e596
unnecessary-key-check
harupy 11b3be4
autofix
harupy e4bcfd4
Update doc
harupy e667b67
Address comments
harupy 588449d
Remove checker.patch
harupy ffc2a02
Merge branch 'main' into unnecessary-key-check
charliermarsh 16f2b75
Tweak message
charliermarsh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
d = {} | ||
# RUF019 | ||
if "k" in d and d["k"]: | ||
pass | ||
|
||
k = "k" | ||
if k in d and d[k]: | ||
pass | ||
|
||
if (k) in d and d[k]: | ||
pass | ||
|
||
if k in d and d[(k)]: | ||
pass | ||
|
||
# OK | ||
v = "k" in d and d["k"] | ||
|
||
if f() in d and d[f()]: | ||
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
131 changes: 131 additions & 0 deletions
131
crates/ruff_linter/src/rules/ruff/rules/unnecessary_key_check.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
use ruff_python_ast::comparable::ComparableExpr; | ||
use ruff_python_ast::{self as ast, BoolOp, CmpOp, Expr}; | ||
|
||
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix}; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_python_ast::helpers::contains_effect; | ||
use ruff_python_ast::parenthesize::parenthesized_range; | ||
use ruff_text_size::Ranged; | ||
|
||
use crate::checkers::ast::Checker; | ||
|
||
/// ## What it does | ||
/// Checks for unnecessary key checks prior to accessing a dictionary. | ||
/// | ||
/// ## Why is this bad? | ||
/// When working with dictionaries, the `get` can be used to access a value | ||
/// without having to check if the dictionary contains the relevant key, | ||
/// returning `None` if the key is not present. | ||
/// | ||
/// ## Examples | ||
/// ```python | ||
/// if "key" in dct and dct["key"]: | ||
/// ... | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// if dct.get("key"): | ||
/// ... | ||
/// ``` | ||
#[violation] | ||
pub struct UnnecessaryKeyCheck; | ||
|
||
impl AlwaysFixableViolation for UnnecessaryKeyCheck { | ||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
format!("Unnecessary key check before dictionary access") | ||
} | ||
|
||
fn fix_title(&self) -> String { | ||
format!("Replace with `dict.get`") | ||
} | ||
} | ||
|
||
/// RUF019 | ||
pub(crate) fn unnecessary_key_check(checker: &mut Checker, expr: &Expr) { | ||
if !checker.semantic().in_boolean_test() { | ||
return; | ||
} | ||
|
||
let Expr::BoolOp(ast::ExprBoolOp { | ||
op: BoolOp::And, | ||
values, | ||
.. | ||
}) = expr | ||
else { | ||
return; | ||
}; | ||
|
||
let [left, right] = values.as_slice() else { | ||
return; | ||
}; | ||
|
||
// Left should be, e.g., `key in dct`. | ||
let Expr::Compare(ast::ExprCompare { | ||
left: key_left, | ||
ops, | ||
comparators, | ||
.. | ||
}) = left | ||
else { | ||
return; | ||
}; | ||
|
||
if !matches!(ops.as_slice(), [CmpOp::In]) { | ||
return; | ||
} | ||
|
||
let [obj_left] = comparators.as_slice() else { | ||
return; | ||
}; | ||
|
||
// Right should be, e.g., `dct[key]`. | ||
let Expr::Subscript(ast::ExprSubscript { | ||
value: obj_right, | ||
slice: key_right, | ||
.. | ||
}) = right | ||
else { | ||
return; | ||
}; | ||
|
||
if ComparableExpr::from(obj_left) != ComparableExpr::from(obj_right) | ||
|| ComparableExpr::from(key_left) != ComparableExpr::from(key_right) | ||
{ | ||
return; | ||
} | ||
|
||
if contains_effect(obj_left, |id| checker.semantic().is_builtin(id)) | ||
|| contains_effect(key_left, |id| checker.semantic().is_builtin(id)) | ||
{ | ||
return; | ||
} | ||
|
||
let mut diagnostic = Diagnostic::new(UnnecessaryKeyCheck, expr.range()); | ||
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( | ||
format!( | ||
"{}.get({})", | ||
checker.locator().slice( | ||
parenthesized_range( | ||
obj_right.into(), | ||
right.into(), | ||
checker.indexer().comment_ranges(), | ||
checker.locator().contents(), | ||
) | ||
.unwrap_or(obj_right.range()) | ||
), | ||
checker.locator().slice( | ||
parenthesized_range( | ||
key_right.into(), | ||
right.into(), | ||
checker.indexer().comment_ranges(), | ||
checker.locator().contents(), | ||
) | ||
.unwrap_or(key_right.range()) | ||
), | ||
), | ||
expr.range(), | ||
))); | ||
checker.diagnostics.push(diagnostic); | ||
} |
82 changes: 82 additions & 0 deletions
82
...ff_linter/src/rules/ruff/snapshots/ruff_linter__rules__ruff__tests__RUF019_RUF019.py.snap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
--- | ||
source: crates/ruff_linter/src/rules/ruff/mod.rs | ||
--- | ||
RUF019.py:3:4: RUF019 [*] Unnecessary key check before dictionary access | ||
| | ||
1 | d = {} | ||
2 | # RUF019 | ||
3 | if "k" in d and d["k"]: | ||
| ^^^^^^^^^^^^^^^^^^^ RUF019 | ||
4 | pass | ||
| | ||
= help: Replace with `dict.get` | ||
|
||
ℹ Fix | ||
1 1 | d = {} | ||
2 2 | # RUF019 | ||
3 |-if "k" in d and d["k"]: | ||
3 |+if d.get("k"): | ||
4 4 | pass | ||
5 5 | | ||
6 6 | k = "k" | ||
|
||
RUF019.py:7:4: RUF019 [*] Unnecessary key check before dictionary access | ||
| | ||
6 | k = "k" | ||
7 | if k in d and d[k]: | ||
| ^^^^^^^^^^^^^^^ RUF019 | ||
8 | pass | ||
| | ||
= help: Replace with `dict.get` | ||
|
||
ℹ Fix | ||
4 4 | pass | ||
5 5 | | ||
6 6 | k = "k" | ||
7 |-if k in d and d[k]: | ||
7 |+if d.get(k): | ||
8 8 | pass | ||
9 9 | | ||
10 10 | if (k) in d and d[k]: | ||
|
||
RUF019.py:10:4: RUF019 [*] Unnecessary key check before dictionary access | ||
| | ||
8 | pass | ||
9 | | ||
10 | if (k) in d and d[k]: | ||
| ^^^^^^^^^^^^^^^^^ RUF019 | ||
11 | pass | ||
| | ||
= help: Replace with `dict.get` | ||
|
||
ℹ Fix | ||
7 7 | if k in d and d[k]: | ||
8 8 | pass | ||
9 9 | | ||
10 |-if (k) in d and d[k]: | ||
10 |+if d.get(k): | ||
11 11 | pass | ||
12 12 | | ||
13 13 | if k in d and d[(k)]: | ||
|
||
RUF019.py:13:4: RUF019 [*] Unnecessary key check before dictionary access | ||
| | ||
11 | pass | ||
12 | | ||
13 | if k in d and d[(k)]: | ||
| ^^^^^^^^^^^^^^^^^ RUF019 | ||
14 | pass | ||
| | ||
= help: Replace with `dict.get` | ||
|
||
ℹ Fix | ||
10 10 | if (k) in d and d[k]: | ||
11 11 | pass | ||
12 12 | | ||
13 |-if k in d and d[(k)]: | ||
13 |+if d.get((k)): | ||
14 14 | pass | ||
15 15 | | ||
16 16 | # OK | ||
|
||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Future improvements could be to also support other checks like:
which could be replaced with:
Instead of
==
, there could be!=
,in
,not in
, etc.