In the a.py class, it's fetching values for the indicators dictionary. I'm trying to save those values to a global dictionary variable in container.py and then access them in b.py.
So, I declared a singleton called GlobalContainer in container.py and declared a dictionary inside it. Then, in a.py, I added the values fetched to that dictionary. However, when I tried to access the dictionary in the singleton from b.py, there were no values. Upon checking, I found that the memory address of GlobalContainer in container.py is different.
I need a single data storage accessible from a.py, b.py, c.py, etc. I don't understand why the singleton addresses are different.
container.py
class Singleton:
def __init__(self, decorated):
self._decorated = decorated
self._initialized = False # Flag for first instance creation
def instance(self):
if not self._initialized:
self._instance = self._decorated()
self._initialized = True
return self._instance
def __call__(self):
raise TypeError('Singletons must be accessed through `instance()`.')
def __instancecheck__(self, inst):
return isinstance(inst, self._decorated)
def __wrap__(self, instance, objtype, wrapper):
# Allow access to class methods using the actual class object (cls)
instance.__getattribute__ = lambda self, name: getattr(objtype, name, self.__dict__[name])
return wrapper(instance)
@Singleton
class GlobalContainer:
containers = {}
def __init__(self):
# No initialization check needed here
print("### GlobalContainer created") # This will print only once
@classmethod
def set_indicators(cls, symbol, indicators):
if symbol not in cls.containers:
cls.containers[symbol] = {'indicators': indicators}
else:
cls.containers[symbol]['indicators'] = indicators
@classmethod
def get_indicators(cls, symbol):
container = cls.containers.get(symbol, {})
return container.get('indicators', None)
in a.py
GlobalContainer.instance().set_indicators(self.symbol, self.indicators)
in b.py
GlobalContainer.instance().get_indicators(symbol)
The print('### GlobalContainer created') in the singleton's init part is executed twice. I want only one instance to be created and used as a global variable for GlobalContainer.
The "singleton" has two different addresses because you are executing two different scripts, each of which defines a new
GlobalContainersclass on start-up. The class is not shared between two separate processes.