eval vs. exec

Michael Hudson mwh at python.net
Tue May 28 08:47:21 EDT 2002


Simon Budig <Simon.Budig at unix-ag.org> writes:

> Michael Hudson <mwh at python.net> wrote:
> > Hmm.  Maybe compile as "single" but smash the last PRINT_EXPR into a
> > RETURN_VALUE?  Might work.  You'd probably want to turn all but the
> > last PRINT_EXPR into POP_TOPs too...
> > 
> > Something like this?
> [...]
> >>>> super_eval("a = 2")
> >>>> super_eval("3*4")
> > 12
> >>>> super_eval("a = 2; b = 3; a*b")
> > 6
> 
> Whow, this is impressive. Yes, this seems to work although this is
> way beyond my python-scope  :-)
> 
> I am not sure if I want to do this or if the interception of
> sys.stdout is a more - uhm - Simon-friendly solution...    ;-)

Here's another crack.  It works much the same way as the last one, but
is somewhat more sensible...

from compiler.pycodegen import InteractiveCodeGenerator, \
     AbstractCompileMode

class SuperICG(InteractiveCodeGenerator):
    def visitDiscard(self, node):
        self.visit(node.expr)
        self.storeName('$ output')

class SuperI(AbstractCompileMode):
    mode = "single"
    def compile(self):
        tree = self._get_tree()
        gen = SuperICG(tree)
        self.code = gen.getCode()

def super_eval2(expr):
    gen = SuperI(expr, "")
    gen.compile()
    code = gen.code
    d = {}
    eval(code,d,d)
    return d.get('$ output')

Just's solution is quite nice too.

Cheers,
M.

-- 
  In that case I suggest that to get the correct image you look at
  the screen from inside the monitor whilst standing on your head.  
               -- James Bonfield, http://www.ioccc.org/2000/rince.hint



More information about the Python-list mailing list