8000 bpo-40000: Improve error messages when validating invalid ast.Constan… · python/cpython@0ac59f9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 0ac59f9

Browse files
bpo-40000: Improve error messages when validating invalid ast.Constant nodes (GH-19055)
Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
1 parent 50e6e99 commit 0ac59f9

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

Lib/test/test_ast.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,15 @@ def test_invalid_identifier(self):
582582
compile(m, "<test>", "exec")
583583
self.assertIn("identifier must be of type str", str(cm.exception))
584584

585+
def test_invalid_constant(self):
586+
for invalid_constant in int, (1, 2, int), frozenset((1, 2, int)):
587+
e = ast.Expression(body=ast.Constant(invalid_constant))
588+
ast.fix_missing_locations(e)
589+
with self.assertRaisesRegex(
590+
TypeError, "invalid type in Constant: type"
591+
):
592+
compile(e, "<test>", "eval")
593+
585594
def test_empty_yield_from(self):
586595
# Issue 16546: yield from value is not optional.
587596
empty_yield_from = ast.parse("def f():\n yield from g()")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improved error messages for validation of ``ast.Constant`` nodes. Patch by
2+
Batuhan Taskaya.

Python/ast.c

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,11 @@ validate_constant(PyObject *value)
147147
return 1;
148148
}
149149

150+
if (!PyErr_Occurred()) {
151+
PyErr_Format(PyExc_TypeError,
152+
"got an invalid type in Constant: %s",
153+
_PyType_Name(Py_TYPE(value)));
154+
}
150155
return 0;
151156
}
152157

@@ -261,9 +266,6 @@ validate_expr(expr_ty exp, expr_context_ty ctx)
261266
validate_keywords(exp->v.Call.keywords);
262267
case Constant_kind:
263268
if (!validate_constant(exp->v.Constant.value)) {
264-
PyErr_Format(PyExc_TypeError,
265-
"got an invalid type in Constant: %s",
266-
_PyType_Name(Py_TYPE(exp->v.Constant.value)));
267269
return 0;
268270
}
269271
return 1;

0 commit comments

Comments
 (0)
0