Skip to content

Commit 38921b7

Browse files
authored
fix: Preserve nested f-string format specs
PR-486: #486
1 parent b450abb commit 38921b7

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

‎packages/griffelib/src/griffe/_internal/expressions.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -531,10 +531,11 @@ def _iterate_format_parts(
531531
format_spec: Sequence[str | Expr] | None,
532532
*,
533533
flat: bool = True,
534+
separate_braces: bool = True,
534535
) -> Iterator[str | Expr]:
535536
# Shared by `ExprFormatted` and `ExprInterpolation`.
536537
yield "{"
537-
if str(value).startswith("{"):
538+
if separate_braces and str(value).startswith("{"):
538539
# Separate braces, `{{` would be read as an escaped brace, e.g. `f"{ {1: 2}}"`.
539540
yield " "
540541
# Lambdas and walrus assignments need parentheses:
@@ -548,6 +549,16 @@ def _iterate_format_parts(
548549
if isinstance(part, str):
549550
# Literal braces must be doubled, as in literal f-string parts.
550551
yield part.replace("{", "{{").replace("}", "}}")
552+
elif flat and isinstance(part, (ExprFormatted, ExprInterpolation)):
553+
# Nested format fields already have their own braces; adding a separating
554+
# space here changes the JoinedStr shape when their value starts with `{`.
555+
yield from _iterate_format_parts(
556+
part.value,
557+
part.conversion,
558+
part.format_spec,
559+
flat=True,
560+
separate_braces=False,
561+
)
551562
else:
552563
yield from _yield(part, flat=flat, outer_precedence=_OperatorPrecedence.NONE)
553564
yield "}"

‎packages/griffelib/tests/test_expressions.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,16 @@ def test_expressions_stay_valid_and_equivalent(shape: str, context: str) -> None
208208
assert ast.dump(reparsed) == ast.dump(original), f"{code!r} rendered as {rendered!r}"
209209

210210

211+
def test_nested_container_format_spec_is_roundtrip_safe() -> None:
212+
"""Container replacement fields in format specs must preserve the source AST."""
213+
code = "f'{value:{{1, 2}}}'"
214+
original = ast.parse(code, mode="eval")
215+
expression = get_expression(original.body, parent=Module("module"), parse_strings=False)
216+
rendered = str(expression)
217+
reparsed = ast.parse(rendered, mode="eval")
218+
assert ast.dump(reparsed) == ast.dump(original), f"{code!r} rendered as {rendered!r}"
219+
220+
211221
def test_length_one_tuple_as_string() -> None:
212222
"""Length-1 tuples must have a trailing comma."""
213223
code = "x = ('a',)"

0 commit comments

Comments
 (0)