Singleton guarantees that a class has exactly one instance and gives everyone a global access point to it. It fits things that really exist once per process (a configuration, a logger, a connection pool), but it is also the most criticised pattern because it is a global object with mutable state.
Way 1: a module-level object
A module is executed once and cached in sys.modules. An object created at module level is therefore already a singleton, and every from config import settings returns the same object. This is the most Pythonic way and needs no pattern code.
# --- config.py ---
class _Settings:
def __init__(self):
self.debug = False
settings = _Settings() # created once, at the first import of config
# --- a.py and b.py both do: from config import settings ---
a = settings
b = settings
a.debug = True
print(b.debug, a is b)True TrueWay 2: __new__
__new__ creates the object, so it can return a saved instance. The trap: Python calls __init__ after every Config(), and a normal __init__ would reset the state of the shared object.
class Config:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self): # runs on EVERY Config() call!
self.debug = False
a = Config()
a.debug = True
b = Config()
print(a is b, b.debug)