singleton.py 1.5 KB

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