eval vs. exec

Michael Hudson mwh at python.net
Wed May 29 07:51:13 EDT 2002


Michael Hudson <mwh at python.net> writes:

> Michael Hudson <mwh at python.net> writes:
> 
> > Simon Budig <Simon.Budig at unix-ag.org> writes:
> 
> [super_eval bytecodehack-lite-stylee]
> 
> > > 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...
> [version using the compiler module]
> 
> Actually, the two versions I posted share a piece of (probably)
> undesired behaviour.  Can anyone spot it?

It seems noone did.  Here it is:

>>> super_eval("1;a=1")
1

That should probably have returned None.

Here's my final word on the subject:

from compiler.pycodegen import InteractiveCodeGenerator, \
     AbstractCompileMode

class SuperICG(InteractiveCodeGenerator):
    def visitDiscard(self, node):
        self.visit(node.expr)
        if self.return_val:
            self.emit('RETURN_VALUE')
        else:
            self.emit('POP_TOP')
    def visitStmt(self, node):
        self.return_val = 0
        children = node.getChildNodes()
        for child in children[:-1]:
            self.visit(child)
        self.return_val = 1
        self.visit(children[-1])
        
class SuperI(AbstractCompileMode):
    mode = "single"
    def compile(self):
        tree = self._get_tree()
        print tree
        gen = SuperICG(tree)
        self.code = gen.getCode()

def super_eval2(expr, d=None):
    if d is None: d = {}
    gen = SuperI(expr, "")
    gen.compile()
    code = gen.code
    return eval(code, d)

This is my first play with the compiler module... I think I like it :)

Cheers,
M.

-- 
  While preceding your entrance with a grenade is a good tactic in
  Quake, it can lead to problems if attempted at work.    -- C Hacking
               -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html



More information about the Python-list mailing list