[Tutor] Parsing and evaluating user input

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Jan 9 12:52:36 CET 2013


On 9 January 2013 11:20, Timo <timomlists at gmail.com> wrote:
> I'm having trouble finding a safe way to parse and evaluate user input in my
> program.
>
> In my app, I'm using a calculation like this:
>   (a / b) * 100
> The user should be able to override this and their preference is stored in a
> configuration file for later use. So I now have a string with the user
> defined calculation template, for example:
>
>>>> config.get('custom-calc')
> '(a * b) / 10'
>
> I could tell the user the values should be entered like %(a)s and %(b)s
> which makes parsing easier I think, because I can do this:
>>>> custom_calc = config.get('custom-calc')
>>>> custom_calc
> '(%(a)s * %(b)s) / 10'
>>>> calc_str = custom_calc % {'a': get_value_a(), 'b': get_value_b()}

I don't think this '%(x)' part is really necessary. If you can parse
the arithmetic expression and compute the result, then it's easy
enough to subsitute variable names for values after parsing the
string. However, this is a big if.

>
> I should parse this, fill in the values which the program has at that point
> and calculate the outcome. What is the safest way?

A very similar question was recently asked on the python-list mailing list:
https://mail.python.org/pipermail/python-list/2013-January/637869.html

Currently there is no really safe way to do it using the standard
library but there are a number of suggestions in that thread.

My own suggestion in that thread was to use the third-party numexpr module:

>>> import numexpr
>>> int(numexpr.evaluate('(a * b) / 10', {'a':20, 'b':30}))
60

http://code.google.com/p/numexpr/


Oscar


More information about the Tutor mailing list