Hacker News 中文摘要

RSS订阅

Python的“冻结”字典 -- A “frozen” dictionary for Python

文章摘要

Python字典因其可变性在并发代码中存在共享问题。为解决此问题,Victor Stinner和Donghee Na提出了PEP 814提案,建议在Python语言中新增不可变字典类型"frozendict",以支持更安全的并发数据共享。

文章总结

Python将引入"冻结字典"类型

Python代码中字典无处不在,但字典的可变性使其在并发代码中共享数据时存在问题。为解决这一问题,Victor Stinner和Donghee Na于11月13日提交了PEP 814,提议在Python内置模块中添加不可变的frozendict类型。

核心特性

  • frozendict继承自基础object类型(而非dict),通过多种方式创建: python fd = frozendict() # 空字典 fd = frozendict(a=1, b=2) # 等价于{'a':1, 'b':2} fd = frozendict({'a':1}) # 从现有字典创建
  • 键必须是可哈希的不可变对象,值可以是可变对象
  • 若所有值都不可变,则整个frozendict可哈希
  • 支持与普通字典的等值比较和并集操作(|运算符)
  • 保留字典插入顺序,但顺序不影响哈希值

标准库应用

PEP中列举了标准库中多个可用frozendict替代dict的场景,包括: - functools.lru_cache的缓存键 - 类__dict__的替代 - 配置参数的存储容器

争议与优化

主要讨论集中在字典转换性能上: - 当前设计采用O(n)的浅拷贝方式 - 有开发者建议O(1)的原地转换(如.freeze()方法) - 核心开发者Brett Cannon反对改变对象类型,认为会导致并发问题 - 未来可能通过PEP 351的"冻结协议"实现优化

该提案已提交Python指导委员会审议。随着Python无GIL多线程版本的推进,这种线程安全的数据结构将更具实用价值。

(注:原文中关于LWN订阅内容、历史PEP 416等背景信息已精简,保留了技术细节和核心讨论)

评论总结

以下是评论内容的总结:

支持frozendict的观点

  1. 功能需求:用户希望Python能像TypeScript一样自动推断最窄的TypedDict类型(评论1:"I miss this TS feature in Python on the daily")。
  2. 现有替代方案的不足:虽然可以使用MappingProxyType实现类似功能,但frozendict更直接(评论3:"A frozen dictionary would be very welcome")。
  3. 性能优化:frozendict可以在某些场景下优化性能,例如JIT可以优化构造过程(评论4:"O(n) operation can be turned to O(1)")。
  4. 实际应用:SQLAlchemy等库已广泛使用frozendict,支持其加入标准库(评论8:"Would be a very welcome addition to the stdlib")。
  5. 并发与安全性:frozendict能明确区分可变与不可变数据,避免运行时意外修改(评论12:"There’s a huge difference between functions that might mutate a dictionary and functions that definitely won’t")。

反对或质疑的观点

  1. 必要性存疑:有人认为冻结字典的需求较弱,现有方法(如MappingProxyType或元组)已足够(评论10:"'it prevents any unintended modifications' is a bit weak")。
  2. 历史争议:Raymond Hettinger曾认为冻结字典是“一罐蠕虫”,且不特别有用(评论7:"freezing dicts is a can of worms and not especially useful")。
  3. 功能局限性:frozendict无法解决字典作为键的问题,因为哈希限制依然存在(评论11:"dicts cannot be dict keys... and there is no reasonable builtin way to get around this")。

其他观点

  1. 与namedtuple的比较:用户对frozendict与namedtuple的区别感到困惑,认为两者的界限模糊(评论6:"The line between dictionaries and named tuples and structs... has always seemed a bit blurry")。
  2. 跨语言参考:C#的frozendict因其读取优化而受到认可(评论13:"It’s optimized for fast reads in exchange for expensive creation")。

总结:评论中支持frozendict的观点主要围绕功能需求、性能优化和实际应用,而反对意见则集中在必要性不足和现有替代方案的可行性上。