CreationalPythonverifiedVerified

Singleton Pattern in Python

Ensures a class has only one instance and provides a global point of access to it.

How to Implement the Singleton Pattern in Python

1Step 1: Define the Singleton using a metaclass

class SingletonMeta(type):
    _instances: dict[type, "SingletonMeta"] = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class Singleton(metaclass=SingletonMeta):
    def do_something(self) -> None:
        print("Singleton method called")

2Step 2: Verify only one instance exists

a = Singleton()
b = Singleton()
print(a is b)  # True
a.do_something()

Singleton Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Singleton Pattern in the Real World

Think of a country’s president. There can only be one at any time. When anyone needs to communicate with the president, they don’t create a new one—they access the existing one through the official channel (the static method).