Singleton
A singleton is a type that has at most one instance. In Python a module is already a singleton; a class-based singleton is for when you need an instance API or lazy setup.
Detailed Explanation
The pattern exists so that configuration, a connection pool, or a hardware handle is not created twice. Java implements it with a private constructor and a static field. Python has a simpler default: a module is imported once and cached in sys.modules. config.SETTINGS is a singleton. Start there.
When you want Logger() to always return the same object, override __new__ to cache the instance, or use a module-level instance created at import. __new__ returning the cached object still calls __init__ on every Logger() unless you guard it. That second __init__ is the usual singleton bug: it resets state you thought was unique.
A decorator or a metaclass can hide the cache. They make the class harder to subclass and to test. Prefer a module, or a factory get_logger() that the tests can monkeypatch.
Singletons are shared mutable state. Tests leak if they do not reset the instance. Threads race if initialisation is not locked. Process pools each have their own singleton, which surprises people who thought "one per machine".
Alternatives: pass the dependency in (dependency injection), use contextvars for per-task state, or use functools.lru_cache on a factory for a lazy, replaceable singleton. lru_cache is easy to .cache_clear() in tests.
Do not make a domain object a singleton because it is convenient to import. Convenience is coupling. A User is not a singleton.
Code Examples
class AppConfig:
_instance = None
def __new__(cls) -> "AppConfig":
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.debug = False
return cls._instance
print(AppConfig() is AppConfig()) # Truefrom functools import lru_cache
@lru_cache(maxsize=1)
def get_config() -> AppConfig:
return AppConfig()
print(get_config() is get_config()) # True
get_config.cache_clear() # tests can reset# Module-as-singleton: settings.py
# debug = False
# Then: import settings; settings.debug = TrueCommon Gotchas
`__init__` runs on every call
reset a flag in `__new__` or move setup out of `__init__`.
Tests share the instance
clear it in a fixture or do not use a singleton in testable code.
Multiprocessing duplicates it
each process has its own. Shared state needs a server or shared memory.
A module is usually enough
a class singleton needs a reason beyond "I know this pattern from Java".