PythoneasyPython

Singleton Pattern Decorator

Ensure a class has only one instance and provide a global point of access to it.

01

The problem

You need to ensure only one instance of a class exists throughout the application.

02

The solution

Python
import functools
from typing import Any, Dict

def singleton(cls):
    """Decorator to implement singleton pattern for a class."""
    instances: Dict[Any, Any] = {}
    
    @functools.wraps(cls)
    def wrapper(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    
    return wrapper

03

Put it to work

Example
@singleton
class DatabaseConnection:
    def __init__(self, connection_string: str):
        self.connection_string = connection_string
        self._connect()
        print(f"Connected to {connection_string}")
    
    def _connect(self):
        # Simulate connection
        pass
    
    def query(self, sql: str):
        return f"Executed: {sql}"

# Both instances will be the same
db1 = DatabaseConnection("mysql://localhost:3306/db")
db2 = DatabaseConnection("mysql://localhost:3306/db")
print(db1 is db2)  # True