exec statement with/without prior compile...

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue May 26 03:19:14 EDT 2009


En Mon, 25 May 2009 11:07:13 -0300, Jaime Fernandez del Rio
<jaime.frio at gmail.com> escribió:

> 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.

The only reason I can think of, is restricting src to be a single
statement only (due to the compile flag used).

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

No, because def is a statement, and eval only accepts an expression.

-- 
Gabriel Genellina




More information about the Python-list mailing list