[pylint] Fix PLC2801 autofix creating a syntax error (#18857)

<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
-->

## Summary
This PR fixes `PLC2801` autofix creating a syntax error due to lack of
padding if it is directly after a keyword.

Fixes https://github.com/astral-sh/ruff/issues/18813
<!-- What's the purpose of the change? What does it do, and why? -->

## Test Plan
Add regression test
<!-- How was it tested? -->
This commit is contained in:
Victor Hugo Gomes 2025-06-23 11:15:53 -03:00 committed by GitHub
parent ca8ed35275
commit f4c6ff3f68
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 25 additions and 1 deletions

View file

@ -129,3 +129,6 @@ blah = dict[{"a": 1}.__delitem__("a")] # OK
# https://github.com/astral-sh/ruff/issues/14597
assert "abc".__str__() == "abc"
# https://github.com/astral-sh/ruff/issues/18813
three = 1 if 1 else(3.0).__str__()

View file

@ -4,6 +4,7 @@ use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::fix::edits;
use crate::rules::pylint::helpers::is_known_dunder_method;
use crate::{Edit, Fix, FixAvailability, Violation};
use ruff_python_ast::PythonVersion;
@ -232,7 +233,7 @@ pub(crate) fn unnecessary_dunder_call(checker: &Checker, call: &ast::ExprCall) {
}
diagnostic.set_fix(Fix::unsafe_edit(Edit::range_replacement(
fixed,
edits::pad(fixed, call.range(), checker.locator()),
call.range(),
)));
}

View file

@ -1193,6 +1193,8 @@ unnecessary_dunder_call.py:131:8: PLC2801 [*] Unnecessary dunder call to `__str_
130 | # https://github.com/astral-sh/ruff/issues/14597
131 | assert "abc".__str__() == "abc"
| ^^^^^^^^^^^^^^^ PLC2801
132 |
133 | # https://github.com/astral-sh/ruff/issues/18813
|
= help: Use `str()` builtin
@ -1202,3 +1204,21 @@ unnecessary_dunder_call.py:131:8: PLC2801 [*] Unnecessary dunder call to `__str_
130 130 | # https://github.com/astral-sh/ruff/issues/14597
131 |-assert "abc".__str__() == "abc"
131 |+assert str("abc") == "abc"
132 132 |
133 133 | # https://github.com/astral-sh/ruff/issues/18813
134 134 | three = 1 if 1 else(3.0).__str__()
unnecessary_dunder_call.py:134:20: PLC2801 [*] Unnecessary dunder call to `__str__`. Use `str()` builtin.
|
133 | # https://github.com/astral-sh/ruff/issues/18813
134 | three = 1 if 1 else(3.0).__str__()
| ^^^^^^^^^^^^^^^ PLC2801
|
= help: Use `str()` builtin
Unsafe fix
131 131 | assert "abc".__str__() == "abc"
132 132 |
133 133 | # https://github.com/astral-sh/ruff/issues/18813
134 |-three = 1 if 1 else(3.0).__str__()
134 |+three = 1 if 1 else str(3.0)