Skip to content

Commit efa8ac1

Browse files
committed
Merge branch 'main' of github.com:mkdocstrings/griffe
2 parents 092ac31 + 38921b7 commit efa8ac1

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
@@ -539,10 +539,11 @@ def _iterate_format_parts(
539539
format_spec: Sequence[str | Expr] | None,
540540
*,
541541
flat: bool = True,
542+
separate_braces: bool = True,
542543
) -> Iterator[str | Expr]:
543544
# Shared by `ExprFormatted` and `ExprInterpolation`.
544545
yield "{"
545-
if str(value).startswith("{"):
546+
if separate_braces and str(value).startswith("{"):
546547
# Separate braces, `{{` would be read as an escaped brace, e.g. `f"{ {1: 2}}"`.
547548
yield " "
548549
# Lambdas and walrus assignments need parentheses:
@@ -556,6 +557,16 @@ def _iterate_format_parts(
556557
if isinstance(part, str):
557558
# Literal braces must be doubled, as in literal f-string parts.
558559
yield part.replace("{", "{{").replace("}", "}}")
560+
elif flat and isinstance(part, (ExprFormatted, ExprInterpolation)):
561+
# Nested format fields already have their own braces; adding a separating
562+
# space here changes the JoinedStr shape when their value starts with `{`.
563+
yield from _iterate_format_parts(
564+
part.value,
565+
part.conversion,
566+
part.format_spec,
567+
flat=True,
568+
separate_braces=False,
569+
)
559570
else:
560571
yield from _yield(part, flat=flat, outer_precedence=_OperatorPrecedence.NONE)
561572
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)