]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-28964: add line number of node (if available) to ast.literal_eval error messages...
authorIrit Katriel <iritkatriel@yahoo.com>
Fri, 25 Dec 2020 17:04:31 +0000 (17:04 +0000)
committerGitHub <noreply@github.com>
Fri, 25 Dec 2020 17:04:31 +0000 (20:04 +0300)
Lib/ast.py
Lib/test/test_ast.py
Misc/NEWS.d/next/Library/2020-12-07-13-21-00.bpo-28964.UTQikc.rst [new file with mode: 0644]

index 7275fe28ba812658cda1c882ed954434ddcf3f8f..845c80c2bbc0d82a6d307261e2161e50d64a9621 100644 (file)
@@ -63,7 +63,10 @@ def literal_eval(node_or_string):
     if isinstance(node_or_string, Expression):
         node_or_string = node_or_string.body
     def _raise_malformed_node(node):
-        raise ValueError(f'malformed node or string: {node!r}')
+        msg = "malformed node or string"
+        if lno := getattr(node, 'lineno', None):
+            msg += f' on line {lno}'
+        raise ValueError(msg + f': {node!r}')
     def _convert_num(node):
         if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
             _raise_malformed_node(node)
index be4b0f78ce9053e69cf280eb2aeb74cf05ed6453..451f40d1f884d73b0d9a970bc3370fdb6c26dfd9 100644 (file)
@@ -1011,6 +1011,18 @@ Module(
         self.assertEqual(ast.literal_eval(" \t -1"), -1)
         self.assertRaises(IndentationError, ast.literal_eval, "\n -1")
 
+    def test_literal_eval_malformed_lineno(self):
+        msg = r'malformed node or string on line 3:'
+        with self.assertRaisesRegex(ValueError, msg):
+            ast.literal_eval("{'a': 1,\n'b':2,\n'c':++3,\n'd':4}")
+
+        node = ast.UnaryOp(
+            ast.UAdd(), ast.UnaryOp(ast.UAdd(), ast.Constant(6)))
+        self.assertIsNone(getattr(node, 'lineno', None))
+        msg = r'malformed node or string:'
+        with self.assertRaisesRegex(ValueError, msg):
+            ast.literal_eval(node)
+
     def test_bad_integer(self):
         # issue13436: Bad error message with invalid numeric values
         body = [ast.ImportFrom(module='time',
diff --git a/Misc/NEWS.d/next/Library/2020-12-07-13-21-00.bpo-28964.UTQikc.rst b/Misc/NEWS.d/next/Library/2020-12-07-13-21-00.bpo-28964.UTQikc.rst
new file mode 100644 (file)
index 0000000..b1be0de
--- /dev/null
@@ -0,0 +1 @@
+:func:`ast.literal_eval` adds line number information (if available) in error message for malformed nodes.
\ No newline at end of file