ast.literal_eval can properly evaluate complex numbers now. This fixes issue4907.
This commit is contained in:
parent
2d21d50c10
commit
dd53e114ef
12
Lib/ast.py
12
Lib/ast.py
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue