How to eval list indices in a safe way?

  abstract-syntax-tree, eval, indexing, list, python

I try to evaluate some Python expressions like [1, 2, 3][1]. I can’t use eval('[1, 2, 3][1]') because every time I do that, a kitten might die. A safer way is to use ast.literal_eval('[1, 2, 3][1]'), however, it raises a ValueError:

ValueError: malformed node or string ...

What can be done in order to make it work? Thanks in advance.

Source: Python Questions

LEAVE A COMMENT