Nested Scopes Question (exec)

Ryan LeCompte rmlecompte at hotmail.com
Sun Jun 24 17:14:41 EDT 2001


Hello all,

I have been reading PEP 227 concerning statically nested scopes, and I have 
read that the from module import * and exec statements are not allowed in 
functions that contain nested function definitions which reference a free 
variable defined outside of the outer namespace. Wow, that sounds confusing. 
Here is exactly what I'm playing with:


Python 2.1 (#1, May 22 2001, 18:23:10)
[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
Type "copyright", "credits" or "license" for more information.
>>>from __future__ import nested_scopes
>>>y = 1
>>>def f():
...     exec "print 'hello'"
...     def g():
...             return y
...
  File "<stdin>", line 2
SyntaxError: unqualified exec is not allowed in function 'f' it contains a 
nested function with free variables
>>>def f():
...     exec "print 'hello'" in globals(), locals()
...     def g():
...             return y
...
>>>f()
hello
>>>def f():
...     exec "print 'hello'"
...     def g(): pass
...
>>>f()
hello
>>>
Now, it states in the PEP 227 that the exec and from module import * 
statements are not allowed in the above cases due to the fact that the 
compiler would not be able to determine if the value of y that the function 
g() would return should be from the free variable y in the global namespace, 
or the local variable y  defined in the namespace for f(), because the exec 
statement could in fact introduce a new local variable that shadows the 
outer global variable y.

Now, it appears that when you utilize the full syntax for the exec 
statement: exec 'expression' in globals(), locals() or exec 'expression in 
locals()', etc... the SyntaxError exception will not be raised and the code 
works as intended.

The PEP states that the SyntaxError exception will be raised for "bare 
execs" which don't utilize the full syntax as given above, but why does the 
exception disappear when the full syntax is used? How does the compiler know 
that the exec statement won't introduce a new local variable in the local 
namespace, and if it does, how does it know at compile time if it should use 
the global value or the possibly newly defined local value?

P.S. --- Aren't the following two calls the same:

exec "print 'hello'"
exec "print 'hello'" in globals(), locals()

So why the different behavior for these two calls when using the above 
examples with from __future__ import nested_scopes
??

Thanks,

Ryan LeCompte
rmlecompte at hotmail.com

_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com





More information about the Python-list mailing list