summaryrefslogtreecommitdiffstats
path: root/Lib/ast.py
diff options
context:
space:
mode:
authorCurtis Bucher <cpbucher5@gmail.com>2020-05-05 19:40:56 (GMT)
committerGitHub <noreply@github.com>2020-05-05 19:40:56 (GMT)
commitc21c51235aa8061da6b0593d6f857f42fd92fd8b (patch)
treebbac12bdb68cdaa5d3317cd6de8e2e47d2724c83 /Lib/ast.py
parentfb2c7c4afbab0514352ab0246b0c0cc85d1bba53 (diff)
downloadcpython-c21c51235aa8061da6b0593d6f857f42fd92fd8b.zip
cpython-c21c51235aa8061da6b0593d6f857f42fd92fd8b.tar.gz
cpython-c21c51235aa8061da6b0593d6f857f42fd92fd8b.tar.bz2
bpo-40355: Improve error messages in ast.literal_eval with malformed Dict nodes (GH-19868)
Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
Diffstat (limited to 'Lib/ast.py')
-rw-r--r--Lib/ast.py11
1 files changed, 7 insertions, 4 deletions
diff --git a/Lib/ast.py b/Lib/ast.py
index 5c68c4a..7a43581 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -62,11 +62,12 @@ 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):
- if isinstance(node, Constant):
- if type(node.value) in (int, float, complex):
- return node.value
- raise ValueError('malformed node or string: ' + repr(node))
+ if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
+ _raise_malformed_node(node)
+ return node.value
def _convert_signed_num(node):
if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
operand = _convert_num(node.operand)
@@ -88,6 +89,8 @@ def literal_eval(node_or_string):
node.func.id == 'set' and node.args == node.keywords == []):
return set()
elif isinstance(node, Dict):
+ if len(node.keys) != len(node.values):
+ _raise_malformed_node(node)
return dict(zip(map(_convert, node.keys),
map(_convert, node.values)))
elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):