9
votes

I saw a lot of methods of making a singleton in Python and I tried to use the metaclass implementation with Python 3.2 (Windows), but it doesn"t seem to return the same instance of my singleton class.

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class MyClass(object):
    __metaclass__ = Singleton

a = MyClass()
b = MyClass()
print(a is b) # False

I use the decorator implementation now which is working, but I'm wondering what is wrong with this implementation?

1
I know this thread is old, but why were you using Python2 syntax if you were programming in Python3? - Charles Addis
Is anyone else bothered that the class is allowed to take arguments? What behavior is defined when a singleton is "instantiated" with two different sets of arguments? - Noctis Skytower

1 Answers

20
votes

The metaclass syntax has changed in Python3. See the documentaition.

class MyClass(metaclass=Singleton):
    pass

And it works:

>>> MyClass() is MyClass()
True