0

I have an object of class Employee.

#  For Example
>>> employee1 = Employee()

I need to substitute the object employee1 in below expression. The expression will be dynamic

>>> expr = "object.basic_sal * 0.10 + 500"


For Example,

>>> employee1 = Employee()
>>> employee1.basic_sal = 10000
>>> expr = "object.basic_sal * 0.10 + 500"

>>> eval_expr(object=employee1, expression=expr)
1500

I could not find similar questions.
Please help me.

4
  • and why do you need that? why don't you create a function? Commented Aug 14, 2018 at 8:44
  • I think a function will more suitable. why not using function? Commented Aug 14, 2018 at 8:45
  • The expression will be variable. So I need to write each functions for each cases. I just need like eval() function. Commented Aug 14, 2018 at 8:48
  • So, use eval, at your own risk? Commented Aug 14, 2018 at 8:51

1 Answer 1

0

You can use str.format() to interpolate values into strings:

expr = "{object.basic_sal} * 0.10 + 500".format(object=employee1)

To evaluate the expression you can use the eval() function, although it is not generally recommended because of security risks.

result = eval(expr)
Sign up to request clarification or add additional context in comments.

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.