eval() woes

Simon Forman rogue_pedro at yahoo.com
Mon Aug 28 00:51:44 EDT 2006


rdrink wrote:
> 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

You must be doing something weird,  that equation works for me:

|>> A, B = 2, 7
|>> eq = 'pow(A + B, 2) + A'
|>> eval(eq)
83

Try posting the minimal code example that causes the error and the
full, exact traceback that you get.  (Or even just post the full
traceback that you're getting now, it would probably contain enough
information itself to solve your problem.  And it's a good idea to do
that anyway, post the whole traceback, not just the final line.)

(Also, assuming your equations are already strings, there's no reason
to call str() on them again.  And you mention a "dictionary level" but
don't mention using a dict.)

FWIW, the error "ValueError: invalid literal for int()" occurs when
you, uh, pass an invalid literal to the int() function (actually int
type.. but not important here), and includes the invalid input so you
don't have to guess at it:

|>> int('wombat')

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
    int('wombat')
ValueError: invalid literal for int(): wombat

So, from what's visible in your post, it looks like int is getting
passed a bare '-', i.e. at some point you're calling int('-')...

HTH


Peace,
~Simon




More information about the Python-list mailing list