singleton.py 1.1 KB

12345678910111213141516171819202122232425262728
  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 in dataclasses.fields(instance_type):
  21. if dataclasses.is_dataclass(field.type):
  22. setattr(instance, field.name, field.type())
  23. else:
  24. setattr(instance, field.name, field.default)