Skip to content

Commit

Permalink
pythongh-109114: Relax the check for invalid lambdas inside f-strings…
Browse files Browse the repository at this point in the history
… to avoid false positives

Signed-off-by: Pablo Galindo <pablogsal@gmail.com>
  • Loading branch information
pablogsal committed Sep 8, 2023
1 parent b9831e5 commit f1b967d
Show file tree
Hide file tree
Showing 4 changed files with 1,257 additions and 1,309 deletions.
2 changes: 1 addition & 1 deletion Grammar/python.gram
Expand Up @@ -1170,7 +1170,7 @@ invalid_expression:
_PyPegen_check_legacy_stmt(p, a) ? NULL : p->tokens[p->mark-1]->level == 0 ? NULL :
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "invalid syntax. Perhaps you forgot a comma?") }
| a=disjunction 'if' b=disjunction !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") }
| a='lambda' [lambda_params] b=':' &(FSTRING_MIDDLE | fstring_replacement_field) {
| a='lambda' [lambda_params] b=':' &FSTRING_MIDDLE {
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "f-string: lambda expressions are not allowed without parentheses") }

invalid_named_expression(memo):
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/test_fstring.py
Expand Up @@ -1027,6 +1027,10 @@ def test_lambda(self):
"f'{lambda x:}'",
"f'{lambda :}'",
])
# Ensure the detection of invalid lambdas doesn't trigger detection
# for valid lambdas in the second error pass
with self.assertRaisesRegex(SyntaxError, "invalid syntax"):
compile("lambda name_3=f'{name_4}': {name_3}\n1 $ 1", "<string>", "exec")

# but don't emit the paren warning in general cases
with self.assertRaisesRegex(SyntaxError, "f-string: expecting a valid expression after '{'"):
Expand Down
@@ -0,0 +1,3 @@
Relax the detection of the error message for invalid lambdas inside
f-strings to not search for arbitrary replacement fields to avoid false
positives. Patch by Pablo Galindo

0 comments on commit f1b967d

Please sign in to comment.