0

I am trying to achieve singleton in python. Why is the below code wrong in achieving singleton pattern in Python?

class test:
    _instance = []

    def __init__(self):
        if len(test._instance)!=0:
            print('Object instantiated')
            self = test._instance[0]
        else:
            test._instance.append(self)

a = test()
print(a)
b = test()
print(b)

The output:

<__main__.test object at 0x0000023094388400>
Object instantiated
<__main__.test object at 0x00000230949D6700>

Expected Object 'b' to be same as 'a'
Robert
  • 7,394
  • 40
  • 45
  • 64
  • Does this answer your question? [Is there a simple, elegant way to define singletons?](https://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons) – Marco F. Jan 10 '23 at 15:54
  • Hi @MarcoF. thanks for responding, but my question was : since __init__ is anyways changing self to already created object that is stored in class variable '_instance' why is the object id of 'b' different from object id of 'a'(which was created previously and stored in class variable '_instance' – karthik basavarajappa Jan 17 '23 at 16:41

1 Answers1

0

Assigning to self rebinds the local variable self to the new object. An assignment to a bare name dontchange any object, it rebinds the name on the left-hand side to point to the object on the right-hand side.

You could make a static method to manage the instance. I don't think it is possible only with __init__.

 class Test():
    obj = None
    def __init__(self):
        print("__init__")
        
    def GetSingleton():  
        if Test.obj is None:
            Test.obj = Test()
        return Test.obj
        
        
        
a = Test.GetSingleton()
b = Test.GetSingleton()
print(a)
print(b)

output

__init__
<__main__.Test object at 0x7f94558b9390>
<__main__.Test object at 0x7f94558b9390>
Marco F.
  • 432
  • 1
  • 10