Kaydet (Commit) dd53e114 authored tarafından Armin Ronacher's avatar Armin Ronacher

ast.literal_eval can properly evaluate complex numbers now. This fixes issue4907.

üst 2d21d50c
......@@ -64,6 +64,18 @@ def literal_eval(node_or_string):
elif isinstance(node, Name):
if node.id in _safe_names:
return _safe_names[node.id]
elif isinstance(node, BinOp) and \
isinstance(node.op, (Add, Sub)) and \
isinstance(node.right, Num) and \
isinstance(node.right.n, complex) and \
isinstance(node.left, Num) and \
isinstance(node.left.n, (int, long, float)):
left = node.left.n
right = node.right.n
if isinstance(node.op, Add):
return left + right
else:
return left - right
raise ValueError('malformed string')
return _convert(node_or_string)
......
......@@ -271,6 +271,17 @@ class ASTHelpers_Test(unittest.TestCase):
self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
self.assertRaises(ValueError, ast.literal_eval, 'foo()')
def test_literal_eval_issue4907(self):
self.assertEqual(ast.literal_eval('2j'), 2j)
self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
try:
ast.literal_eval('2 + (3 + 4j)')
except ValueError:
pass
else:
self.fail('expected value error')
def test_main():
test_support.run_unittest(AST_Tests, ASTHelpers_Test)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment