Limit inplace diagnostics to methods that accept inplace (#9495)

## Summary

This should reduce false positives like
https://github.com/astral-sh/ruff/issues/9491, by ignoring methods that
are clearly not on a DataFrame.

Closes https://github.com/astral-sh/ruff/issues/9491.
This commit is contained in:
Charlie Marsh 2024-01-12 14:12:54 -05:00 committed by GitHub
parent 3261d16e61
commit fee64b52ba
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 49 additions and 0 deletions

View file

@ -31,3 +31,6 @@ import torch
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)

View file

@ -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 {
@ -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"
)
}

View file

@ -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
@ -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)