singleton.py 1.3 KB

123456789101112131415161718192021222324252627282930
  1. import dataclasses
  2. class Singleton(type):
  3. _instances: dict = {}
  4. def __call__(cls, *args, **kwargs):
  5. if cls not in cls._instances:
  6. cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
  7. else:
  8. # allow updates, just update existing instance
  9. # perhaps not the most orthodox way to do it, though it simplifies client code
  10. # useful for pre-defined groups of settings
  11. instance = cls._instances[cls]
  12. for key, value in kwargs.items():
  13. setattr(instance, key, value)
  14. return cls._instances[cls]
  15. @classmethod
  16. def reset(cls):
  17. # used by pytest to reset the state of the singleton instances
  18. for instance_type, instance in cls._instances.items():
  19. print('resetting... ', instance_type)
  20. for field_info in dataclasses.fields(instance_type):
  21. if dataclasses.is_dataclass(field_info.type):
  22. setattr(instance, field_info.name, field_info.type())
  23. elif field_info.default_factory is not dataclasses.MISSING:
  24. setattr(instance, field_info.name, field_info.default_factory())
  25. else:
  26. setattr(instance, field_info.name, field_info.default)