0

I am looking for a way to evaluate string syntax that allows for indexing.

Example:

string = '[1,2,3][0]'
foo = literal_eval( string )

In this case, I want foo to equal 1

ast literal_eval does not support this because

It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

The code is untrusted so I cannot use the python eval() function.

Any thoughts?

Jay Ocean
  • 273
  • 1
  • 3
  • 14
  • The `ast` module provides parsing functions. – Barmar Feb 14 '20 at 16:46
  • Can you use a template application such as Jinja2 or do you have to stick with the standard library? – Matt Shin Feb 14 '20 at 17:03
  • I can use a template application - key things are making sure it isn't a security risk with untrusted code. Any thoughts on how to make it happen? – Jay Ocean Feb 14 '20 at 17:10
  • You could write your own parser with [Lark](https://github.com/lark-parser/lark). Or any other parser generator. – Wombatz Feb 14 '20 at 17:42

0 Answers0