Skip to content

Commit fd806a6

Browse files
committed
Canonicalize f-string field spacing in annotations [skip ci]
Ignore incidental source whitespace when unparsing formatted values, retaining the brace-leading-expression safeguard and literal/debug text. Add compile-only Python annotation-constant coverage. Assisted-by: OpenAI Codex:model identifier unavailable
1 parent 06007c8 commit fd806a6

2 files changed

Lines changed: 14 additions & 13 deletions

File tree

‎crates/codegen/src/unparse.rs‎

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -628,19 +628,7 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> {
628628
// put a space to avoid escaping the bracket
629629
"{ "
630630
} else {
631-
// Preserve leading whitespace between '{' and the expression
632-
let source_text = self.source.source_text();
633-
let start = val.range().start().to_usize();
634-
if start > 0
635-
&& source_text
636-
.as_bytes()
637-
.get(start - 1)
638-
.is_some_and(|b| b.is_ascii_whitespace())
639-
{
640-
"{ "
641-
} else {
642-
"{"
643-
}
631+
"{"
644632
};
645633
self.p(brace)?;
646634
self.p(&buffered)?;

‎extra_tests/snippets/syntax_annotations.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
11
from typing import get_type_hints
22

3+
# Future f-string annotations canonicalize fields, not their literal padding.
4+
for formatted, expected in (
5+
("f'{ value }'", "f'{value}'"),
6+
("f'{ value = }'", "f' value = {value!r}'"),
7+
("f'{ value : >8}'", "f'{value: >8}'"),
8+
("f'{ {1, 2} }'", "f'{ {1, 2}}'"),
9+
):
10+
formatted_code = compile(
11+
"from __future__ import annotations\nx: " + formatted, "<test>", "exec"
12+
)
13+
assert expected in formatted_code.co_consts
14+
15+
316
def func(s: str) -> int:
417
return int(s)
518

0 commit comments

Comments
 (0)