8000 [3.12] gh-109114: Relax the check for invalid lambdas inside f-string… · python/cpython@21f4e6d · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 21f4e6d

Browse files
authored
[3.12] gh-109114: Relax the check for invalid lambdas inside f-strings to avoid false positives (GH-109121). (#109155)
(cherry picked from commit 5bda2f6) Signed-off-by: Pablo Galindo <pablogsal@gmail.com>
1 parent 8208657 commit 21f4e6d

File tree

4 files changed

+1257
-1309
lines changed

4 files changed

+1257
-1309
lines changed

Grammar/python.gram

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1170,7 +1170,7 @@ invalid_expression:
11701170
_PyPegen_check_legacy_stmt(p, a) ? NULL : p->tokens[p->mark-1]->level == 0 ? NULL :
11711171
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Perhaps you forgot a comma?") }
11721172
| a=disjunction 'if' b=disjunction !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") }
1173-
| a='lambda' [lambda_params] b=':' &(FSTRING_MIDDLE | fstring_replacement_field) {
1173+
| a='lambda' [lambda_params] b=':' &FSTRING_MIDDLE {
11741174
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "f-string: lambda expressions are not allowed without parentheses") }
11751175

11761176
invalid_named_expression(memo):

Lib/test/test_fstring.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,6 +1027,10 @@ def test_lambda(self):
10271027
"f'{lambda x:}'",
10281028
"f'{lambda :}'",
10291029
])
1030+
# Ensure the detection of invalid lambdas doesn't trigger detection
1031+
# for valid lambdas in the second error pass
1032+
with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
1033+
compile("lambda name_3=f'{name_4}': {name_3}\n1 $ 1", "<string>", "exec")
10301034

10311035
# but don't emit the paren warning in general cases
10321036
with self.assertRaisesRegex(SyntaxError, "f-string: expecting a valid expression after '{'"):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Relax the detection of the error message for invalid lambdas inside
2+
f-strings to not search for arbitrary replacement fields to avoid false
3+
positives. Patch by Pablo Galindo

0 commit comments

Comments
 (0)
0