You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ast.literal_eval doesn't support the Python ternary operator #68334
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee=Noneclosed_at=<Date2015-05-08.14:25:28.768>created_at=<Date2015-05-08.13:22:43.292>labels= ['type-bug', 'invalid']
title="ast.literal_eval doesn't support the Python ternary operator"updated_at=<Date2015-05-08.14:25:28.766>user='https://github.com/larryhastings'
>>> ast.literal_eval('2*3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/ast.py", line 84, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python3.4/ast.py", line 83, in _convert
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.BinOp object at 0xb6f8446c>
And shouldn't. It supports "+" and "-" only because they are needed for support of complex "literals". It is unintentional side effect, that ast.literal_eval() supports not only "2+3j", but "2+3" too.
Activity
larryhastings commentedon May 8, 2015
ast.literal_eval() supports all Python operators, yes? No. It doesn't support "if/else", Python's ternary operator.
Is there a reason it does not? I think it probably should.
serhiy-storchaka commentedon May 8, 2015
No it doesn't support all Python operators.
>>> ast.literal_eval('2*3') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/ast.py", line 84, in literal_eval return _convert(node_or_string) File "/usr/lib/python3.4/ast.py", line 83, in _convert raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: <_ast.BinOp object at 0xb6f8446c>And shouldn't. It supports "+" and "-" only because they are needed for support of complex "literals". It is unintentional side effect, that ast.literal_eval() supports not only "2+3j", but "2+3" too.
bitdancer commentedon May 8, 2015
Right, this isn't a bug, it is that literal_eval is intended only to support *literals*, not expressions. See also bpo-22525.