why import * only allowed at module level?
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.
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."
# decode for email address ;-)
More information about the Python-list