Reputation: 41
How can I pass variables to an eval function?
I have tried some solutions posted here on SO as well as reading through the Python documentation
I have this section of code 'v' which I would like to reuse in another part of my code. Here is a snippet:
v = lambda r5, cdate : somefunc(r4, cdate) + math.exp(-t_3m*r1 - t_6m*r2 - t_1y*r3 - t_2y*r4 - retfrac(d[4], d[5], cdate, eoffset = 730)*r5) + \
math.exp(-t_3m*r1 - t_6m*r2 - t_1y*r3 - t_2y*r4 - t_3y*r5)
I would then like to do something to the likes of:
w = "v(r5, cdate) + math.exp(-t_3m*r1 - t_6m*r2 - t_1y*r3 - t_2y*r4 - t_3y*r5)*(0"
# + some other expressions that I have to build up using a for loop since there is no closed form solution
func = lambda r6, cdate = i[30] : (five_year + (coupon_five_year/2)*(1-(ia_5y/.5))) - (coupon_five_year/2)*(eval(w)) - 100*math.exp(-t_3m*r1 - t_6m*r2 - t_1y*r3 - t_2y*r4 - t_3y*r5 - t_5y*r6)
r6 = fsolve(func, xguess)[0]
When I try to evaluate this, I am getting an error that says:
NameError: name 'v' is not defined
Once I remove v, from the expression for w, I then get a NameError for t_3m and it just waters through all of the variables. Could someone please help me out?
Upvotes: 0
Views: 2014
Reputation: 42143
The eval function accepts two additional parameters to provide it with global and local variables.
You simply need to call it like this: eval(w,globals(),locals())
That's assuming the variable references made in the w string are all in scope when you call eval().
Upvotes: 1