Slowness in compile()/eval()

Pedro Rodriguez pedro_rodriguez at club-internet.fr
Thu Jan 17 13:04:20 EST 2002


"Alex Martelli" <aleax at aleax.it> wrote:

>> - if this is the case, could this an idiom :
>>   instead of writing :
>>       code = compile("some expr", '<string>', "eval") val = eval(code)
>>
>>   one should consider writing :
>>       code = compile("def __f(v1,v2,...):\n return some_expr\n"
>>                      , '<string>', 'exec')
>>       eval(code)
> 
> You must use exec code here, not eval(code).
> 

See, I was really missing a point here ;)

I think it is almost there. Almost because :

-----------------------------------------------------------------------
def a():
    code = compile("def f():\n pass\n", '<string>', "exec")
    exec code
    print f

a()
-----------------------------------------------------------------------
<function f at 80dfa48>
-----------------------------------------------------------------------

But :
-----------------------------------------------------------------------
def a():
    f = None
    code = compile("def f():\n pass\n", '<string>', "exec")
    exec code
    print f

a()
-----------------------------------------------------------------------
None
-----------------------------------------------------------------------

Doing 'exec code in locals()' does not help.


> eval should reject code, since it was compiled for exec, not for eval
> (it's a statement, not an expression).  You should open a bug report
> about this, I believe, since this is the bug (in eval) which produces
> the following anomaly:
> 

Will submit it.


>> - why is eval("some_expr") so slow with Python 2.x (will profile it)
> 
> Profiling is a good idea, but I think you won't find it slower (once the
> compile step is removed, of course -- recompiling each and every time
> WILL slow things down) than the same expression in a normal setting,
> when both (e.g.) access data globally.
> 

Sorry, I didn't meant to compare eval(code) to eval(string), I meant by 
comparing Python 1.5.2 to Python 2.X performance, for the function 
eval("string") : 50% of loss ???


Regards,
-- 

Pedro



More information about the Python-list mailing list