eval raising SyntaxError (was No Subject)

J. Clifford Dyer jcd at sdf.lonestar.org
Tue Dec 11 20:13:33 EST 2007


On Tue, 2007-12-11 at 16:55 -0800, katie smith wrote:
> I tried your suggestions and all that came up was the error
> Traceback (most recent call last):
>   File "C:\Python25\empire\Empire Strategy.pyw", line 1788, in
> <module>
>     NewMap1= eval (NewMap1, {}, {})
>   File "<string>", line 1
>     Tropical Islands
>                    ^
> SyntaxError: invalid syntax
>  
> And what is this about trusting your source? The string is taken
> exactly from another part in the program so I know for sure it is
> correct if that is what that means.
> 

Katie,

First, please provide a useful subject heading when posting to the list.
It makes everyone's life easier when searching the archives.

Second, the example you provided in your last post was converting a
string of the form "[1,2,3,4,5]" to a list of integers.  What is
happening here, is you are trying to convert a string of the form
"Tropical Islands" to... what?  

I assume you are not getting the string you thought you would get.  Eval
is acting as advertised.  It is taking the line "Tropical Islands" and
trying to parse it as python code.  If that's not what you wanted to do,
the question you should be asking is "why did I get the string "Tropical
Islands" instead of "[1,2,3,4,5]".  You should not be asking "what is
eval doing wrong."

Before you were advised not to use eval unless you were sure of the
source of your inputs.  

If the source of your input is "me," or "trusted operators" then you are
not sure of your inputs, because you might type something in thinking
that the focus was on a different window, or you might mistype
something.  

If the source of your inputs is a line you are extracting from another
python file, you are not sure of your inputs, because there could be an
error in your python file, or someone could add a line, so while
pulling, e.g., line 15 used to give you "[1,2,3,4,5]", that's now line
16, and line 15 gives you "Tropical Islands" instead, because somebody
thought there should be an extra blank line before the start of the code
or something.  

If the source of your inputs is the output of another function, why is
it passing you a repr of a list instead of the list itself.  

Almost NEVER use eval.  If you find yourself using eval, make your next
task figuring out how not to use eval.

Cheers,
Cliff





More information about the Python-list mailing list