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

printf-string-formatting (UP031) - fix should f-string instead of str.format #11332

Open
DetachHead opened this issue May 8, 2024 · 7 comments
Labels
fixes Related to suggested fixes for violations

Comments

@DetachHead
Copy link

when both UP031 and UP032 are enabled, the fix for UP031 causes UP032:

foo = "foo"
"%s" % (foo,) # error: UP031

after applying the quick fix:

foo = "foo"
"{}".format(foo) # error: UP032

https://play.ruff.rs/c4a825b4-12e5-4479-9167-c0f4388a17c2

this means i have to apply 2 fixes to get to the correct code. it would be nice if UP031 suggested f strings instead.

@dhruvmanila
Copy link
Member

We iteratively apply fixes until the source code is stable so if you've select both UP031 and UP032, the final diff should be the f-string code:

$ ruff check --unsafe-fixes --fix --no-cache --diff --select=UP031,UP032 src/autofix.py
--- src/autofix.py
+++ src/autofix.py
@@ -1,2 +1,2 @@
 foo = "foo"
-"%s" % (foo,)
+f"{foo}"

Would fix 2 errors.

Can you tell me how are you running ruff?

@DetachHead
Copy link
Author

i meant when applying the quick fix from vscode (or in this case the playground):

image

that only applies one quick fix at a time. IMO, since f strings are the preferred method of interpolating strings, i think UP031's message and fix should be to change it to an f string

@AlexWaygood AlexWaygood added the fixes Related to suggested fixes for violations label May 8, 2024
@dhruvmanila
Copy link
Member

I think astral-sh/ruff-vscode#451 is related.

For this specific case, maybe we could prioritize UP032 if both UP031 and UP032 are enabled similar to what @charliermarsh did in #11173.

@dhruvmanila
Copy link
Member

Oh, but that might not be possible because UP032 isn't triggered until UP031 is fixed.

@charliermarsh
Copy link
Member

Yeah this is roughly by design though I understand why it's not ideal in an editor. IIRC we only support translating % to .format, and .format to f-string.

@autinerd
Copy link
Contributor

autinerd commented May 9, 2024

Maybe it would be a good idea to merge UP031 and UP032. I don't know if ruff has a minimum version, but f-strings exist since Python 3.6 🤔

@Avasam
Copy link

Avasam commented May 31, 2024

@autinerd UP031 and UP032 have different concerns. .format can still be used to avoid very long lines or multiline string concatenation (styling preferences).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fixes Related to suggested fixes for violations
Projects
None yet
Development

No branches or pull requests

6 participants