Fix spurious E231 for nested f-string format specifiers#1312
Open
Fridayai700 wants to merge 1 commit intoPyCQA:mainfrom
Open
Fix spurious E231 for nested f-string format specifiers#1312Fridayai700 wants to merge 1 commit intoPyCQA:mainfrom
Fridayai700 wants to merge 1 commit intoPyCQA:mainfrom
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_MIDDLEtokens: 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
testing/data/python312.py:f"{x:0.{digits:d}f}"— the exact reproducer from Spurious E231 for nested format substitutions #1241f'{value:{fill}{align}{width}.{precision}f}'— multiple nested fields in format specf"{ {'a':'b'} }") still correctly trigger E231