python / python/typing

Special-casing `__hash__`

未关闭
#2,284 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic: typing spec
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
8

描述

The concept of "hashable" and "unhashable" classes has been a bit of the sore point in the past. typeshed uses __hash__: ClassVar[None] to mark classes as non-hashable, although that requires a # type: ignore[assignment] annotation. I think this is special-cased by at least some type checkers for marking classes as unhashable.

Except for some wordage in the dataclasses section, the typing spec is silent about hashability. Since I believe that this needs special-casing by type checkers, it should be added to the typing spec. A raw idea:

  • Classes are hashable by default (due to object.__hash__() being implemented and typeshed having a type corresponding type annotation.)
  • To mark a class as non-hashable, use __hash__: ClassVar[None]. We could alternatively use something simpler such as __hash__ = None. I believe we used to use that, but I don't know why it's changed.
  • To mark a class as hashable, use def __hash__(self, ...) -> ..., usually def __hash__(self) -> int: ....
  • Sub-classes inherit their parent's hashability, unless overridden.

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

先阅读 typing 规范,尤其是现有的 dataclasses 部分,并查看此 issue 中的讨论和提出的替代方案。定义关于默认 hashability、__hash__: ClassVar[None]__hash__ = None、显式 __hash__ 方法以及继承的既定规则;完成的标准是 typing 规范记录已接受的行为。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
documentation
Issue 类型
文档
难度
5/5
预计耗时
一周以上
活跃度
冷清
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。