Explicit or general importing of namespaces?

Peter Hansen peter at engcorp.com
Mon Feb 28 07:33:25 EST 2005


Diez B. Roggisch wrote:
>>I'm unable to tell a real difference other than in the code writing
>>:-).
> 
> The difference is that the from-syntax may cause name space pollution. See
> the FAQ:
> 
> http://www.python.org/doc/faq/programming.html#id12

Ultimately more important than mere "pollution" are the
latent problems this can cause if any of the names in
the original module can ever be re-bound.

Use of the "import *" technique creates module-global names
with bindings to the original objects referenced by the
names in the imported module.  If those names (in the imported
module) are rebound (reassigned) at any time by other
code, whether in the module or elsewhere, this has no
effect on the module-global names created in the _importing_
module, which is quite often a bug.

Small demo:

# module A
x = 5

# module B
import A
A.x = 6

# module C
from A import x
import B
print x


This will not print 5, of course.  In non-trivial code this
sort of problem is much harder to discover and debug.

In general, unless the names being imported are *guaranteed*
never to be rebound, it is a very bad idea to use "import *",
and it's still a bad idea in almost all cases anyway, for
reasons already given by others.

-Peter



More information about the Python-list mailing list