Implement Singleton Pattern in Python

Singleton is a creational design pattern, which is intended to be used when a class must have exactly one instance, no more, no less.

Let’s create a singleton Logger class that will be responsible for logging different actions.

The most popular way of creating a singleton in Python is using the metaclass approach:

A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass.

Let’s get to the code:

class Singleton(type):

def __init__(cls, name, bases, attrs, **kwargs):
super().__init__(name, bases, attrs)
cls._instance = None

def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance

class Logger(metaclass=Singleton):
#some class

l1 = Logger()
l2 = Logger()
print(l1 is l2)