I'm not sure I completely understand your problem, partly because you haven't included any code in your question. So, based solely on my interpretation of the description you wrote, I think the following will address the issue of the two singleton subclasses interfering with each other.
A generic Singleton metaclass is used to define the base singleton class. The metaclass ensures that a separate single instance is created for each singleton class instance of itself -- i.e. your MySingletonBase
in this case -- which is exactly what I think you want. The two subclasses derived from it, A
and B
, will inherit this metaclass from the baseclass and thereby will have independent instances of their singleton superclass.
This code below is based on one of my answers to the question:
How to initialize Singleton-derived object once?
# singleton metaclass
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 MySingletonBase(object):
__metaclass__ = Singleton
def __init__(self):
self.values_list = []
def test_method(self, value):
self.values_list.append(value)
def total(self):
return sum(self.values_list)
class A(MySingletonBase): pass
class B(MySingletonBase): pass
a1 = A()
b1 = B()
a2 = A()
a1.test_method(42)
a2.test_method(13)
print '{}, {}'.format(a1.values_list, a1.total()) # [42, 13], 55
print '{}, {}'.format(a2.values_list, a2.total()) # [42, 13], 55
print '{}, {}'.format(b1.values_list, b1.total()) # [], 0
The output illustrates that instances of subclass A
are indeed singletons, and are separate from any instances created of subclass B
, yet they are both inheriting MySingletonBase
's methods.