eval, exec and execfile dilemma

Laszlo Nagy gandalf at shopzeus.com
Sat Jul 30 15:48:56 EDT 2011


I have a program that generates source code for a function. I need to 
compile that function so that it can be executed (relatively) fast 
later. In most cases, I'll be generating about 10 functions per second, 
and evaluate them frequently. But sometimes I'll have to generate 100 
functions per second (upper limit). I also need to change the dict of 
global variables that are accessible from that function. Here is the 

    * the eval function can only be used to evaluate expressions. The
      source code of the generated function is too complex to be put
      into a lambda expression. The def statement is not handled by
      eval(), so I cannot use eval().
    * the exec statement can be used to execute a def statement.
      However, I see no way to change the globals, so I cannot use the
      exec statement.
    * the execfile statement could do everything that I want (e.g.
      support statements + changing globals). But.... I cannot pass the
      source code as a string. Looks like I MUST give a file name as the
      first argument. Even worse, this can't be a temporary file
      (because it has no name on some systems). This I consider a
      security problem. Yes, I know that I might be able to create a
      directory with good permissions, and then write out 10-100 files
      in every second for compiling... but it seems a waste of time, and
      why would I create 100 files per second on an unknown filesystem
      when I only need to pre-compile some functions?

Are there any other options? (Python 2.7 + numpy, should be compatible 
with Windows, Linux and FreeBSD)



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110730/8caa6b61/attachment.html>

More information about the Python-list mailing list