2

Is there a native way of doing safe evaluation of simple Python expressions like those in:

a = ['None', 'False', '0', '0.0', '"s"', '(0,)', '[0,]']

These may for example be provided by HTTP GET like:

http://...?alfa=1&bravo=True&delta=1.0&charlie="s"&echo=None

The result of the evaluation should be Python types like None, bool, int, float, str, etc.

Evaluation using Python eval would be the obvious starting point, but since eval is unsafe, it can't be used directly for evaluating arguments from HTTP GET.

What is a good way to do safe evaluation of simple Python expressions?

EquipDev
  • 5,573
  • 10
  • 37
  • 63
  • Although the duplicated post answers the question as posted, you should really consider using JSON for this usecase instead. JSON parsing happens to be faster as well. – Martijn Pieters Oct 22 '15 at 09:18
  • @IgnacioVazquezAbrams: Thanks for the duplicate reference; [ast.literal_eval(node_or_string)](https://docs.python.org/3/library/ast.html#ast.literal_eval) was exactly what I was looking for. Would like to given you an upvote and correct answer for the duplicate reference ;-) – EquipDev Oct 22 '15 at 09:21
  • @MartijnPieters: Thanks for pointing to JSON; in this case I need it for parsing of HTTP GET arguments, but I see the point in using JSON elsewhere. – EquipDev Oct 22 '15 at 09:21
  • 1
    JSON is perfectly usable in URL query parameters too! :-) `alfa=1&bravo=true&delta=1.0&charlie="s"&echo=null` is the JSON equivalent for just the `application/x-www-form-urlencoded` values, or you could use `{"alfa":1,"bravo":true,"delta":1.0,"charlie":"s","echo":null}` as the query string to go JSON all the way. – Martijn Pieters Oct 22 '15 at 09:29

0 Answers0