56 lines
1.8 KiB
Python
56 lines
1.8 KiB
Python
from .electron import Electron
|
|
from .nucleon import Nucleon
|
|
import pathlib
|
|
import typing
|
|
import toml
|
|
import json
|
|
|
|
class Atom():
|
|
"""
|
|
统一处理一系列对象的所有信息与持久化:
|
|
关联电子 (算法数据)
|
|
关联核子 (内容数据)
|
|
关联轨道 (策略数据)
|
|
以及关联路径
|
|
"""
|
|
|
|
def __init__(self, ident = ""):
|
|
self.ident = ident
|
|
self.register = {
|
|
"nucleon": None,
|
|
"nucleon_path": None,
|
|
"nucleon_fmt": "toml",
|
|
"electron": None,
|
|
"electron_path": None,
|
|
"electron_fmt": "json",
|
|
"orbital": None,
|
|
"orbital_path": None, # 允许设置为 None, 此时使用 nucleon 文件内的推荐配置
|
|
"orbital_fmt": "toml",
|
|
}
|
|
|
|
def link(self, key, value):
|
|
if key in self.register.keys():
|
|
self.register[key] = value
|
|
else:
|
|
raise ValueError("不受支持的原子元数据链接操作")
|
|
|
|
def persist(self, key):
|
|
path: pathlib.Path | None = self.register[key + "_path"]
|
|
if isinstance(path, pathlib.Path):
|
|
path = typing.cast(pathlib.Path, path)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
if self.register[key + "_fmt"] == "toml":
|
|
with open(path, "w") as f:
|
|
toml.dump(self.register[key], f)
|
|
elif self.register[key + "_fmt"] == "json":
|
|
with open(path, "w") as f:
|
|
json.dump(self.register[key], f)
|
|
else:
|
|
raise KeyError("不受支持的持久化格式")
|
|
else:
|
|
raise TypeError("对未初始化的路径对象操作")
|
|
|
|
@staticmethod
|
|
def placeholder():
|
|
return (Electron.placeholder(), Nucleon.placeholder(), {})
|