So I have read that the way to share globals across files is to create a module which holds globals and import this in all python files needing to access the global. However it doesn't seem to work as expected for me (Python 3.6+)
Simple directory structure:
run.py
mypack/
-- globals.py
-- stuff.py
-- __init__.py
I have a global var in globals.py which I need to modify in main file (run.py) and finally print out while exiting the program. It does not seem to work:
__init__.py:
from .stuff import *
globals.py:
test = 'FAIL'
stuff.py:
import atexit
from .globals import test
def cya():
print ("EXIT: test = " + test)
atexit.register(cya)
def hi():
print('HI')
run.py:
import mypack
import mypack.globals as globals
mypack.hi()
globals.test = 'PASS'
print ("MAIN: test = " + globals.test)
Output on script execution:
HI
MAIN: test = PASS
EXIT: test = FAIL
Clearly the exit routine (cya) did not show the correct value of global value that was modified in run.py. Not sure what I am doing wrong.