How to create a singleton in Python?

Better Stack Team
Updated on February 17, 2023

The singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance.

Using metaclass

In Python, there are multiple ways to do that but the most effective is using metaclasses.

 
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 Logger(metaclass=Singleton):
    pass

In the example above, the Logger class is a singleton - every instance of the Logger will be the same. There will always be only one Logger and all Logger objects will refer to that one Logger.