Skip to content

Fix spurious E231 for nested f-string format specifiers#1312

Open
Fridayai700 wants to merge 1 commit intoPyCQA:mainfrom
Fridayai700:fix-e231-nested-fstring-format
Open

Fix spurious E231 for nested f-string format specifiers#1312
Fridayai700 wants to merge 1 commit intoPyCQA:mainfrom
Fridayai700:fix-e231-nested-fstring-format

Conversation

@Fridayai700
Copy link

Summary

Fixes #1241. When a replacement field appears inside an f-string format spec (e.g. f"{x:0.{digits:d}f}"), the : in the nested {digits:d} is a format specifier colon, not a dict colon. Previously pycodestyle reported a false-positive E231 on it.

The fix tracks FSTRING_MIDDLE / TSTRING_MIDDLE tokens: when { is opened immediately after one of these tokens, it is a nested replacement field inside a format spec. A distinct marker 'F' (instead of '{') is pushed onto the brace stack, and E231 is suppressed for : when the top of the stack is 'F'.

Test plan

  • Added two test cases to testing/data/python312.py:
  • Verified dict colons inside f-strings (f"{ {'a':'b'} }") still correctly trigger E231
  • All 770 existing tests pass

When a replacement field appears inside an f-string format spec
(e.g. `f"{x:0.{digits:d}f}"`), the `:` in the nested `{digits:d}` is a
format specifier, not a dict colon.  Previously pycodestyle reported a
false-positive E231 on it because the brace-stack pattern `['f', '{']`
only matched the top-level replacement field.

Track `FSTRING_MIDDLE` / `TSTRING_MIDDLE` tokens: when `{` is opened
immediately after one of these tokens it is a nested replacement field
inside a format spec.  Push `'F'` (instead of `'{'`) onto the brace
stack, then suppress E231 for `:` when the top of the stack is `'F'`.

Fixes PyCQA#1241.
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.

Spurious E231 for nested format substitutions

1 participant

Comments