I am using Method 3: A metaclass from Creating a singleton in Python for creating object from singleton class.
Now depending upon certain event, I want to delete this singleton object and remove its entry from dictionary maintained by metaclass.
How I can do this (without making any change in Singleton class) ?
Here is code snippet for better understanding:
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():
__metaclass__ = Singleton
def __init__(self, val1):
self.val1 = val1
obj1 = MyClass(10)
print obj1.val1
del obj1
obj2 = MyClass(20)
print obj2.val1
Output:
10
10