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

Jeff Shannon jeff at ccvcorp.com
Wed Dec 8 20:21:43 EST 2004


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:
>
> [...]
> exec """\
> def fib2(n):
>     a, b = 0, 1
>     while True:
>         a, b = b, a + b
>         yield a
> """


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:

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

In your fib2(), when the function is defined, the entire contents of the 
local namespace can be determined (it's just that the function isn't 
"defined" until the exec statement is executed).  In fib3(), when the 
function is defined, the parser can't determine what's happening inside 
the exec statement (it just sees a string, and that string may depend on 
other runtime circumstances which will happen latter), so it can't say 
for certain whether names other than a and b are created.  (Consider the 
case where the string to be exec'ed is passed in as a function argument...)

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list