Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 2 additions & 0 deletions Lib/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ def _convert(node):
node.func.id == 'set' and node.args == node.keywords == []):
return set()
elif isinstance(node, Dict):
if len(node.keys) != len(node.values):
raise ValueError(f'malformed node or string: {node!r}')
return dict(zip(map(_convert, node.keys),
map(_convert, node.values)))
Copy link
Member

@brandtbucher brandtbucher May 2, 2020

Choose a reason for hiding this comment

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

Collecting node.keys and node.values into lists should be fine:

Suggested change
if len(node.keys) != len(node.values):
raise ValueError(f'malformed node or string: {node!r}')
return dict(zip(map(_convert, node.keys),
map(_convert, node.values)))
keys, values = list(node.keys), list(node.values)
if len(keys) != len(values):
raise ValueError(f'malformed node or string: {node!r}')
return dict(zip(map(_convert, keys),
map(_convert, values)))

elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,12 @@ def test_literal_eval_complex(self):
self.assertRaises(ValueError, ast.literal_eval, '3+(0+6j)')
self.assertRaises(ValueError, ast.literal_eval, '-(3+6j)')

def test_literal_eval_malformed(self):
Copy link
Member

Choose a reason for hiding this comment

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

I find this name is too generic. Maybe test_literal_eval_malformed_dict_nodes ?

malformed = ast.Dict(keys=[ast.Constant(1), ast.Constant(2)], values=[ast.Constant(3)])
self.assertRaises(ValueError, ast.literal_eval, malformed)
malformed = ast.Dict(keys=[ast.Constant(1)], values=[ast.Constant(2), ast.Constant(3)])
self.assertRaises(ValueError, ast.literal_eval, malformed)

def test_bad_integer(self):
# issue13436: Bad error message with invalid numeric values
body = [ast.ImportFrom(module='time',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed case where malformed :class:`ast.Dict` nodes could have keys or values
thrown away by :func:`ast.literal_eval`. Patch by Curtis Bucher.