Python: Singleton Class

created:

updated:

tags: python design pattern

Singleton class

| Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. (Refactoring Guru)

| A singleton class is a class that only allows creating one instance of itself. (Python Morsels)

How to make a Singleton in Python

There are a few different ways to create a singleton class in Python. Below is from an example from Python Morsel’s:

class Example:
    _self = None

    def __new__(cls):
        if cls._self is None:
            cls._self = super().__new__(cls)
        return cls._self

    def __init__(self):
        self.attribute1 = "I'm an attribute 1"
  • __init__ method is the initializer method.
  • By the time the __init__ method gets called, our class instance has already been constructed. That’s what the self argument in a method is:

    def __init__(self):
        ...
    
  • The __new__ method is the constructor method. Its job is to do the actual work of constructing and then returning a new instance of our class:

    class Example:
    _self = None
    
    def __new__(cls):
        if cls._self is None:
            cls._self = super().__new__(cls)
        return cls._self
    
    • In the Example class, our constructor always returns the same instance.
  • Since every instance of the Example class is the same, it means that we made a singleton class.

References