Bizarre import duplication.

R

Richard Thomas

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.

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.

Richard
 
G

Gabriel Genellina

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top