I afraid this makes an error message more confusing and misleading.
>>> ast.literal_eval('~2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/serhiy/py/cpython/Lib/ast.py", line 93, in literal_eval
return _convert(node_or_string)
File "/home/serhiy/py/cpython/Lib/ast.py", line 92, in _convert
return _convert_signed_num(node)
File "/home/serhiy/py/cpython/Lib/ast.py", line 65, in _convert_signed_num
return _convert_num(node)
File "/home/serhiy/py/cpython/Lib/ast.py", line 56, in _convert_num
raise ValueError('%s not allowed in literal' % type(node).__name__)
ValueError: UnaryOp not allowed in literal
This is not true since + and - are allowed:
>>> ast.literal_eval('-2')
-2
>>> ast.literal_eval('2+3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/serhiy/py/cpython/Lib/ast.py", line 93, in literal_eval
return _convert(node_or_string)
File "/home/serhiy/py/cpython/Lib/ast.py", line 92, in _convert
return _convert_signed_num(node)
File "/home/serhiy/py/cpython/Lib/ast.py", line 65, in _convert_signed_num
return _convert_num(node)
File "/home/serhiy/py/cpython/Lib/ast.py", line 56, in _convert_num
raise ValueError('%s not allowed in literal' % type(node).__name__)
ValueError: BinOp not allowed in literal
But:
>>> ast.literal_eval('2+3j')
(2+3j)
>>> ast.literal_eval('"a"+"b"')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/serhiy/py/cpython/Lib/ast.py", line 93, in literal_eval
return _convert(node_or_string)
File "/home/serhiy/py/cpython/Lib/ast.py", line 85, in _convert
left = _convert_signed_num(node.left)
File "/home/serhiy/py/cpython/Lib/ast.py", line 65, in _convert_signed_num
return _convert_num(node)
File "/home/serhiy/py/cpython/Lib/ast.py", line 56, in _convert_num
raise ValueError('%s not allowed in literal' % type(node).__name__)
ValueError: Str not allowed in literal
But Str is allowed:
>>> ast.literal_eval('"ab"')
'ab' |