exec statement with/without prior compile...

Jaime Fernandez del Rio jaime.frio at gmail.com
Mon May 25 10:07:13 EDT 2009


These weekend I've been tearing down to pieces Michele Simionato's
decorator module, that builds signature preserving decorators. At the
heart of it all there is a dynamically generated function, which works
something similar to this...

...
    src = """def function(a,b,c) :\n    return _caller_(a,b,c)\n"""
    evaldict = {'_caller_' : _caller_}
    code = compile(src, '<string>', 'single')
    exec code in evaldict
    new_func = evaldict[function]
...

I have found fooling around with this code, that the compile step can
be completely avoided and go for a single:

    exec src in evaldict

Now, I'm sure there is a good reason for that additional step, but I
haven't been able to find what the difference between both approaches
is.

And since I'm asking, could something similar, i.e. defining a new
function and get a handle to it, be achieved with eval?

Thanks in advance,

Jaime Fernández
http://numericalrecipes.blogspot.com

-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
planes de dominación mundial.



More information about the Python-list mailing list