Python3 Singleton Metaclass Method Not Working

I saw many methods for creating a singleton in Python, and I tried using a metaclass implementation with Python 3.2 (Windows), but it does not 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 am now using a decorator implementation that works, but I wonder what is wrong with this implementation?

+4
source share
1 answer

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

 class MyClass(metaclass=Singleton): pass 

And it works:

 >>> MyClass() is MyClass() True 
+10
source

Source: https://habr.com/ru/post/1487488/


All Articles