]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-40000: Improve error messages when validating invalid ast.Constant nodes (GH...
authorBatuhan Taşkaya <47358913+isidentical@users.noreply.github.com>
Thu, 19 Mar 2020 11:32:28 +0000 (14:32 +0300)
committerGitHub <noreply@github.com>
Thu, 19 Mar 2020 11:32:28 +0000 (11:32 +0000)
Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
Lib/test/test_ast.py
Misc/NEWS.d/next/Library/2020-03-18-12-54-25.bpo-40000.FnsPZC.rst [new file with mode: 0644]
Python/ast.c

index 66f83841ce3417ffec21c0431bf4abf64de5c603..d072c338d952ec08ba8ef65837be4c76192ceb21 100644 (file)
@@ -582,6 +582,15 @@ class AST_Tests(unittest.TestCase):
             compile(m, "<test>", "exec")
         self.assertIn("identifier must be of type str", str(cm.exception))
 
+    def test_invalid_constant(self):
+        for invalid_constant in int, (1, 2, int), frozenset((1, 2, int)):
+            e = ast.Expression(body=ast.Constant(invalid_constant))
+            ast.fix_missing_locations(e)
+            with self.assertRaisesRegex(
+                TypeError, "invalid type in Constant: type"
+            ):
+                compile(e, "<test>", "eval")
+
     def test_empty_yield_from(self):
         # Issue 16546: yield from value is not optional.
         empty_yield_from = ast.parse("def f():\n yield from g()")
diff --git a/Misc/NEWS.d/next/Library/2020-03-18-12-54-25.bpo-40000.FnsPZC.rst b/Misc/NEWS.d/next/Library/2020-03-18-12-54-25.bpo-40000.FnsPZC.rst
new file mode 100644 (file)
index 0000000..2081697
--- /dev/null
@@ -0,0 +1,2 @@
+Improved error messages for validation of ``ast.Constant`` nodes. Patch by
+Batuhan Taskaya.
index 2e9a8d05f7ea260dfdfb4938f561419c164ab6ae..2b74ed4dbdefd6503c58a162534840a69c7167a7 100644 (file)
@@ -147,6 +147,11 @@ validate_constant(PyObject *value)
         return 1;
     }
 
+    if (!PyErr_Occurred()) {
+        PyErr_Format(PyExc_TypeError,
+                     "got an invalid type in Constant: %s",
+                     _PyType_Name(Py_TYPE(value)));
+    }
     return 0;
 }
 
@@ -261,9 +266,6 @@ validate_expr(expr_ty exp, expr_context_ty ctx)
             validate_keywords(exp->v.Call.keywords);
     case Constant_kind:
         if (!validate_constant(exp->v.Constant.value)) {
-            PyErr_Format(PyExc_TypeError,
-                         "got an invalid type in Constant: %s",
-                         _PyType_Name(Py_TYPE(exp->v.Constant.value)));
             return 0;
         }
         return 1;