annotationlib.ForwardRef.__hash__ raises TypeError on an unhashable value
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
annotationlib.ForwardRef defines both __eq__ and __hash__, but __hash__
raises TypeError when the forward reference holds an unhashable value, even
though two such forward references compare equal. This violates the data model
(objects that compare equal must be hashable and hash equal) and breaks storing
forward references in sets or as dict keys, which typing tools do.
Reproducer
from annotationlib import Format, get_annotations
class Unhashable:
__hash__ = None
obj = Unhashable()
def f(a: undefined | obj): ...
fr1 = get_annotations(f, format=Format.FORWARDREF)["a"]
fr2 = get_annotations(f, format=Format.FORWARDREF)["a"]
assert fr1 == fr2
hash(fr1) # TypeError: unhashable type: 'Unhashable'
obj resolves as a global, so the FORWARDREF format stores it in the forward
reference's __extra_names__. The same happens when the forward reference's
__owner__ is unhashable, for example a class whose metaclass sets
__hash__ = None.
Root cause
ForwardRef.__hash__ already hashes the unhashable __globals__ and __cell__
fields by identity (id()), but __owner__ and __extra_names__ are hashed
directly. __extra_names__ holds arbitrary values embedded in an annotation
that the FORWARDREF format could not render as a plain name, so those values
may be unhashable.
Regression
This is a sibling of #143831, which fixed the same class of bug for __cell__.
The traceback in that report already pointed at the __extra_names__ line.
Affected versions
3.14+ (where annotationlib was added).
Linked PRs
- gh-152360
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 annotationlib.ForwardRef.hash 开始,将 globals 和 cell 的处理方式与 owner 和 extra_names 进行比较。查看相关 issue #143831,并复现此处所示的失败;当包含不可哈希值的相等 forward references 能够在不产生 TypeError 的情况下被一致地进行哈希时,即表示完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- tooling
- Issue 类型
- 缺陷
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 35/100