Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-109114: Relax the check for invalid lambdas inside f-strings to avoid false positives #109121

Merged
merged 1 commit into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion Grammar/python.gram
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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