eval() woes

rdrink rdrink at artic.edu
Sun Aug 27 23:32:34 EDT 2006


 n.n.h. (noob needs help)
Ok, I've been beating my head against this for a day... time to ask
others.
To explain things as simply as possible:
I am trying to use eval() to evaluate some simple equations, such as--
pow(AB,2)
pow(AB,2)+A
pow(A+B,2)
pow(A+B,2)+A
and so forth... for a variety of math operations (+,-,*) and a variety
of variables, all of which have been genrated by a script,  written to
a .txt file., then recalled sequentially and passed to eval().

The variables (A,B,C,D) are generated elsewhere [Note: AB is a concat,
e.g. A=2,B=7,AB=27] , so both are passed into a function e.g.
def (equation, list):
   A=list[0]
   B=list[1]
   ...etc.
   return eval(str(equation))
Where 'equation' is one of the above, selected from the "equations
file"

So here's the rub:
With the above examples everything works fine... up to the last
(pow(A+B,2)+A), then it bombs with:
ValueError: invalid literal for int(): -
And I have tried 'hard typing' the vars e.g. A=str(list[0]) and
A=int(str(list[0]))... which only leads to it breaking in the other
expressions.
I have also tried 'compile()', which bombs the same way, and have also
looked at 'pickle' (but I don't think I really need to go that far)...

All of which leaves me wondering... Could it simply be that eval()
can't handle the progressive order of math operations?  Because
pow(AB,2) + A works, as does pow(A+B,2)... but then adding pow(A+B,2)+A
(the result, *plus* A) doesn't?
Or is the problem deeper (like at the dictionary level)?

Either way I'm stumped, and could use some help.
Thanks
Robb Drinkwater




More information about the Python-list mailing list