[Tutor] Parsing and evaluating user input

Timo timomlists at gmail.com
Wed Jan 9 12:20:13 CET 2013


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 should parse this, fill in the values which the program has at that 
point and calculate the outcome. What is the safest way?

Timo


More information about the Tutor mailing list