Reputation: 14355
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....
Upvotes: 0
Views: 1407
Reputation: 304355
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)
Upvotes: 2
Reputation: 13191
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'
Upvotes: 1
Reputation: 6260
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)
Upvotes: 1