Skip to content

Commit cdd491c

Browse files
committed
gh-102856: Allow comments inside multi-line f-string expresions
1 parent 00e2c59 commit cdd491c

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

Lib/test/test_fstring.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,40 @@ def test_comments(self):
653653
["f'{)#}'", # When wrapped in parens, this becomes
654654
# '()#)'. Make sure that doesn't compile.
655655
])
656+
self.assertEqual(f'''A complex trick: {
657+
2 # two
658+
}''', 'A complex trick: 2')
659+
self.assertEqual(f'''
660+
{
661+
40 # fourty
662+
+ # plus
663+
2 # two
664+
}''', '\n42')
665+
self.assertEqual(f'''
666+
{
667+
40 # fourty
668+
+ # plus
669+
2 # two
670+
}''', '\n42')
671+
672+
self.assertEqual(f'''
673+
# this is not a comment
674+
{ # the following operation it's
675+
3 # this is a number
676+
* 2}''', '\n# this is not a comment\n6')
677+
self.assertEqual(f'''
678+
{# f'a {comment}'
679+
86 # constant
680+
# nothing more
681+
}''', '\n86')
682+
683+
self.assertAllRaise(SyntaxError, r"f-string: valid expression required before '}'",
684+
["""f'''
685+
{
686+
# only a comment
687+
}'''
688+
""", # this is equivalent to f'{}'
689+
])
656690

657691
def test_many_expressions(self):
658692
# Create a string with many expressions in it. Note that

Parser/tokenizer.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1793,7 +1793,9 @@ tok_get_normal_mode(struct tok_state *tok, tokenizer_mode* current_tok, struct t
17931793
/* Skip comment, unless it's a type comment */
17941794
if (c == '#') {
17951795

1796-
if (INSIDE_FSTRING(tok)) {
1796+
// We don't allow # inside a one-line f-string expr,
1797+
// but we do in multi-line f-string expr
1798+
if (INSIDE_FSTRING(tok) && (tok->lineno == 1)) {
17971799
return MAKE_TOKEN(syntaxerror(tok, "f-string expression part cannot include '#'"));
17981800
}
17991801

0 commit comments

Comments
 (0)