""" 全局上下文管理模块 以及基准路径 """ from contextvars import ContextVar import pathlib from heurams.services.config import ConfigFile root_dir = pathlib.Path(__file__).parent working_dir = pathlib.Path.cwd() config_var: ContextVar[ConfigFile] = ContextVar('config_var', default=ConfigFile(working_dir / "config" / "config.toml")) # 配置文件 runtime_var: ContextVar = ContextVar('runtime_var', default=dict()) # 运行时共享数据 class ConfigContext: """ 功能完备的上下文管理器 用于临时切换配置的作用域, 支持嵌套使用 Example: >>> with ConfigContext(test_config): ... get_daystamp() # 使用 test_config >>> get_daystamp() # 恢复原配置 """ def __init__(self, config_provider: ConfigFile): self.config_provider = config_provider self._token = None def __enter__(self): self._token = config_var.set(self.config_provider) return self def __exit__(self, exc_type, exc_val, exc_tb): config_var.reset(self._token) # type: ignore