Live Engine
Select Topic
easyDesign Patterns
A developer reads the Gang of Four (GoF) book and tries to implement a Singleton pattern in Python exactly as described for Java — using a private constructor and a static getInstance() method. Their Python colleague says: "The canonical GoF Singleton implementation doesn't translate idiomatically to Python." What are the two most Pythonic ways to implement a Singleton, and how do they differ from the GoF approach?
Code
# config.py
class _Config:
def __init__(self):
self.db_host = "localhost"
self.debug = False
# Module-level instance — created once on first import, cached by sys.modules
config = _Config()
# Usage in any file:
from config import config
config.db_host = "production.db.com" # Same object everywhere