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?
Creating Singletons using Metaclasses The singleton pattern is a design pattern that restricts the instantiation of a class to one object. It is used in cases where exactly one object is needed.
_instances: instance = super(). __call__(*args, **kwargs) cls. _instances[cls] = instance return cls. _instances[cls] class Singleton(metaclass=SingletonMeta): def some_business_logic(self): """ Finally, any singleton should define some business logic, which can be executed on its instance.
Creating a singleton in Python In the classic implementation of the Singleton Design pattern, we simply use the static method for creating the getInstance method which has the ability to return the shared resource.
Modules are “singletons” in Python because import only creates a single copy of each module; subsequent imports of the same name keep returning the same module object.
The metaclass syntax has changed in Python3. See the documentaition.
class MyClass(metaclass=Singleton):
pass
And it works:
>>> MyClass() is MyClass()
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With