Skip to content

Prefer f-strings and non-printf-style format#2122

Merged
mhammond merged 2 commits intomhammond:mainfrom
Avasam:Prefer-non-printf-format
Nov 1, 2023
Merged

Prefer f-strings and non-printf-style format#2122
mhammond merged 2 commits intomhammond:mainfrom
Avasam:Prefer-non-printf-format

Conversation

@Avasam
Copy link
Copy Markdown
Collaborator

@Avasam Avasam commented Sep 21, 2023

From #2100 (comment)
Prefer "f-strings" (f"{str}") > str.format("") > "printf-style" ("%s" % str)

Due to the sheer number of changes (994), I'm keeping this PR to automated changes only. Ran using ruff . --select=UP030,UP031,UP032 --exclude=Pythonwin/Scintilla --exclude=adodbapi --fix then black . (Ruff re-implements pyupgrade and is configurable)
Ruff explicitly won't make a change if it can't ensure the type of the format value (ie, is it a tuple or a string?) or if the argument count doesn't match. This leaves 580 instances of printf-style format in non-adodbapi and non Scintilla-vendored code.

https://docs.astral.sh/ruff/rules/format-literals/#why-is-this-bad

In Python 3.1 and later, format strings can use implicit positional references. For example, "{0}, {1}".format("Hello", "World") can be rewritten as "{}, {}".format("Hello", "World").
If the positional indices appear exactly in-order, they can be omitted in favor of automatic indices to improve readability.

https://docs.astral.sh/ruff/rules/printf-string-formatting/#why-is-this-bad

printf-style string formatting has a number of quirks, and leads to less readable code than using str.format calls or f-strings. In general, prefer the newer str.format and f-strings constructs over printf-style string formatting.

https://docs.astral.sh/ruff/rules/f-string/#why-is-this-bad

f-strings are more readable and generally preferred over str.format calls.

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

Note The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants