views:

69

answers:

3

I have list like:

['name','country_id', 'price','rate','discount', 'qty']

and a string expression like

exp = 'qty * price - discount + 100'

I want to convert this expression into

exp = 'obj.qty * obj.price - obj.discount + 100'

as I wanna eval this expression like eval(exp or False, dict(obj=my_obj))

my question is what would be the best way to generate the expression for python eval evaluation....

+2  A: 

Of course you have to be very careful using eval. Would be interesting to know why you need to use eval for this at all

This way makes it harder for something bad to happen if a malicious user finds a way to put non numeric data in the fields

import re
exp = 'qty * price - discount + 100'
exp = re.sub('(qty|price|discount)','%(\\1)f', exp)%vars(obj)
gnibbler
I can use literal eval also, but expression is dynamically entered by end user !
Tumbleweed
@shahjapan: Use `literal_eval` -- that's what it's there for!
katrielalex
+1  A: 

I assume that the list you have is the list of available obj properties.

If it is so, I'd suggest to use regular expressions, like this:

import re

properties = ['name', 'country_id', 'price', 'rate', 'discount', 'qty']
prefix = 'obj'
exp = 'qty * price - discount + 100'

r = re.compile('(' + '|'.join(properties) + ')')
new_exp = r.sub(prefix + r'.\1', exp)
Ihor Kaharlichenko
+1  A: 

The simplest way would be to loop through each of your potential variables, and replace all instances of them in the target string.

keys = ['name','country_id', 'price','rate','discount', 'qty']
exp = 'qty * price - discount + 100'

for key in keys:
    exp = exp.replace(key, '%s.%s' % ('your_object', key))

Output:

'your_object.qty * your_object.price - your_object.discount + 100'
Andrew
It was failed when I have keys like list_price, price, standard_price..... :)
Tumbleweed