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

Limit inplace diagnostics to methods that accept inplace #9495

Merged
merged 1 commit into from
Jan 12, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@
torch.m.ReLU(inplace=True) # safe because this isn't a pandas call

(x.drop(["a"], axis=1, inplace=True))

# This method doesn't take exist in Pandas, so ignore it.
x.rotate_z(45, inplace=True)
41 changes: 41 additions & 0 deletions crates/ruff_linter/src/rules/pandas_vet/rules/inplace_argument.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,15 @@ pub(crate) fn inplace_argument(checker: &mut Checker, call: &ast::ExprCall) {
return;
}

// If the function doesn't take an `inplace` argument, abort.
if !call
.func
.as_attribute_expr()
.is_some_and(|func| accepts_inplace_argument(&func.attr))
{
return;
}

let mut seen_star = false;
for keyword in call.arguments.keywords.iter().rev() {
let Some(arg) = &keyword.arg else {
Expand Down Expand Up @@ -134,3 +143,35 @@ fn convert_inplace_argument_to_assignment(

Some(Fix::unsafe_edits(insert_assignment, [remove_argument]))
}

/// Returns `true` if the given method accepts an `inplace` argument when used on a Pandas
/// `DataFrame`, `Series`, or `Index`.
///
/// See: <https://pandas.pydata.org/docs/reference/frame.html>
fn accepts_inplace_argument(method: &str) -> bool {
matches!(
method,
"where"
| "mask"
| "query"
| "clip"
| "eval"
| "backfill"
| "bfill"
| "ffill"
| "fillna"
| "interpolate"
| "dropna"
| "pad"
| "replace"
| "drop"
| "drop_duplicates"
| "rename"
| "rename_axis"
| "reset_index"
| "set_index"
| "sort_values"
| "sort_index"
| "set_names"
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ PD002.py:33:24: PD002 [*] `inplace=True` should be avoided; it has inconsistent
32 |
33 | (x.drop(["a"], axis=1, inplace=True))
| ^^^^^^^^^^^^ PD002
34 |
35 | # This method doesn't take exist in Pandas, so ignore it.
|
= help: Assign to variable; remove `inplace` arg

Expand All @@ -173,5 +175,8 @@ PD002.py:33:24: PD002 [*] `inplace=True` should be avoided; it has inconsistent
32 32 |
33 |-(x.drop(["a"], axis=1, inplace=True))
33 |+x = (x.drop(["a"], axis=1))
34 34 |
35 35 | # This method doesn't take exist in Pandas, so ignore it.
36 36 | x.rotate_z(45, inplace=True)