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

Steven Bethard steven.bethard at gmail.com
Thu Dec 9 01:49:54 CET 2004


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:

 > 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
"""
 > python -m timeit -s "import fib" "fib.fib1(100)"
1000000 loops, best of 3: 0.714 usec per loop

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



More information about the Python-list mailing list