The problem
You need to ensure only one instance of a class exists throughout the application.
The solution
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 wrapperPut it to work
@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