example08.py 427 B

1234567891011121314151617181920212223
  1. from functools import wraps
  2. from threading import RLock
  3. def singleton(cls):
  4. instances = {}
  5. lock = RLock()
  6. @wraps(cls)
  7. def wrapper(*args, **kwargs):
  8. if cls not in instances:
  9. with lock:
  10. if cls not in instances:
  11. instances[cls] = cls(*args, **kwargs)
  12. return instances[cls]
  13. @singleton
  14. class President:
  15. pass
  16. President = President.__wrapped__