Skip to content

Commit db2d8b6

Browse files
authored
gh-122300: Preserve AST nodes for format specifiers with single elements (#122308)
1 parent 7c29218 commit db2d8b6

File tree

4 files changed

+8
-3
lines changed

4 files changed

+8
-3
lines changed

Doc/library/ast.rst

+3-1
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,9 @@ Literals
316316
args=[
317317
Name(id='a', ctx=Load())]),
318318
conversion=-1,
319-
format_spec=Constant(value='.3'))]))
319+
format_spec=JoinedStr(
320+
values=[
321+
Constant(value='.3')]))]))
320322

321323

322324
.. class:: List(elts, ctx)

Lib/test/test_ast.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3638,7 +3638,7 @@ def main():
36383638
('Expression', ('Subscript', (1, 0, 1, 10), ('List', (1, 0, 1, 3), [('Constant', (1, 1, 1, 2), 5, None)], ('Load',)), ('Slice', (1, 4, 1, 9), ('Constant', (1, 4, 1, 5), 1, None), ('Constant', (1, 6, 1, 7), 1, None), ('Constant', (1, 8, 1, 9), 1, None)), ('Load',))),
36393639
('Expression', ('IfExp', (1, 0, 1, 21), ('Name', (1, 9, 1, 10), 'x', ('Load',)), ('Call', (1, 0, 1, 5), ('Name', (1, 0, 1, 3), 'foo', ('Load',)), [], []), ('Call', (1, 16, 1, 21), ('Name', (1, 16, 1, 19), 'bar', ('Load',)), [], []))),
36403640
('Expression', ('JoinedStr', (1, 0, 1, 6), [('FormattedValue', (1, 2, 1, 5), ('Name', (1, 3, 1, 4), 'a', ('Load',)), -1, None)])),
3641-
('Expression', ('JoinedStr', (1, 0, 1, 10), [('FormattedValue', (1, 2, 1, 9), ('Name', (1, 3, 1, 4), 'a', ('Load',)), -1, ('Constant', (1, 5, 1, 8), '.2f', None))])),
3641+
('Expression', ('JoinedStr', (1, 0, 1, 10), [('FormattedValue', (1, 2, 1, 9), ('Name', (1, 3, 1, 4), 'a', ('Load',)), -1, ('JoinedStr', (1, 4, 1, 8), [('Constant', (1, 5, 1, 8), '.2f', None)]))])),
36423642
('Expression', ('JoinedStr', (1, 0, 1, 8), [('FormattedValue', (1, 2, 1, 7), ('Name', (1, 3, 1, 4), 'a', ('Load',)), 114, None)])),
36433643
('Expression', ('JoinedStr', (1, 0, 1, 11), [('Constant', (1, 2, 1, 6), 'foo(', None), ('FormattedValue', (1, 6, 1, 9), ('Name', (1, 7, 1, 8), 'a', ('Load',)), -1, None), ('Constant', (1, 9, 1, 10), ')', None)])),
36443644
]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Preserve AST nodes for f-string with single-element format specifiers. Patch
2+
by Pablo Galindo

Parser/action_helpers.c

+2-1
Original file line numberDiff line numberDiff line change
@@ -1010,7 +1010,8 @@ _PyPegen_setup_full_format_spec(Parser *p, Token *colon, asdl_expr_seq *spec, in
10101010
spec = resized_spec;
10111011
}
10121012
expr_ty res;
1013-
if (asdl_seq_LEN(spec) == 0) {
1013+
Py_ssize_t n = asdl_seq_LEN(spec);
1014+
if (n == 0 || (n == 1 && asdl_seq_GET(spec, 0)->kind == Constant_kind)) {
10141015
res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno,
10151016
end_col_offset, p->arena);
10161017
} else {

0 commit comments

Comments
 (0)