Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 Singleton metaclass method not working

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?

like image 362
Lord Gamez Avatar asked Jun 21 '13 14:06

Lord Gamez


People also ask

What is metaclass Singleton?

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.

How do you call a singleton class in Python?

_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.

How do you get singleton in Python?

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.

Are Python modules singletons?

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.


1 Answers

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

class MyClass(metaclass=Singleton):
    pass

And it works:

>>> MyClass() is MyClass()
True
like image 199
Elazar Avatar answered Sep 21 '22 20:09

Elazar