Is this form of global variable declaration good practice in Python? My dictionary has no data in B.py in some cases. Just seems inconsistent.
classes.py
class Aclass:
dict = {}
myClass = Aclass()
A.py:
from classes import myClass
myClass.dict["variable"]
B.py:
from classes import myClass
print str(myClass.dict)
A.py is processed before B.py. This prints an empty dict {} for me.
This is a simplified question from previous post: Shared/Global Dictionary in Django Between URLs and Context Processor. Your insight is appreciated.
1 Answer 1
if in A.py you change it to
myClass.dict["variable"]="hello"
(as pointed out in comments)
then the question becomes interesting.
it's ok but it's better to have another interface (functions, methods) to that data. It's a way to store a state of the module. The object you called myClass (!) is the same both from a and b.
multiple imports are safe and do nothing except to return the same loaded module.
1 Comment
sys.modules dictionary. :)
myClass.dict["variable"] = "value"(or something to that effect)?