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

feat: update C416 with dict comprehension (autofixable) #3605

Merged
merged 7 commits into from
Mar 19, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_comprehensions/C416.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
x = [1, 2, 3]
y = [("a", 1), ("b", 2), ("c", 3)]
z = [(1,), (2,), (3,)]
d = {"a": 1, "b": 2, "c": 3}

[i for i in x]
{i for i in x}
{k: v for k, v in y}
{k: v for k, v in d.items()}

[i for i, in z]
[i for i, j in y]
[i for i in x if i > 1]
[i for i in x for j in x]

{v: k for k, v in y}
{k.foo: k for k in y}
{k["foo"]: k for k in y}
{k: v if v else None for k, v in y}
21 changes: 19 additions & 2 deletions crates/ruff/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3330,16 +3330,33 @@ where
}
ExprKind::ListComp { elt, generators } | ExprKind::SetComp { elt, generators } => {
if self.settings.rules.enabled(Rule::UnnecessaryComprehension) {
let elts: Vec<&Expr> = vec![elt];
flake8_comprehensions::rules::unnecessary_comprehension(
self, expr, elt, generators,
self, expr, &elts, generators,
);
}
if self.settings.rules.enabled(Rule::FunctionUsesLoopVariable) {
flake8_bugbear::rules::function_uses_loop_variable(self, &Node::Expr(expr));
}
self.ctx.push_scope(ScopeKind::Generator);
}
ExprKind::GeneratorExp { .. } | ExprKind::DictComp { .. } => {
ExprKind::DictComp {
key,
value,
generators,
} => {
if self.settings.rules.enabled(Rule::UnnecessaryComprehension) {
let elts: Vec<&Expr> = vec![key, value];
flake8_comprehensions::rules::unnecessary_comprehension(
self, expr, &elts, generators,
);
}
if self.settings.rules.enabled(Rule::FunctionUsesLoopVariable) {
flake8_bugbear::rules::function_uses_loop_variable(self, &Node::Expr(expr));
}
self.ctx.push_scope(ScopeKind::Generator);
}
ExprKind::GeneratorExp { .. } => {
if self.settings.rules.enabled(Rule::FunctionUsesLoopVariable) {
flake8_bugbear::rules::function_uses_loop_variable(self, &Node::Expr(expr));
}
Expand Down
24 changes: 23 additions & 1 deletion crates/ruff/src/rules/flake8_comprehensions/fixes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -961,8 +961,30 @@ pub fn fix_unnecessary_comprehension(
whitespace_before_args: ParenthesizableWhitespace::default(),
}));
}
Expression::DictComp(inner) => {
body.value = Expression::Call(Box::new(Call {
func: Box::new(Expression::Name(Box::new(Name {
value: "dict",
lpar: vec![],
rpar: vec![],
}))),
args: vec![Arg {
value: inner.for_in.iter.clone(),
keyword: None,
equal: None,
comma: None,
star: "",
whitespace_after_star: ParenthesizableWhitespace::default(),
whitespace_after_arg: ParenthesizableWhitespace::default(),
}],
lpar: vec![],
rpar: vec![],
whitespace_after_func: ParenthesizableWhitespace::default(),
whitespace_before_args: ParenthesizableWhitespace::default(),
}));
}
_ => {
bail!("Expected Expression::ListComp | Expression:SetComp");
bail!("Expected Expression::ListComp | Expression:SetComp | Expression:DictComp");
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use itertools::{EitherOrBoth, Itertools};
use log::error;
use rustpython_parser::ast::{Comprehension, Expr, ExprKind};

Expand Down Expand Up @@ -33,7 +34,7 @@ impl AlwaysAutofixableViolation for UnnecessaryComprehension {
pub fn unnecessary_comprehension(
checker: &mut Checker,
expr: &Expr,
elt: &Expr,
elts: &[&Expr],
dhruvmanila marked this conversation as resolved.
Show resolved Hide resolved
generators: &[Comprehension],
) {
if generators.len() != 1 {
Expand All @@ -43,19 +44,36 @@ pub fn unnecessary_comprehension(
if !(generator.ifs.is_empty() && generator.is_async == 0) {
return;
}
let Some(elt_id) = helpers::function_name(elt) else {
return;
};
let elt_ids: Vec<Option<&str>> = elts.iter().map(|&e| helpers::function_name(e)).collect();

let Some(target_id) = helpers::function_name(&generator.target) else {
return;
let target_ids: Vec<Option<&str>> = match &generator.target.node {
dhruvmanila marked this conversation as resolved.
Show resolved Hide resolved
ExprKind::Name { id, .. } => vec![Some(id.as_str())],
ExprKind::Tuple { elts, .. } => {
// If the target is a tuple of length 1, the comprehension is
// used to flatten the iterable. E.g., [(1,), (2,)] => [1, 2]
if elts.len() == 1 {
return;
}
elts.iter().map(helpers::function_name).collect()
}
_ => return,
};
if elt_id != target_id {

if !elt_ids
.iter()
.zip_longest(target_ids.iter())
.all(|e| match e {
EitherOrBoth::Both(&Some(e), &Some(t)) => e == t,
_ => false,
})
{
return;
}

let id = match &expr.node {
ExprKind::ListComp { .. } => "list",
ExprKind::SetComp { .. } => "set",
ExprKind::DictComp { .. } => "dict",
_ => return,
};
if !checker.ctx.is_builtin(id) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@ expression: diagnostics
suggestion: "Rewrite using `list()`"
fixable: true
location:
row: 2
row: 6
column: 0
end_location:
row: 2
row: 6
column: 14
fix:
content: list(x)
location:
row: 2
row: 6
column: 0
end_location:
row: 2
row: 6
column: 14
parent: ~
- kind:
Expand All @@ -28,18 +28,58 @@ expression: diagnostics
suggestion: "Rewrite using `set()`"
fixable: true
location:
row: 3
row: 7
column: 0
end_location:
row: 3
row: 7
column: 14
fix:
content: set(x)
location:
row: 3
row: 7
column: 0
end_location:
row: 3
row: 7
column: 14
parent: ~
- kind:
name: UnnecessaryComprehension
body: "Unnecessary `dict` comprehension (rewrite using `dict()`)"
suggestion: "Rewrite using `dict()`"
fixable: true
location:
row: 8
column: 0
end_location:
row: 8
column: 20
fix:
content: dict(y)
location:
row: 8
column: 0
end_location:
row: 8
column: 20
parent: ~
- kind:
name: UnnecessaryComprehension
body: "Unnecessary `dict` comprehension (rewrite using `dict()`)"
suggestion: "Rewrite using `dict()`"
fixable: true
location:
row: 9
column: 0
end_location:
row: 9
column: 28
fix:
content: dict(d.items())
location:
row: 9
column: 0
end_location:
row: 9
column: 28
parent: ~