SingletonType.py 502 B

123456789101112131415
  1. import threading
  2. class SingletonType(type):
  3. _instance_lock = threading.Lock()
  4. def __call__(cls, *args, **kwargs):
  5. if not hasattr(cls, "_instance"):
  6. with SingletonType._instance_lock:
  7. if not hasattr(cls, "_instance"):
  8. cls._instance = super(SingletonType, cls).__call__(*args, **kwargs)
  9. return cls._instance
  10. @classmethod
  11. def clear_instance(cls):
  12. if hasattr(cls, "_instance"):
  13. delattr(cls, "_instance")