diff options
author | Armin Ronacher <armin.ronacher@active-4.com> | 2009-01-13 11:52:23 (GMT) |
---|---|---|
committer | Armin Ronacher <armin.ronacher@active-4.com> | 2009-01-13 11:52:23 (GMT) |
commit | dd53e114efb3ce52e3ae6f2e334174945327bf3d (patch) | |
tree | f16f2ba592507329e7da0a745516eaa7f567d22a /Lib | |
parent | 2d21d50c10d1041f56d6f089d66a98b2bbf55e12 (diff) | |
download | cpython-dd53e114efb3ce52e3ae6f2e334174945327bf3d.zip cpython-dd53e114efb3ce52e3ae6f2e334174945327bf3d.tar.gz cpython-dd53e114efb3ce52e3ae6f2e334174945327bf3d.tar.bz2 |
ast.literal_eval can properly evaluate complex numbers now. This fixes issue4907.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/ast.py | 12 | ||||
-rw-r--r-- | Lib/test/test_ast.py | 11 |
2 files changed, 23 insertions, 0 deletions
@@ -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) diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py index 00a5aae..994e10b 100644 --- a/Lib/test/test_ast.py +++ b/Lib/test/test_ast.py @@ -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) |