0

I'm trying to learn how to implement singleton pattern in python. It seems little bit difficult to implement singleton pattern in python.i don't know it's becauses of the nature of the language.

This is what i tried

class Singleton(object):
    _instance = None
    def __new__(cls):
        if cls._instance is not None:
            pass
        else:
            cls._instance = super().__new__(cls)
            return Singleton._instance
    def getInstance():
        return Singleton._instance

Does this code will create a singleton pattern, if it does is it a proper/good approach if it not what is bad about this code. I've read some SO questions and looked at the python data model documentation and this what i could come up with i wanna know what is the best approach in python to create a singleton pattern

ABHIJITH EA
  • 308
  • 4
  • 13
  • `getInstance` is a sign of poorly written singleton. Not to mention that it lacks any arguments, including required `self`. Each call to constructor will give you the same singleton instance, having a separate method for that is pointless. – matszwecja Dec 08 '22 at 08:32
  • @matszwecja yes you're right i understand now that `getInstance` method is pointless here. I did it because i read it here https://en.m.wikipedia.org/wiki/Singleton_pattern but i realise it's pointless here – ABHIJITH EA Dec 08 '22 at 08:40
  • @Cpt.Hook yeah i saw it, but it seems little old i wanted to know if there is any change happened or not and i wanted to get an opinion about my code like does it do the job or not – ABHIJITH EA Dec 08 '22 at 08:43
  • Singletons aren’t particularly hard to create in Python, your code is simply wrong. Where you have `pass`, you should be returning the existing instance… – deceze Dec 08 '22 at 08:51

0 Answers0