shelve.Shelf.sync() leaves writeback disabled if writing a cached entry fails
还没有人认领这个 Issue。
评估
调研方向
该错误位于 Lib/shelve.py 中,具体在 Shelf.sync() 方法中。查看将缓存条目写回的循环以及设置 self.writeback 的位置。添加一个 finally 块,以便在任何异常时将 writeback 恢复到其原始状态。运行提供的测试脚本来验证修复,并检查测试套件中是否已有针对 shelve 的测试(可能在 Lib/test/test_shelve.py 中)。
由索引模型根据 Issue 内容生成。
描述
Bug report
Bug description:
Shelf.sync() sets self.writeback to False while it writes the cached entries back, and only sets it back to True after the loop. If writing one of the entries raises (for example, a cached object that can no longer be pickled), the exception propagates as expected, but writeback stays False. The shelf keeps working, and later mutations of accessed objects are silently lost:
import shelve
class Unpicklable:
def __reduce__(self):
raise RuntimeError("cannot pickle")
d = {}
s = shelve.Shelf(d, writeback=True)
s["a"] = []
s["a"].append(Unpicklable())
try:
s.sync()
except RuntimeError:
pass
print(s.writeback) # False, expected True
s["a"].clear()
s["b"] = [1]
s["b"].append(2)
s.close()
print(shelve.Shelf(d)["b"]) # [1], expected [1, 2]
The cached entries are still in s.cache after the failure, so the caller could fix the offending object and call sync() again, but by then the shelf is no longer in writeback mode.
Restoring writeback in a finally block would fix this, leaving the cache intact so sync() can be retried.
CPython versions tested on:
3.13, 3.14, 3.15, 3.16, CPython main branch
Operating systems tested on:
Linux
Linked PRs
- gh-157977
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 36k
- 平均合并
- 1 天 12 小时
- 30 天内合并 PR
- 557
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
python/cpython 的其他 Issue
-
docs pending
难度 2/5 1-3 小时 新手友好度 78/100
-
stdlib type-feature
难度 2/5 1-3 小时 新手友好度 78/100
-
stdlib type-feature
难度 2/5 1-3 小时 新手友好度 72/100
-
build type-bug
难度 2/5 1-3 小时 新手友好度 76/100
-
stdlib topic-email type-feature
难度 2/5 1-3 小时 新手友好度 70/100
相似的 Issue
-
bug
难度 2/5 1-3 小时 新手友好度 75/100
xinnan-tech/xiaozhi-fde-talk#263 ·
-
rules
难度 1/5 1 小时以内 新手友好度 90/100
-
难度 2/5 1-3 小时 新手友好度 70/100
huggingface/Repo2RLEnv#163 · 1 条评论 ·
-
难度 1/5 1 小时以内 新手友好度 95/100
huggingface/sentence-transformers#4074 ·
-
comp/dashboard invalid P3
难度 2/5 1-3 小时 新手友好度 70/100
NousResearch/hermes-agent#121143 ·