Skip to content

bpo-32888: enhance ast.literal_eval error messagess with context information #17662

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions Lib/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,20 +62,23 @@ def literal_eval(node_or_string):
node_or_string = parse(node_or_string, mode='eval')
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}')
def _convert_num(node):
def _raise_malformed_node(node, context = None):
message = "malformed node or string"
if context is not None and isinstance(node, AST):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is it necessary to check here that node is an AST and not just that context is not None?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if 'context' is overloaded. Maybe it's better not to add it here to the string passed in, and let the context arg be complete, like "literal expression" or "unary expression arg".

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is it necessary to check here that node is an AST and not just that context is not None?

For malformed nodes (manually constructed), it might not be an AST type, example (already presented in tests);

            ast.BinOp(
                ast.Constant(1), ast.Add(), "oops"
            ): "malformed node or string: 'oops'",

I wonder if 'context' is overloaded. Maybe it's better not to add it here to the string passed in, and let the context arg be complete, like "literal expression" or "unary expression arg".

I am not a native speaker, but from the point of messages, it satisfies the expectations and gives the precise location. (+a => ValueError: malformed node or string in binary operation context: <ast.Name object at 0x7f02f058d5f0>). What would you prefer instead of the message above? By the way thanks for your bump on this old PR! I completely forgot it existed since there was no activity :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • I see about the first point.
  • On the wording - would it work to simply have "malformed binary operation" in this case?
  • My pleasure 👍

message += f" in {context} context"
raise ValueError(f'{message}: {node!r}')
def _convert_num(node, context):
if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
_raise_malformed_node(node)
_raise_malformed_node(node, context)
return node.value
def _convert_signed_num(node):
def _convert_signed_num(node, context):
if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
operand = _convert_num(node.operand)
operand = _convert_num(node.operand, "unary operation")
if isinstance(node.op, UAdd):
return + operand
else:
return - operand
return _convert_num(node)
return _convert_num(node, context)
def _convert(node):
if isinstance(node, Constant):
return node.value
Expand All @@ -90,18 +93,18 @@ def _convert(node):
return set()
elif isinstance(node, Dict):
if len(node.keys) != len(node.values):
_raise_malformed_node(node)
_raise_malformed_node(node, "dictionary")
return dict(zip(map(_convert, node.keys),
map(_convert, node.values)))
elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
left = _convert_signed_num(node.left)
right = _convert_num(node.right)
left = _convert_signed_num(node.left, "binary operation")
right = _convert_num(node.right, "binary operation")
if isinstance(left, (int, float)) and isinstance(right, complex):
if isinstance(node.op, Add):
return left + right
else:
return left - right
return _convert_signed_num(node)
return _convert_signed_num(node, "literal")
return _convert(node_or_string)


Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -971,6 +971,22 @@ def test_literal_eval_malformed_dict_nodes(self):
malformed = ast.Dict(keys=[ast.Constant(1)], values=[ast.Constant(2), ast.Constant(3)])
self.assertRaises(ValueError, ast.literal_eval, malformed)

def test_literal_eval_message(self):
tests = {
"2 * 5": "in literal context",
"[] + []": "in binary operation context",
"+''": "in unary operation context",
ast.Dict(
keys=[ast.Constant(1)], values=[]
): "in dictionary context",
ast.BinOp(
ast.Constant(1), ast.Add(), "oops"
): "malformed node or string: 'oops'",
}
for test, message in tests.items():
with self.subTest(test=test, expected_message=message):
self.assertRaisesRegex(ValueError, message, ast.literal_eval, test)

def test_bad_integer(self):
# issue13436: Bad error message with invalid numeric values
body = [ast.ImportFrom(module='time',
Expand Down
5 changes: 4 additions & 1 deletion Lib/test/test_fstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,10 @@ def g():
self.assertIsNone(g.__doc__)

def test_literal_eval(self):
with self.assertRaisesRegex(ValueError, 'malformed node or string'):
with self.assertRaisesRegex(
ValueError,
'malformed node or string in literal context'
):
ast.literal_eval("f'x'")

def test_ast_compile_time_concat(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Enhance :func:`ast.literal_eval` error messages with context information. Original
patch is written by Chris Angelico, improved and maintained by Batuhan Taskaya.