I am trying to apply the Singleton design pattern in the below code
class SMSMgr( object ):
_instance = None
def __init__(self):
self._allsp = []
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(SMSMgr, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def loadsettings(self):
get_all_sp = ServiceProvider.objects.filter(status = False)
for obj in get_all_sp:
cla = obj.class_Name
a=globals()[str(obj.class_Name)](obj.userName,obj.password,obj.sendingurl)
self._allsp.append(a)
#print self._allsp
def send(self):
print "+++++++++++++++++++== Global send "
if __name__ == "__main__":
b = SMSMgr()
b.loadsettings()
print b._allsp
print "b end -------------------"
c = SMSMgr()
c.loadsettings()
print c._allsp
print "c end -------------------"
According to singleton b object should be same as c object .
But when i am running this above code i am getting the different objects for b and c
Please suggest me how can i do this as a Singleton.
I’m pretty sure the problem here is that there is no sentinel for your
__init__, so even though each instantiation returns the same object,__init__is being rerun each time as well. You could try something like this:Though for a more robust solution, you probably want something more like:
Just be aware that this is not thread safe unless you wrap the init functionality in a lock of some sort.
As @mgilson eludes to in his answer though, if you are trying to create a singleton in Python, you probably should just be using class attributes instead of instance attributes, and looking at whether it even makes sense for the class to be completely separate to begin with, or to fold it in to some other, non-singleton class. There’s also a pattern, the borg pattern, that is frequently mentioned when singetons and Python are brought up in the same paragraph.