Wow, this seems so basic, but I can’t get it to work. All I need to do is store a global dict which can be accessed and modified from other modules & threads.
What’s the “best practices” way of achieving this?
test.py
import testmodule
class MyClassA():
def __init__(self, id):
self.id = id
if __name__ == '__main__':
global classa_dict
classa_dict = {}
classa_dict[1] = MyClassA(1)
classa_dict[2] = MyClassA(2)
testing = testmodule.TestModule()
testmodule.py
class TestModule():
def __init__(self):
global classa_dict
print classa_dict[2]
output
$ python test.py
Traceback (most recent call last):
File "test.py", line 13, in <module>
testing = testmodule.TestModule()
File "/path/to/project/testmodule.py", line 4, in __init__
print classa_dict[2]
NameError: global name 'classa_dict' is not defined
You can in fact acchieve something like what you want:
testmodule.py:
test.py:
Please note that global is used somewhat else than what you might think of. If you write
global varname, this means, that Python should not generate a local variablevarname, but look in the global scope for a variable namedvarname. That is, the classTestdoes not generate a local variableclassa_dict, but it uses the global variablyclassa_dictinstead.So,
globalis nothing to give at declaration to tell python that the variable can be used everywhere. It much more tells Python that there is already some variable with this name, that is referred to.This means, in
testmodule.tythe lineglobal classa_dictmeans: Look somewhere in the module to find a variableclassa_dictand operate on this variabla instead of creating a new local variableclassa_dict.In
test.py, then you can assignclassa_dict = testmodule.classa_dictwhich tells python thatlclassa_dictrefers to theclassa_dictintestmodule.py. Therefore, you don’t need aglobalintest.py, because, you simply modifytestmodule.classa_dictwhen you assign something tolclassa_dict. Then, the classTestintestmodule.pyknows that it should look totestmodule.classa_dictbecause it uses theglobal.