Python singleton pattern
class SingletonMeta(type):
"""
The Singleton class can be implemented in different ways in Python. Some
possible methods include: base class, decorator, metaclass. We will use the
metaclass because it is best suited for this purpose.
"""
_instances = {}
def __call__(cls, *args, **kwargs):
"""
Possible changes to the value of the `__init__` argument do not affect
the returned instance.
"""
if cls not in cls._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.
"""
...
class NetManager:
"""
Execute net manager command.
This is singleton class only one
object of net manager will be created.
"""
_instance_ = None
@staticmethod
def get_net_manager(**kwargs):
""" Static method to get net manager object """
if NetManager.__instance__ is not None:
NetManager.__instance__.__dict__.update(**kwargs)
return NetManager.__instance__
return NetManager(**kwargs)
def __init__(self, **kwargs):
"""
Initialize Net Manager object
"""
if NetManager.__instance__ is None:
NetManager.__instance__ = self
self.__dict__.update(kwargs)
else:
raise Exception(
"You can not create another instance of net manger"
)
if _name_ == "__main__":
The client code.
s1 = Singleton()
s2 = Singleton()
if id(s1) == id(s2):
print("Singleton works, both variables contain the same instance.")
else:
print("Singleton failed, variables contain different instances.")