上下文管理器与进一步移植

This commit is contained in:
2025-10-13 00:28:15 +08:00
parent 6dac9d5a7c
commit aa99aa7686
67 changed files with 438 additions and 4415 deletions

31
src/heurams/context.py Normal file
View File

@@ -0,0 +1,31 @@
"""
全局上下文管理模块
"""
from contextvars import ContextVar
from typing import Optional
from heurams.services.config import ConfigFile
config_var: ContextVar[ConfigFile] = ContextVar('config_var', default=ConfigFile("")) # 配置文件
runtime_var: ContextVar = ContextVar('runtime_var', default=None) # 运行时共享数据
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