is there a way to do range() with ast.literal_eval?
or another way to ask I suppose is there a literal which will literal_eval to the equivalent of the range function (without sendi开发者_运维问答ng the entire array as a range).
the following
import ast
ast.literal_eval("range(0,3)")
ast.literal_eval("[0, 1, 2, 3][0:3]")
results in:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/usr/lib64/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
while this is possible it converts the entire array to a string then back which is not ideal. I was hoping for something with [0:3] syntax without the initial list.
>>> ast.literal_eval(str(range(0,3)))
[0, 1, 2]
http://docs.python.org/library/ast.html#ast.literal_eval
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
A range (other than an explicitly specified list) is not any of those, so no.
精彩评论