redundant imports

Peter Hansen peter at engcorp.com
Wed Mar 30 08:27:32 EST 2005


max(01)* wrote:
> hi everybody.
> 
> suppose that code-1.py imports code-2.py and code-3.py (because it uses 
> names from both), and that code-2.py imports code-3.py.
> 
> if python were c, code-1.c should only *include* code-2.c, because the 
> latter in turns includes code-3.c.
> 
> inclusion of modules in c is a purely preprocessing textual matter 
> (compilation is deferred to after the fact), i guess, so that such 
> things are possible. import of modules in python is a different beast, 
> so the "redundancy" is (i think) necessary.
> 
> any comment/suggestion/idea?

You're mixed up about this whole idea.

You say first that "[code-1] uses names from both",
which by definition means that it needs to import
both.  (I say by definition because import is *how*
a module gets names from another module.)

Then you say that code-1 can choose not to include
code-3 because some other module is including it...
but so what?  That doesn't change the fact that
code-1 needs names from code-3, and just because
code-3 is imported elsewhere is no reason to think
that code-1 magically gets its names too.  Should
all modules magically see all names in all modules
which are imported, even by other modules?  That
would pretty much defeat most of the value of
namespaces.

Anyway, why this concern over so-called redundant
imports?  The source code itself is not parsed
and compiled all over again, and even the .pyc file
is not re-read... once any module has imported a
module any other import just retrieves a reference
to that module from the sys.modules dictionary,
which is practically a free operation.

-Peter



More information about the Python-list mailing list