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

RUF055 ignores backslashes in the repl argument of re.sub #14757

Closed
dscorbett opened this issue Dec 3, 2024 · 3 comments
Closed

RUF055 ignores backslashes in the repl argument of re.sub #14757

dscorbett opened this issue Dec 3, 2024 · 3 comments
Assignees
Labels
bug Something isn't working help wanted Contributions especially welcome

Comments

@dscorbett
Copy link

In Ruff 0.8.1, unnecessary-regular-expression (RUF055) reports a false positive for re.sub when the replacement string contains a backslash.

$ cat ruf055.py
import re
print(re.sub(" ", r"\n", "a b"))

$ python ruf055.py
a
b

$ ruff check --isolated --preview --select RUF055 ruf055.py --fix
Found 1 error (1 fixed, 0 remaining).

$ cat ruf055.py
import re
print("a b".replace(" ", "\\n"))

$ python ruf055.py
a\nb

This issue was mentioned in #14679 (comment) with the example of \g<0>, which was deemed acceptably implausible. Because a replacement string can also include character escapes, this issue is plausible.

Alternatively, this could be considered a true positive, in which case the fix needs to interpret escape sequences in the replacement string.

@MichaReiser
Copy link
Member

Thanks.

Okay, so the part that we overlooked from the specification is:

if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth.

@MichaReiser MichaReiser added bug Something isn't working help wanted Contributions especially welcome labels Dec 3, 2024
@MichaReiser
Copy link
Member

@AlexWaygood pointed out that this could be addressed by #14679

@AlexWaygood
Copy link
Member

Thanks @dscorbett, as ever! You were quite right that #14679 would not have fixed this in its earlier form. I pushed some updates to it, so I think it now handles everything correctly, though. Let us know if you see any other issues with the check!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working help wanted Contributions especially welcome
Projects
None yet
Development

No branches or pull requests

3 participants