why import * only allowed at module level?

Hans Nowak wurmy at earthlink.net
Mon Jan 14 05:39:13 CET 2002


Simo Salminen wrote:
> 
> How come python 2.2 does not allow code like this:
> 
> >>> def a():
> ...     from os import *
> <interactive input>:1: SyntaxWarning: import * only allowed at module level
> 
> Why this was changed? I like to do import * at function level because
> it is handy but doesn't pollute namespace.

See

  http://amk.ca/python/2.1/index.html

the section about nested scopes.

"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." 

--Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==') 
       # decode for email address ;-)
Site:: http://www.awaretek.com/nowak/



More information about the Python-list mailing list