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):

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.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →