import typing from pathlib import Path import tomli import os @typing.no_type_check class SingletonMeta(type): """ Singleton metaclass to ensure only one instance of a class exists. """ _instances = {} @typing.no_type_check def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Config(metaclass=SingletonMeta): def __init__( self, config_path: Path | None = Path(__file__).parent.parent / "config.toml", ): """ Initialize the configuration object. Args: config_path (Path): Path to the configuration file. """ if config_path is None and "ADL_CONFIG_PATH" in os.environ: self.config_path = Path(os.environ["ADL_CONFIG_PATH"]) elif config_path is not None: self.config_path = config_path else: raise ValueError("Either config_path or ADL_CONFIG_PATH must be provided") self.loaded_config_path = None self._load_config() def _load_config(self): """ Load the configuration from the specified file. """ with open(self.config_path, "rb") as f: config = tomli.load(f) self.loaded_config_path = str(self.config_path) print(f"Loaded config from {self.config_path}") self._config_dict = config def __getitem__(self, key: str): """ Get a configuration value by key. Args: key (str): The key of the configuration value. Returns: The configuration value. """ return self._config_dict.get(key, None)