diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py index e18dff6c3b24b5..8039ccca262262 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -467,7 +467,7 @@ def test_compile_invalid_namedexpr(self): type_ignores=[], ) - with self.assertRaises(SyntaxError): + with self.assertRaisesRegex(ValueError, "NamedExpr target must be a Name"): compile(ast.fix_missing_locations(m), "", "exec") def test_compile_ast(self): diff --git a/Python/ast.c b/Python/ast.c index 21cb38f8cbfb65..9ae03e5b75c953 100644 --- a/Python/ast.c +++ b/Python/ast.c @@ -381,6 +381,11 @@ validate_expr(struct validator *state, expr_ty exp, expr_context_ty ctx) ret = validate_exprs(state, exp->v.Tuple.elts, ctx, 0); break; case NamedExpr_kind: + if (exp->v.NamedExpr.target->kind != Name_kind) { + PyErr_SetString(PyExc_ValueError, + "NamedExpr target must be a Name"); + return 0; + } ret = validate_expr(state, exp->v.NamedExpr.value, Load); break; /* This last case doesn't have any checking. */ diff --git a/Python/symtable.c b/Python/symtable.c index cebf01f7f4417a..d737c09203d31b 100644 --- a/Python/symtable.c +++ b/Python/symtable.c @@ -1869,10 +1869,7 @@ static int symtable_extend_namedexpr_scope(struct symtable *st, expr_ty e) { assert(st->st_stack); - if (e->kind != Name_kind) { - PyErr_SetString(PyExc_SyntaxError, ":= target must be a Name"); - VISIT_QUIT(st, 0); - } + assert(e->kind == Name_kind); PyObject *target_name = e->v.Name.id; Py_ssize_t i, size;