Singleton Design Pattern

sohesh doshi
2 min readDec 20, 2022

A Singleton is a design pattern that restricts the instantiation of a class to a single object. This is useful when exactly one object is needed to coordinate actions across the system.

To implement a Singleton in Python, we can use a metaclass or a decorator.

Here is an example of a Singleton implemented using a 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 MyClass(metaclass=Singleton):
pass

In this example, the Singleton metaclass overrides the __call__ method of the class, which is called when a new instance of the class is created. The __call__ method checks if an instance of the class already exists in the _instances dictionary. If it does, it returns the existing instance. If not, it creates a new instance and stores it in the _instances dictionary before returning it.

Here is an example of a Singleton implemented using a decorator:

def singleton(cls):
instances = {}
def getinstance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return getinstance

@singleton
class MyClass:
pass

In this example, the singleton decorator is a function that takes a class as an argument and returns a modified version of the class that only allows a single instance to be created. The decorator creates a getinstance function that behaves similarly to the __call__ method in the previous example.

Both of these approaches have the same effect: they allow only a single instance of the class to be created, and any subsequent attempts to create a new instance will return the existing instance.

There are a few things to keep in mind when using Singletons in Python:

  • Singletons are not thread-safe by default. If you need to use a Singleton in a multi-threaded environment, you will need to implement additional synchronization to ensure that only one thread can create the instance at a time.
  • Singletons can make it more difficult to write unit tests, as they can introduce global state into your code. This can make it harder to isolate the behavior of individual classes and functions.
  • Singletons can make it harder to understand the dependencies between different parts of your code, as it can be unclear where the single instance of a class is being created and how it is being used.

--

--