0

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....

1
  • user input, its being used in dynamic way, where user needs to change their expressions Commented Aug 19, 2010 at 6:38

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I can use literal eval also, but expression is dynamically entered by end user !
@shahjapan: Use literal_eval -- that's what it's there for!
1

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)

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.