-
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
Generalize PIE807 to handle dict literals #8608
Merged
charliermarsh
merged 7 commits into
astral-sh:main
from
alanhdu:alan/container-builtins
Nov 13, 2023
Merged
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
56eb170
Generalize PIE807 to include dict literals
alanhdu d4af4f5
Update snpashot tests
alanhdu b630dde
Make PIE807 dict fix preview only
alanhdu 1154cbf
Use an enum
charliermarsh 05930bc
Merge branch 'main' into alan/container-builtins
charliermarsh 0ef31d4
Tweak docs
charliermarsh e14024e
Clippy
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
16 changes: 13 additions & 3 deletions
16
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE807.py
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 |
---|---|---|
@@ -1,27 +1,37 @@ | ||
@dataclass | ||
class Foo: | ||
foo: List[str] = field(default_factory=lambda: []) # PIE807 | ||
bar: Dict[str, int] = field(default_factory=lambda: {}) # PIE807 | ||
|
||
|
||
class FooTable(BaseTable): | ||
bar = fields.ListField(default=lambda: []) # PIE807 | ||
foo = fields.ListField(default=lambda: []) # PIE807 | ||
bar = fields.ListField(default=lambda: {}) # PIE807 | ||
|
||
|
||
class FooTable(BaseTable): | ||
bar = fields.ListField(lambda: []) # PIE807 | ||
foo = fields.ListField(lambda: []) # PIE807 | ||
bar = fields.ListField(default=lambda: {}) # PIE807 | ||
|
||
|
||
@dataclass | ||
class Foo: | ||
foo: List[str] = field(default_factory=list) | ||
bar: Dict[str, int] = field(default_factory=dict) | ||
|
||
|
||
class FooTable(BaseTable): | ||
bar = fields.ListField(list) | ||
foo = fields.ListField(list) | ||
bar = fields.ListField(dict) | ||
|
||
|
||
lambda *args, **kwargs: [] | ||
lambda *args, **kwargs: {} | ||
|
||
lambda *args: [] | ||
lambda *args: {} | ||
|
||
lambda **kwargs: [] | ||
lambda **kwargs: {} | ||
|
||
lambda: {**unwrap} |
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
91 changes: 91 additions & 0 deletions
91
crates/ruff_linter/src/rules/flake8_pie/rules/reimplemented_container_builtin.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,91 @@ | ||
use ruff_python_ast::{self as ast, Expr, ExprLambda}; | ||
|
||
use ruff_diagnostics::{Diagnostic, Edit, Fix}; | ||
use ruff_diagnostics::{FixAvailability, Violation}; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_text_size::Ranged; | ||
|
||
use crate::checkers::ast::Checker; | ||
|
||
/// ## What it does | ||
/// Checks for lambdas that can be replaced with the `list` builtin. | ||
/// If [preview] mode is enabled, then we will also look for lambdas | ||
/// that can be replaced with the `dict` builtin. | ||
/// | ||
/// ## Why is this bad? | ||
/// Using container builtins is more readable. | ||
/// | ||
/// ## Example | ||
/// ```python | ||
/// from dataclasses import dataclass, field | ||
/// | ||
/// | ||
/// @dataclass | ||
/// class Foo: | ||
/// bar: list[int] = field(default_factory=lambda: []) | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// from dataclasses import dataclass, field | ||
/// | ||
/// | ||
/// @dataclass | ||
/// class Foo: | ||
/// bar: list[int] = field(default_factory=list) | ||
/// baz: dict[str, int] = field(default_factory=dict) | ||
/// ``` | ||
/// | ||
/// | ||
/// If [preview] | ||
/// ## References | ||
/// - [Python documentation: `list`](https://docs.python.org/3/library/functions.html#func-list) | ||
/// | ||
/// [preview]: https://docs.astral.sh/ruff/preview/ | ||
#[violation] | ||
pub struct ReimplementedContainerBuiltin(&'static str); | ||
|
||
impl Violation for ReimplementedContainerBuiltin { | ||
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes; | ||
|
||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
format!("Prefer `{}` over useless lambda", self.0) | ||
} | ||
|
||
fn fix_title(&self) -> Option<String> { | ||
Some(format!("Replace with lambda with `{}`", self.0)) | ||
} | ||
} | ||
|
||
/// PIE807 | ||
pub(crate) fn reimplemented_container_builtin(checker: &mut Checker, expr: &ExprLambda) { | ||
let ExprLambda { | ||
parameters, | ||
body, | ||
range: _, | ||
} = expr; | ||
|
||
if parameters.is_none() { | ||
let builtin = match body.as_ref() { | ||
Expr::List(ast::ExprList { elts, .. }) if elts.is_empty() => Some("list"), | ||
Expr::Dict(ast::ExprDict { values, .. }) | ||
if values.is_empty() & checker.settings.preview.is_enabled() => | ||
{ | ||
Some("dict") | ||
} | ||
_ => None, | ||
}; | ||
if let Some(builtin) = builtin { | ||
let mut diagnostic = | ||
Diagnostic::new(ReimplementedContainerBuiltin(builtin), expr.range()); | ||
if checker.semantic().is_builtin(builtin) { | ||
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement( | ||
builtin.to_string(), | ||
expr.range(), | ||
))); | ||
} | ||
checker.diagnostics.push(diagnostic); | ||
} | ||
} | ||
} |
76 changes: 0 additions & 76 deletions
76
crates/ruff_linter/src/rules/flake8_pie/rules/reimplemented_list_builtin.rs
This file was deleted.
Oops, something went wrong.
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
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.
I could make this an
enum
instead, but not sure it's worthwhile compared to just storing the builtin inline.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.
I decided to make it an enum to follow the pattern we use elsewhere, even though it's really unimportant.