Question

my situation is as follows:

  1. I have a large table like object which is accessed with a string key and integer index; i.e. lookup is like this: value = table.get("Key", index) .
  2. I would like to give the user the opportunity to enter an arbitrary algebraic expression involving the string keys. The code code should then iterate over the second index and evaluate the expression repeatedly.

So for user input like this: "KeyA + 2*math.abs(KeyC)" I would like to run python code resembling:

for index in index_list:
    answer = table.get("KeyA", index) + 2*math.abs(table.get("Keyc",index))

I guess can parse the expression using one of the Python Parser libraries I found on the internet, but it is not by any means clear to me how actually "run" the parsed code. Any suggestions?

Was it helpful?

Solution

If your end users can enter variables in figure brackets, {..}, you can use str.format to format your string

>>> expression = '{a}*{b}'
>>> values = {'a': 10, 'b': 20, 'c': 30} 
>>> expression.format(**values)
'10*20'

Here values dictionary might be filled with table.get for all keys found in expression, for example with a regular expression:

>>> import re
>>> regexp = re.compile('{(.*?)}')
>>> keys = regexp.findall(expression)
>>> keys
['a', 'b']
>>> table_get = lambda *x: np.random.randint(5)
>>> values = {k: table_get(k) for k in keys}
>>> expression.format(**values)
'1*4'

Then you can refer to Safe way to parse user-supplied mathematical formula in Python for safe expression parsing and evaluation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top