I met with such a situation that a singleton object implemented by module is instantiated twice when imported in two different other module files. I suspected that it was caused by the uses of two kinds of import statement and therefore making the Python interpreter loaded the module twice, hence two instances of a singleton object.
Here is a simplified version of environment / structure to reproduce:
.
├── main.py
└── package
├── __init__.py
├── modA.py
├── modB.py
├── modC.py
main.py
import package.modB
import package.modC
if __name__ == "__main__":
print('Hello world')
modA.py
a_list = [1, 2, 3]
__init__.py, in order to directly import modA
import sys
import os
sys.path.insert(1, os.path.dirname(__file__))
modB.py
import modA
print(hex(id(modA.a_list)))
modC.py
from . import modA
print(hex(id(modA.a_list)))
Invoking main.py
in project directory would give such output
0x7fc579bd5c80
0x7fc579bd5a40
Hello world
You can see that the two memory addresses of a_list
are different.
So, modA
is imported using absolute as well as relative importing statements. If you may ask why I was doing that, it’s because I learnt and wanted to try relative importing in the middle of development while the project started off using only absolute importing.
In modC.py
, by printing sys.modules
I can confirm that package.modA
and modA
co-exist, showing that the same module was loaded twice.
Is this a bug or something else?