eval vs. exec

holger krekel pyth at devel.trillke.net
Mon May 27 15:17:10 EDT 2002


Simon Budig wrote:
> holger krekel <pyth at devel.trillke.net> wrote:
> > what you can do is e.g.
>  
> [slightly adjusted]
> (...)
> As you can see the return value always is "None". The real results
> get printed to stdout. This is the same problem I had with the
> eval/exec stuff.
> 
> Thanks for trying  :-)

:-) 

ok. seriously now!

this is the working version (i hope you appreciate it :-)

import compiler
from parser import ParserError

class MyCodeGenerator(compiler.pycodegen.InteractiveCodeGenerator):
    def visitDiscard(self, node):
        self.visit(node.expr)
        self.emit('RETURN_VALUE') # instead of printing :-)

def get_code(string):
    """ determine whether string is an expression or a statement """
    try: tree = compiler.pycodegen.parse(string,'exec')
    except ParserError,e:
        print "no valid statement:",string
        raise
    tree.filename='<string>'
    return MyCodeGenerator(tree).getCode()

def run_code(string, mathstuff={'myabs': lambda x: abs(x)}):
   print "execing",string
   codeobj = get_code(string)
   return eval(codeobj,mathstuff)

print "Result: %s" % repr (run_code('a=asdlkj(-3;myabs(a*5)'))
print "Result: %s" % repr (run_code('a=2'))
print "Result: %s" % repr (run_code('3*4'))
print "Result: %s" % repr (run_code('a=2;b=3;a*b'))
print "Result: %s" % repr (run_code('a=-3;myabs(a*5)'))


I know that this has the odor of beeing 'hackish'. But i 
think this is *mostly* because the compiler/parser modules 
are not in wide use. There are some respectable applications 
though which work with this layer of python (quixote e.g.). 

Also note that with this solution you can distinguish
parsing and runtime-exceptions.

have fun,

    holger





More information about the Python-list mailing list