Python 3.10.6
Suppose you have the following files:
main.py
setter.py
Folder/shared.py
With these contents:
# Folder/shared.py
class Shared:
i = 0 # something that is used in multiple locations
# setter.py
from Folder.shared import Shared
def set_i():
global Shared
print("mem in setter: " + hex(id(Shared.i)))
Shared.i = 2 # set the shared resource
# main.py
IMPORT_VIA_PATH = False
if IMPORT_VIA_PATH:
import sys, os
pwd = os.path.dirname(os.path.abspath(__file__))
shared_path = pwd + '/Folder'
sys.path.insert(0, shared_path)
from shared import Shared
else:
from Folder.shared import Shared
from setter import set_i
set_i()
print(Shared.i)
print("mem in main: " + hex(id(Shared.i)))
If IMPORT_VIA_PATH
is False
, main prints 2
for i
's value, and the memory addresses are different.
If IMPORT_VIA_PATH
is True
, main prints 0
for i
's value, and the memory addresses are the same.
Even more confusingly, if Shared.i
is replaced with just i
, throughout:
# Folder/shared.py
i = 0 # something that is used in multiple locations
# setter.py
from Folder.shared import i
def set_i():
global i
print("mem in setter: " + hex(id(i)))
i = 2 # set the shared resource
# main.py
IMPORT_VIA_PATH = True
if IMPORT_VIA_PATH:
import sys, os
pwd = os.path.dirname(os.path.abspath(__file__))
shared_path = pwd + '/Folder'
sys.path.insert(0, shared_path)
from shared import i
else:
from Folder.shared import i
from setter import set_i
set_i()
print(i)
print("mem in main: " + hex(id(i)))
Then for both IMPORT_VIA_PATH
True
or False
, i
remains zero and the memory addresses are the same. What is going on here?