蓝色天空网 · mbsky.com 全部实例

备忘录:独立存档、恢复及历史分支

创建和恢复都要隔离可变状态,历史容量和归属必须明确。

本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。

Python 3.12.14 · 22 项实际检查 · 当前入口SHA256 040f5919f40b30d72e8e548f451c3327bce044a964d34454465fa3995e7f86a1

检查项实际结果预期结果
saved nested state isolated11
restore does not contaminate saved inventory11
frozen snapshot field"FrozenInstanceError""AttributeError"
another origin cannot load snapshot"ValueError""ValueError"
bounded history size22
first undo"二""二"
second undo"一""一"
oldest dropped no further undofalsefalse
redo restores content"二""二"
new edit clears redofalsefalse
failed edit restored"ValueError""ValueError"
failed edit state"{\"content\": \"新分支\", \"health\": 100, \"inventory\": [{\"name\": \"sword\", \"stats\": {\"power\": 1}}], \"level\": 1, \"score\": 0}""{\"content\": \"新分支\", \"health\": 100, \"inventory\": [{\"name\": \"sword\", \"stats\": {\"power\": 1}}], \"level\": 1, \"score\": 0}"
selective snapshot excludes cache{}{}
named save identitytruetrue
missing named slot"KeyError""KeyError"
invalid capacity"ValueError""ValueError"
actual save file schema11
save timestamp explicit"2026-11-03T00:00:00+00:00""2026-11-03T00:00:00+00:00"
disk nested data11
actual DB savepoint not connection-copy rollback[["base"]][["base"]]
configuration selective backup"blue""blue"
configuration transient cache unchanged{"transient": 1}{"transient": 1}

本章源码与生成文件

下载独立入口 共享实现 补充实例实现 本章结果JSON

查看当前核心代码
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *

def memento(c,out):
    origin=OriginatorModel();history=SnapshotHistory(origin,2);saved=origin.save();origin.state["inventory"][0]["stats"]["power"]=9
    c.eq("saved nested state isolated",json.loads(saved.payload)["inventory"][0]["stats"]["power"],1)
    origin.restore(saved);origin.state["inventory"][0]["stats"]["power"]=7;origin.restore(saved);c.eq("restore does not contaminate saved inventory",origin.state["inventory"][0]["stats"]["power"],1)
    c.raises("frozen snapshot field",AttributeError,lambda:setattr(saved,"payload","{}"));c.raises("another origin cannot load snapshot",ValueError,lambda:OriginatorModel().restore(saved))
    history.edit(lambda state:state.update(content="一"));history.edit(lambda state:state.update(content="二"));history.edit(lambda state:state.update(content="三"))
    c.eq("bounded history size",len(history.undo_stack),2);history.undo();c.eq("first undo",origin.state["content"],"二");history.undo();c.eq("second undo",origin.state["content"],"一");c.eq("oldest dropped no further undo",history.undo(),False)
    history.redo();c.eq("redo restores content",origin.state["content"],"二");history.edit(lambda state:state.update(content="新分支"));c.eq("new edit clears redo",history.redo(),False)
    before=origin.save()
    def bad(state):state["content"]="bad";raise ValueError("controlled edit")
    c.raises("failed edit restored",ValueError,lambda:history.edit(bad));c.eq("failed edit state",origin.save().payload,before.payload)
    origin.cache["transient"]="cache";checkpoint=origin.save();origin.cache.clear();origin.restore(checkpoint);c.eq("selective snapshot excludes cache",origin.cache,{})
    slots={"first":saved,"current":origin.save()};c.eq("named save identity",slots["first"]is saved,True);c.raises("missing named slot",KeyError,lambda:slots["absent"])
    c.raises("invalid capacity",ValueError,lambda:SnapshotHistory(origin,0))
    path=out/"owned-game-save.json";path.write_text(json.dumps({"version":1,"timestamp":saved.timestamp,"state":json.loads(saved.payload)},ensure_ascii=False),encoding="utf8")
    loaded=json.loads(path.read_text(encoding="utf8"));c.eq("actual save file schema",loaded["version"],1);c.eq("save timestamp explicit",loaded["timestamp"],"2026-11-03T00:00:00+00:00");c.eq("disk nested data",loaded["state"]["inventory"][0]["stats"]["power"],1)

def extra_memento(c,out):
    with closing(sqlite3.connect(':memory:'))as db:
        db.execute('CREATE TABLE lesson(title TEXT)');db.execute('INSERT INTO lesson VALUES(?)',('base',));db.commit();db.execute('SAVEPOINT lesson_checkpoint');db.execute('INSERT INTO lesson VALUES(?)',('temporary',));db.execute('ROLLBACK TO lesson_checkpoint');db.execute('RELEASE lesson_checkpoint');c.eq("actual DB savepoint not connection-copy rollback",db.execute('SELECT title FROM lesson').fetchall(),[('base',)])
    config={"settings":{"theme":"blue"},"preferences":{"font":16},"cache":{"transient":1}};backup=deepcopy({k:config[k]for k in ('settings','preferences')});config['settings']['theme']='dark';config.update(deepcopy(backup));c.eq("configuration selective backup",config['settings']['theme'],'blue');c.eq("configuration transient cache unchanged",config['cache'],{'transient':1})

def run_case(out):
    c=Checks()
    memento(c,out)
    extra_memento(c,out)
    return {"chapter":'python-memento',"checks":c.rows,"passed":True,"scope":"named owned all24chapter named cases only; full source coverage pending"}

if __name__ == "__main__":
    output=Path(sys.argv[1]);output.mkdir(parents=True,exist_ok=False)
    print(json.dumps(run_case(output),ensure_ascii=False,default=repr))

上图是本站运行生成文件,不能当作来源原图已采集。