Skip to content

Singleton

The Singleton pattern is a design pattern that restricts the instantiation of a class to a single instance. This is useful when exactly one object is needed to coordinate actions across the system.

Import packages

1
2
3
import sqlite3
import threading
from typing import Any, Dict, Type

Define class

class Singleton(type):
    _instances: Dict[Type, Any] = {}
    _locks: Dict[Type, threading.Lock] = {}
    _global_lock: threading.Lock = threading.Lock()

    def __call__(cls, *args: Any, **kwargs: Any) -> Any:
        if cls in cls._instances:
            return cls._instances[cls]

        with cls._global_lock:
            lock = cls._locks.setdefault(cls, threading.Lock())

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

    @staticmethod
    def drop() -> None:
        Singleton._instances.clear()
        Singleton._locks.clear()

Usage

class Database(metaclass=Singleton):
    def __init__(self, db_url: str = ":memory:"):
        self.conn = sqlite3.connect(db_url)

    def query(self, sql: str):
        return self.conn.execute(sql).fetchall()


db1 = Database("database.sqlite")
db2 = Database("ignored.sqlite")

print(db1 is db2)
True