How to Implement a Singleton Class in Python
This code demonstrates a classic Singleton pattern in Python by overriding __new__ to ensure only one instance of the class is created, even when instantiated multiple times.
Python code
18 linesclass Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
self.value = 0
if __name__ == "__main__":
s1 = Singleton()
s2 = Singleton()
s1.value = 42
print(s1 is s2)
print(s2.value)
Output
True
42
How it works
The Singleton class overrides __new__ to control instance creation. A class attribute _instance stores the single instance, initially None. When creating an instance, if _instance is None, a new instance is created and assigned; otherwise, the existing instance is returned. This ensures s1 and s2 point to the same object, so setting value on s1 is reflected in s2. The __init__ method still runs on each instantiation, so in practice you might guard state initialization to avoid overwriting.
Common mistakes
- Forgetting that `__init__` runs every time, which can reset instance state
- Not using thread-safe locking in multi-threaded environments
- Assuming class inheritance will catch the singleton behavior without overriding again
Variations
- Use a decorator to wrap the class and cache instances
- Use a metaclass to enforce singleton behavior across subclasses
Real-world use cases
- Managing a single database connection pool across an application to avoid resource leaks.
- Sharing a global configuration object that is loaded once and accessed everywhere.
- Implementing a central logging service to ensure consistent log formatting and single file handle.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.