Files
chongming-core/workers/demo/global_var.py
T

33 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Demo 进程插件全局运行时状态 — 与 inline 插件约定一致
约定:
- 模块只做"声明默认值",不产生任何导入期副作用
- 所有值统一在 on_init 中通过 set_global_var 显式写入
- set_global_var 仅允许写入 _ALLOWED 白名单,拼写错误会立即抛错
"""
from typing import Any
# 允许写入的全局变量白名单(防止拼写错误静默创建无用的新变量)
_ALLOWED = frozenset({"greeting_prefix"})
# 显式声明所有运行时状态(默认值,运行时由 on_init 写入)
greeting_prefix: str = "Hello"
def set_global_var(name: str, value: Any) -> None:
"""白名单校验版 setter — 设置模块级运行时状态。"""
if name not in _ALLOWED:
raise KeyError(f"global_var 未知变量: {name}(允许: {sorted(_ALLOWED)})")
globals()[name] = value
def require(name: str) -> Any:
"""取"必须已存在"的值,未初始化时抛清晰错误。"""
if name not in _ALLOWED:
raise KeyError(f"global_var 未知变量: {name}")
return globals()[name]
__all__ = ["greeting_prefix", "set_global_var", "require"]