-
-
Notifications
You must be signed in to change notification settings - Fork 28
Description
pyproject-fmt
currently provides an opinionated format but lacks an option to enforce a consistent quote style for strings. While TOML's syntax allows for both single and double quotes, development teams often prefer a single, consistent style across their project configuration.
This feature request proposes adding a configuration option to automatically format TOML strings to a preferred quote style, while correctly handling the semantic differences between them to ensure the string's value is never altered.
Proposed Configuration and Behavior
A new quote_style
option should be added to the [tool.pyproject-fmt]
table.
Configuration Example:
[tool.pyproject-fmt]
quote_style = "single" # or "double"
The formatting logic must correctly handle the two types of TOML strings:
- Literal Strings (
'...'
): All content is taken as-is. Backslashes have no special meaning. - Basic Strings (
"..."
): Support escape sequences (e.g.,\n
for a newline,\\
for a literal backslash).
The conversion rules should be as follows:
1. When quote_style = "double"
:
This option will convert all single-quoted literal strings to double-quoted basic strings. This transformation is always possible, provided that special characters are correctly escaped.
- Rule: When converting from
'...'
to"..."
, any backslashes (\
) and double quotes ("
) within the string must be escaped. - Example 1:
'hello'
becomes"hello"
. - Example 2:
'path\to\file'
must become"path\\to\\file"
to preserve the literal backslashes. - Example 3:
'this contains "quotes"'
must become"this contains \"quotes\""
.
2. When quote_style = "single"
:
This option will convert double-quoted basic strings to single-quoted literal strings, but only when it is safe to do so without changing the string's value.
- Rule: Convert from
"..."
to'...'
if, and only if, the string's content meets both of these conditions:- It does not contain any single quotes (
'
). - It does not contain any escape sequences (like
\n
,\t
,\uXXXX
) that would be interpreted differently in a literal string. A string like"a\\b"
(representinga\b
) can be safely converted, but"a\nb"
(representing a newline) cannot.
- It does not contain any single quotes (
- If a string cannot be safely converted, it must remain double-quoted to preserve its semantic value.
- Example 1:
"hello"
becomes'hello'
. - Example 2:
"don't change"
remains"don't change"
because it contains a single quote. - Example 3:
"line1\nline2"
remains"line1\nline2"
because its value depends on interpreting the\n
escape sequence.
Implementing this feature would significantly improve pyproject-fmt
's utility for projects with strict style guides, allowing for stylistic consistency without compromising the correctness of the TOML file.