I'm struggling a bit to understand how this variable is able to be shared in this package setup I have. It is working fine using the standard config.py module, but I can't wrap my head around "why" it is working.
Here is my current simple package setup (code for each module is placed under the module for better readability here):
test/
__init__.py
from test import config
config.username = "username-init"
config.py
username = "username-config"
main.py
from test import config
print(config.username) # prints "username-init"
In Python, when I run from test import main , here is what happens (learned by putting extra print() statements in each module to see what is happening):
__init__.pyruns first, which makes sense with thefrom testpart of the import statement.__init__.pyimportsconfig.pyconfig.pyruns which sets the username variable to the initial value ofusername-config- So at this point,
__init__.pyhas the username variable in its global namespace. main.pyfinally runs, which once again runsfrom test import configmain.pyprintsconfig.usernamewhich returns the edited valueusername-init
My question centers around step 5 above. By putting extra print() statements in each module, I can see that when main.py runs its from test import config line, __init__.py is not run a second time as it was the first time in Step 1 above. Why wouldn't main.py have to run __init__.py also since the main.py namespace would have no knowledge of anything in __init__.py ? Certainly my Python session's global namespace now has knowledge of __init__.py after Step 1 above, but the main.py module's namespace would not, so when main.py encounters its own from test import config line it would need to run __init__.py as was done in Step 1, correct?