config.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import typing
  2. from pathlib import Path
  3. import tomli
  4. import os
  5. @typing.no_type_check
  6. class SingletonMeta(type):
  7. """
  8. Singleton metaclass to ensure only one instance of a class exists.
  9. """
  10. _instances = {}
  11. @typing.no_type_check
  12. def __call__(cls, *args, **kwargs):
  13. if cls not in cls._instances:
  14. cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
  15. return cls._instances[cls]
  16. class Config(metaclass=SingletonMeta):
  17. def __init__(
  18. self,
  19. config_path: Path | None = Path(__file__).parent.parent / "config.toml",
  20. ):
  21. """
  22. Initialize the configuration object.
  23. Args:
  24. config_path (Path): Path to the configuration file.
  25. """
  26. if config_path is None and "ADL_CONFIG_PATH" in os.environ:
  27. self.config_path = Path(os.environ["ADL_CONFIG_PATH"])
  28. elif config_path is not None:
  29. self.config_path = config_path
  30. else:
  31. raise ValueError("Either config_path or ADL_CONFIG_PATH must be provided")
  32. self.loaded_config_path = None
  33. self._load_config()
  34. def _load_config(self):
  35. """
  36. Load the configuration from the specified file.
  37. """
  38. with open(self.config_path, "rb") as f:
  39. config = tomli.load(f)
  40. self.loaded_config_path = str(self.config_path)
  41. print(f"Loaded config from {self.config_path}")
  42. self._config_dict = config
  43. def __getitem__(self, key: str):
  44. """
  45. Get a configuration value by key.
  46. Args:
  47. key (str): The key of the configuration value.
  48. Returns:
  49. The configuration value.
  50. """
  51. return self._config_dict.get(key, None)