Bizarre import duplication.

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Mar 7 02:29:06 CET 2009


En Fri, 06 Mar 2009 22:05:53 -0200, Richard Thomas <chardster at gmail.com>  
escribió:

> Say I have a project like this:
>
>     ./run.py
>     ./package/__init__.py
>     ./package/mod1.py
>     ./package/subpackage/__init__.py
>     ./package/subpackage/mod2.py
>     ./package/subpackage/mod3.py
>
> And suppose that "." and "package" (or their absolute paths) are in
> sys.path.

That's a mistake. Never put redundant directories in sys.path. In this  
case, mod1 is reachable as "package.mod1" (from the "." entry in sys.path)  
and also as "mod1" (from the "package" entry). That must not happen -  
module names *must* be unique (here, "module name" means "sequence of  
package names plus the final file name", starting at some entry in  
sys.path)
Usually there is no need (and it's not even convenient) to put a package  
in sys.path -- the directory *containing* the package should be listed  
instead. In this case, it is ".".

> Now mod1.py and mod2.py both contain this:
>     from subpackage import mod3
>
> In this very particular case, the two references to mod3 are separate
> initialisations of mod3.py. This can't be the intended behaviour, its
> maybe a little contrived but I found myself want to set it up this way
> so it can't be outside possibility.

Using a relative import (and enabling absolute imports by default, by  
using: from __future__ import absolute_imports) is somewhat safer, but you  
can still confuse the complicated import machinery if you put redundant  
entries in sys.path

-- 
Gabriel Genellina




More information about the Python-list mailing list