Singleton in Python: module-level state, new, or decorator, with caveats
The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. In Python, the simplest and most Pythonic way to achieve this is a module-level instance, because modules are singletons by nature: they are imported once and cached in sys.modules. If you need a class-based singleton, you can override new to return a cached instance, use a metaclass to control instantiation, or use a decorator. Each approach has caveats. The pattern introduces global mutable state, which makes testing harder and hides dependencies. It can be thread-unsafe unless you add a lock. It complicates inheritance and can be broken by multiple interpreters or processes. In most cases, dependency injection is a better choice for testability and flexibility.
Module-level instance: define a module with a single instance and import it. This is the most Pythonic and avoids metaclass complexity.
Override new: check if an instance exists and return it. Must handle thread safety with a lock.
Metaclass: override call to control instantiation. More complex but works with inheritance.
Decorator: wrap the class to return a single instance. Simple but can break isinstance.
Caveats: global mutable state, hard to test, hides dependencies, not thread-safe unless locked, and breaks with multiple interpreters or processes.
Trade-off: singletons are convenient but often a design smell. Prefer dependency injection for testability.
Common mistake: using a singleton for a database connection without pooling, which serializes access.
Version note: Python's module system already provides singletons. No language-level singleton exists.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience