why import * only allowed at module level?

Simo Salminen this at is.invalid
Mon Jan 14 06:33:49 CET 2002


* Hans Nowak [Mon, 14 Jan 2002 04:39:13 GMT]
> "One side effect of the change is that the from module 
> import * and exec statements have been made illegal 
> inside a function scope under certain conditions. The 
> Python reference manual has said all along that from 
> module import * is only legal at the top level of a 
> module, but the CPython interpreter has never enforced 
> this before. As part of the implementation of nested 
> scopes, the compiler which turns Python source into 
> bytecodes has to generate different code to access 
> variables in a containing scope. from module import * 
> and exec make it impossible for the compiler to 
> figure this out, because they add names to the local 
> namespace that are unknowable at compile time." 
> 

[and that paragraph continues]
"Therefore, if a function contains function definitions or lambda expressions
with free variables, the compiler will flag this by raising a SyntaxError
exception." 

ok, but why:
>>> def a1():
...     from os import *

does not work, but:

>>> def a2():
...     exec 'from os import *'


works?

-- 
simo <dot> salminen <at> iki <dot> fi



More information about the Python-list mailing list