Globals across modules
Posted
by
Coder1
on Stack Overflow
See other posts from Stack Overflow
or by Coder1
Published on 2011-11-26T09:35:40Z
Indexed on
2011/11/26
9:53 UTC
Read the original article
Hit count: 196
python
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
© Stack Overflow or respective owner