DEV Community

João M.C. Teixeira
João M.C. Teixeira

Posted on • Updated on

Python Singletons

A long time has passed since I last wrote a Singleton. Definitively, we rarely write singleton patterns in Python because we can represent singletons as variables in a module, and import them everywhere - see my strategy for logging library wide.

However, how should we construct a singleton class which represents a state that is initialized (loaded/read) together with the class first instantiation and for which we don't want the whole loading process to be repeated in case the singleton class is instantiated again at a different stage of the runtime?

Well, here it is:

class MyClass:
    _state = None

    def __new__(cls, *args, **kwargs):

        if cls._state:
            print('State already exists, returning existing state.')
            return cls._state

        elif cls._state is None:
            cls._state = super().__new__(cls)
            return cls._state

    def __init__(self, arg):
        self.arg = 1


a = MyClass(1)
print(a.arg)  # 1
b = MyClass(2)
print(b.arg)  # 1

assert a is b  # True
Enter fullscreen mode Exit fullscreen mode

Enjoy and Cheers,

Top comments (0)