I want to turn my derived class into a singleton in python. I would like to implement the singleton via metaclass, but I always come across the following error:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
My Code:
# singleton.py
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]
# base.py
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def run(self, value):
pass
# foo.py
from base import Base
from singleton import Singleton
class Foo(Base, metaclass=Singleton):
def run(self, value):
print(value)
# main.py
from foo import Foo
f1 = Foo()
print(f1)
f1.run(42)
f2 = Foo()
print(f2)
f2.run(24)