How do you implement the Singleton pattern in Python?
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. In Python, there are several ways to implement it:
- Module-level variable (most Pythonic): Python modules are singletons by nature. Import the same module twice and you get the same object.
__new__override: Control instance creation by caching the first instance.- Metaclass: A metaclass that intercepts class creation.
- Decorator: Wrap a class to cache its instance.
The module-level approach is the most Pythonic because Python modules are already singletons.
Module-level: Just use a module variable
__new__: Override __new__ to return cached instance
Metaclass: type.__call__ checks for existing instance
Decorator: Wrap class; return same instance on repeated calls
# Method 1: Module-level singleton (most Pythonic)
# config.py
class _Config:
def __init__(self):
self.debug = False
self.database_url = 'sqlite:///app.db'
config = _Config() # Module-level instance
# Usage: from config import config
# Every import gets the same instance
# Method 2: __new__ override
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, value=None):
if not hasattr(self, '_initialized'):
self.value = value
self._initialized = True
a = Singleton('first')
b = Singleton('second')
print(a is b) # True
print(a.value) # 'first' (not overwritten)
# Method 3: Metaclass singleton
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Database(metaclass=SingletonMeta):
def __init__(self, url='sqlite:///app.db'):
self.url = url
print(f'Connecting to {url}')
db1 = Database() # 'Connecting to sqlite:///app.db'
db2 = Database('postgres://...') # No output; returns existing instance
print(db1 is db2) # True
# Method 4: Decorator singleton
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Logger:
def __init__(self, name='app'):
self.name = name
def log(self, message):
print(f'[{self.name}] {message}')
logger1 = Logger()
logger2 = Logger('other') # Ignored; returns existing
print(logger1 is logger2) # True
- •Module-level variables are the most Pythonic singleton (modules are cached after first import)
- •__new__ is called before __init__; override it to return a cached instance
- •Metaclass approach is cleanest for multiple singleton classes
- •Decorator approach is simple but changes the class to a function (breaks isinstance)
- •Guard __init__ with a flag to prevent re-initialization
- •__init__ is called every time even with __new__ singleton; guard with _initialized flag
- •The decorator approach replaces the class with a function, breaking isinstance checks
- •Singletons make unit testing harder because state persists between tests
- •Thread safety: add threading.Lock() for multithreaded singleton creation