Eval Problem

J. Clifford Dyer jcd at sdf.lonestar.org
Mon Apr 6 18:37:28 EDT 2009


On Mon, 2009-04-06 at 15:11 -0400, Victor Subervi wrote:
> Hi:
> I have this code:
> 
> x = 1
> while x <= bitties:
>   file = open(p + str(x) + ".txt")
>   for line in file:
>     print line
>   print eval(bits[x - 1])
>   x += 1
> 
> which throws this error:
> 
> [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221]
> PythonHandler mod_python.cgihandler: Traceback (most recent call
> last): 
> [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221]
> PythonHandler mod_python.cgihandler: File
> "/usr/lib64/python2.4/site-packages/mod_python/apache.py", line 299,
> in HandlerDispatch\n result = object(req) 
> [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221]
> PythonHandler mod_python.cgihandler: File
> "/usr/lib64/python2.4/site-packages/mod_python/cgihandler.py", line
> 96, in handler\n imp.load_module(module_name, fd, path, desc) 
> [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221]
> PythonHandler mod_python.cgihandler: File
> "/var/www/vhosts/articles.13gems.com/httpdocs/index_frame.py", line
> 89, in ?\n print eval(bits[1]) 
> [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221]
> PythonHandler mod_python.cgihandler: File "<string>", line 1 
> [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221]
> PythonHandler mod_python.cgihandler: tableBottom(348,180) 
> [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221]
> PythonHandler mod_python.cgihandler: ^ 
> [Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221]
> PythonHandler mod_python.cgihandler: SyntaxError: invalid syntax
> 

Hmm.  That's not the problem I get.  For me, your code raises:
"NameError: name 'bitties' is not defined"

It's easier for us to help you if you present a self-contained piece of
code that exhibits the problem you've encountered.  Creating that code
will often reveal the problem with the original code, and you will have
solved your own problem.

The other problem with your code is that you are using eval.  Eval leads
to difficult-to-debug errors, and is usually unnecessary, given the
dynamic nature of python.  If you need to access a class method using a
string, you can use getattr.  If you need to dynamically select a
function based on some condition known in another variable, you can use
a dictionary to hash into the function.  

It's hard to say what might be appropriate for your situation, because
your code fragment is so... fragmentary.

Cheers,
Cliff





More information about the Python-list mailing list