views:

6009

answers:

4

What is the best way to implement the singleton pattern in Python? It seems impossible to declare the constructor private or protected as is normally done with the Singleton pattern...

+1  A: 

The Singleton Pattern implemented with Python courtesy of ActiveState.

It looks like the trick is to put the class that's supposed to only have one instance inside of another class.

Mark Biek
+4  A: 

This is a duplicate of this question.

EDIT: fixed link

dF
That should be http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python (beta.stackoverflow.com is no more)
James Emerton
+4  A: 

you can ovverdie the new method like this

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(
                                cls, *args, **kwargs)
        return cls._instance


if __name__ == '__main__':
    s1=Singleton()
    s2=Singleton()
    if(id(s1)==id(s2)):
        print "Same"
    else:
        print "Different"
jojo
I like this one, it's simple and works.
Ian
+1  A: 

Have you guys seen this implementation from Wikipedia? Implementing the singleton pattern with a decorator.

def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance

@singleton class MyClass: ...

Wei