0

I ran across a very specific case where I cannot explain myself, why the python import does what it does and I am hoping you can help me. The set up is as follows:

root/
├── main.py
└── pack/
    ├── __init__.py  
    ├── db.py  
    └── plugins/
        ├── __init__.py  
        └── plug1/
           ├── __init__.py
           └── db.py

All files in the tree above are empty except root/pack/plugins/plug1/__init__.py which has the following content:

from pack.plugins.plug1 import db as plugin_db
from pack import db

and main.py with the following content:

import pack.plugins.plug1.db as plug_db
import pack.db as pack_db

print(pack_db.__file__)
print(plug_db.__file__)

When running main.py the output of the print statements is:

.../root/pack/db.py
.../root/pack/db.py

meaning the imported module is exactly the same.

My questions are:

  1. Why are the imported modules the same?
  2. Why does changing from pack import db to from pack import db as pack_db resolves the issue?
Woltan
  • 13,723
  • 15
  • 78
  • 104
  • would be interesting to edit tags to show exact python version – Jean-François Fabre Apr 24 '20 at 08:46
  • These are some really bad name choices. Whoever set things up like this is causing problems for themselves. – user2357112 Apr 24 '20 at 08:49
  • I assume he's using python 2. Because in python 2, its own modules are considered global, which would result in the same import because of the same name situation (as commented above) – lhd Apr 24 '20 at 08:53
  • Nah, this would behave the same in 2 or 3 because of how the import order and shadowing work out. – user2357112 Apr 24 '20 at 09:00
  • I agree that the name choices are bad. But this results from a plugin architecture and the main focus of this question is the import mechanics of python itself. – Woltan Apr 28 '20 at 18:45

0 Answers0