Skip to content

Commit 26ba98e

Browse files
committed
Improve exception message in ast.literal_eval
When a non-literal is given to literal_eval, attempt to be more helpful with the message, rather than calling it 'malformed'.
1 parent 7a1e178 commit 26ba98e

File tree

3 files changed

+5
-1
lines changed

3 files changed

+5
-1
lines changed

Lib/ast.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ def _convert_num(node):
5252
return node.value
5353
elif isinstance(node, Num):
5454
return node.n
55+
elif isinstance(node, AST):
56+
raise ValueError('%s not allowed in literal' % type(node).__name__)
5557
raise ValueError('malformed node or string: ' + repr(node))
5658
def _convert_signed_num(node):
5759
if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):

Lib/test/test_fstring.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ def g():
327327
self.assertIsNone(g.__doc__)
328328

329329
def test_literal_eval(self):
330-
with self.assertRaisesRegex(ValueError, 'malformed node or string'):
330+
with self.assertRaisesRegex(ValueError, 'JoinedStr not allowed in literal'):
331331
ast.literal_eval("f'x'")
332332

333333
def test_ast_compile_time_concat(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve wording of error messages from ast.literal_eval, distinguishing
2+
valid-but-unacceptable nodes from those that are actually malformed.

0 commit comments

Comments
 (0)