Ben Chuanlong Du's Blog

It is never too late to learn.

Implement Singleton in Python

Tips and Traps

  1. Module is a good alternative to singletons in Python.
In [1]:
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

Comments