How to implement singleton pattern in Python
· Category: Python Programming
Short answer
A singleton ensures only one instance of a class exists. Implement it with __new__, a decorator, or a metaclass depending on your needs. For object-oriented patterns, see python classes objects. For decorators in general, see python decorators explained.
Steps
- Override
__new__to return an existing instance if available - Store the instance in a private class variable
- Alternatively, use a decorator that caches instances
- For thread safety, add a locking mechanism
- Consider whether a module-level variable or Borg pattern is simpler
Tips
- Singletons are useful for shared resources like database connections
- Avoid overusing singletons because they make testing harder
- For testing patterns, see python testing with pytest