summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorIrit Katriel <iritkatriel@yahoo.com>2020-12-25 17:04:31 (GMT)
committerGitHub <noreply@github.com>2020-12-25 17:04:31 (GMT)
commit586f3dbe15139cafb2a6ffb82cea146906561844 (patch)
tree0de5a1236469ee1a791f11d378d2c65e52f45faa /Lib
parentbb70b2afe39ad4334a9f3449cddd28149bd628b6 (diff)
downloadcpython-586f3dbe15139cafb2a6ffb82cea146906561844.zip
cpython-586f3dbe15139cafb2a6ffb82cea146906561844.tar.gz
cpython-586f3dbe15139cafb2a6ffb82cea146906561844.tar.bz2
bpo-28964: add line number of node (if available) to ast.literal_eval error messages (GH-23677)
Diffstat (limited to 'Lib')
-rw-r--r--Lib/ast.py5
-rw-r--r--Lib/test/test_ast.py12
2 files changed, 16 insertions, 1 deletions
diff --git a/Lib/ast.py b/Lib/ast.py
index 7275fe2..845c80c 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -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)
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index be4b0f7..451f40d 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -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',