Skip to content

Commit

Permalink
Limit inplace diagnostics to methods that accept inplace (#9495)
Browse files Browse the repository at this point in the history
## Summary

This should reduce false positives like
#9491, by ignoring methods that
are clearly not on a DataFrame.

Closes #9491.
  • Loading branch information
charliermarsh committed Jan 12, 2024
1 parent 3261d16 commit fee64b5
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
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)


0 comments on commit fee64b5

Please sign in to comment.