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

  1. Override __new__ to return an existing instance if available
  2. Store the instance in a private class variable
  3. Alternatively, use a decorator that caches instances
  4. For thread safety, add a locking mechanism
  5. 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