exec'ing functions (WAS: updating locals() and globals())

Steven Bethard steven.bethard at gmail.com
Thu Dec 9 04:44:02 CET 2004


Jeff Shannon wrote:
> Steven Bethard wrote:
> 
>> Jeff Shannon wrote:
>>
>>> Note also that functions which use exec cannot use the static 
>>> namespace optimization, and thus tend to be *much* slower than normal 
>>> functions 
>>
>> In what circumstances will this be true?  I couldn't verify it:
[snip]
> 
> I was referring to functions which have an internal exec statement, not 
> functions which are created entirely within an exec -- i.e., something 
> like this:

Thanks for the clarification.  Here's the results for some functions 
with internal exec statements:

 > cat fib.py
def fib1(n):
     a, b = 0, 1
     while True:
         a, b = b, a + b
         yield a


exec """\
def fib2(n):
     a, b = 0, 1
     while True:
         a, b = b, a + b
         yield a
"""

def fib3(n):
     a, b = 0, 1
     while True:
         exec "a, b = b, a + b"
         yield a

def fib4(n):
     exec "a, b = 0, 1"
     while True:
         exec "a, b = b, a + b"
         yield a

 >
 > python -m timeit -s "import fib" "fib.fib1(100)"
1000000 loops, best of 3: 0.71 usec per loop

 > python -m timeit -s "import fib" "fib.fib2(100)"
1000000 loops, best of 3: 0.678 usec per loop

 > python -m timeit -s "import fib" "fib.fib3(100)"
1000000 loops, best of 3: 0.826 usec per loop

 > python -m timeit -s "import fib" "fib.fib4(100)"
1000000 loops, best of 3: 0.821 usec per loop

I'm not sure I'd say they're *much* slower, but you're right; they're 
definitely slower.

Steve



More information about the Python-list mailing list