8000 gh-102856: Allow comments inside multi-line f-string expresions (#104… · python/cpython@0a77960 · GitHub
[go: up one dir, main page]

Skip to content

Commit 0a77960

Browse files
authored
gh-102856: Allow comments inside multi-line f-string expresions (#104006)
1 parent 9bc80da commit 0a77960

File tree

2 files changed

+38
-7
lines changed

2 files changed

+38
-7
lines changed

Lib/test/test_fstring.py

+38-3
Original file line numberDiff line numberDiff line change
@@ -661,15 +661,50 @@ def test_comments(self):
661661
self.assertEqual(f'{"#"}', '#')
662662
self.assertEqual(f'{d["#"]}', 'hash')
663663

664-
self.assertAllRaise(SyntaxError, "f-string expression part cannot include '#'",
665-
["f'{1#}'", # error because the expression becomes "(1#)"
666-
"f'{3(#)}'",
664+
self.assertAllRaise(SyntaxError, "'{' was never closed",
665+
["f'{1#}'", # error because everything after '#' is a comment
667666
"f'{#}'",
667+
"f'one: {1#}'",
668+
"f'{1# one} {2 this is a comment still#}'",
668669
])
669670
self.assertAllRaise(SyntaxError, r"f-string: unmatched '\)'",
670671
["f'{)#}'", # When wrapped in parens, this becomes
671672
# '()#)'. Make sure that doesn't compile.
672673
])
674+
self.assertEqual(f'''A complex trick: {
675+
2 # two
676+
}''', 'A complex trick: 2')
677+
self.assertEqual(f'''
678+
{
679+
40 # fourty
680+
+ # plus
681+
2 # two
682+
}''', '\n42')
683+
self.assertEqual(f'''
684+
{
685+
40 # fourty
686+
+ # plus
687+
2 # two
688+
}''', '\n42')
689+
690+
self.assertEqual(f'''
691+
# this is not a comment
692+
{ # the following operation it's
693+
3 # this is a number
694+
* 2}''', '\n# this is not a comment\n6')
695+
self.assertEqual(f'''
696+
{# f'a {comment}'
697+
86 # constant
698+
# nothing more
699+
}''', '\n86')
700+
701+
self.assertAllRaise(SyntaxError, r"f-string: valid expression required before '}'",
702+
["""f'''
703+
{
704+
# only a comment
705+
}'''
706+
""", # this is equivalent to f'{}'
707+
])
673708

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

Parser/tokenizer.c

-4
Original file line numberDiff line numberDiff line change
@@ -1818,10 +1818,6 @@ tok_get_normal_mode(struct tok_state *tok, tokenizer_mode* current_tok, struct t
18181818
/* Skip comment, unless it's a type comment */
18191819
if (c == '#') {
18201820

1821-
if (INSIDE_FSTRING(tok)) {
1822-
return MAKE_TOKEN(syntaxerror(tok, "f-string expression part cannot include '#'"));
1823-
}
1824-
18251821
const char* p = NULL;
18261822
const char *prefix, *type_start;
18271823
int current_starting_col_offset;

0 commit comments

Comments
 (0)
0