Skip to content

Commit 0f161b3

Browse files
bpo-34854: Fix compiling string annotations containing lambdas. (GH-9645)
* Compiling a string annotation containing a lambda with keyword-only argument without default value caused a crash. * Remove the final "*" (it is incorrect syntax) in the representation of lambda without *args and keyword-only arguments when compile from AST. * Improve the representation of lambda without arguments. (cherry picked from commit 2a2940e) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent b0b8f9b commit 0f161b3

File tree

3 files changed

+11
-5
lines changed

3 files changed

+11
-5
lines changed

Lib/test/test_future.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,11 +178,12 @@ def test_annotations(self):
178178
eq('-1')
179179
eq('~int and not v1 ^ 123 + v2 | True')
180180
eq('a + (not b)')
181+
eq('lambda: None')
181182
eq('lambda arg: None')
182183
eq('lambda a=True: a')
183184
eq('lambda a, b, c=True: a')
184185
eq("lambda a, b, c=True, *, d=1 << v2, e='str': a")
185-
eq("lambda a, b, c=True, *vararg, d=v1 << 2, e='str', **kwargs: a + b")
186+
eq("lambda a, b, c=True, *vararg, d, e='str', **kwargs: a + b")
186187
eq('lambda x: lambda y: x + y')
187188
eq('1 if True else 2')
188189
eq('str or None if int or True else str or bytes or None')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed a crash in compiling string annotations containing a lambda with a
2+
keyword-only argument that doesn't have a default value.

Python/ast_unparse.c

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ append_ast_args(_PyUnicodeWriter *writer, arguments_ty args)
212212
}
213213

214214
/* vararg, or bare '*' if no varargs but keyword-only arguments present */
215-
if (args->vararg || args->kwonlyargs) {
215+
if (args->vararg || asdl_seq_LEN(args->kwonlyargs)) {
216216
APPEND_STR_IF_NOT_FIRST(", ");
217217
APPEND_STR("*");
218218
if (args->vararg) {
@@ -229,8 +229,11 @@ append_ast_args(_PyUnicodeWriter *writer, arguments_ty args)
229229

230230
di = i - arg_count + default_count;
231231
if (di >= 0) {
232-
APPEND_STR("=");
233-
APPEND_EXPR((expr_ty)asdl_seq_GET(args->kw_defaults, di), PR_TEST);
232+
expr_ty default_ = (expr_ty)asdl_seq_GET(args->kw_defaults, di);
233+
if (default_) {
234+
APPEND_STR("=");
235+
APPEND_EXPR(default_, PR_TEST);
236+
}
234237
}
235238
}
236239

@@ -248,7 +251,7 @@ static int
248251
append_ast_lambda(_PyUnicodeWriter *writer, expr_ty e, int level)
249252
{
250253
APPEND_STR_IF(level > PR_TEST, "(");
251-
APPEND_STR("lambda ");
254+
APPEND_STR(asdl_seq_LEN(e->v.Lambda.args->args) ? "lambda " : "lambda");
252255
APPEND(args, e->v.Lambda.args);
253256
APPEND_STR(": ");
254257
APPEND_EXPR(e->v.Lambda.body, PR_TEST);

0 commit comments

Comments
 (0)