Reputation: 2814
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.
Upvotes: 0
Views: 144
Reputation: 149823
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)
Upvotes: 0