Python 如何散列 itertools.count()?

How does Python hash itertools.count()?

我正在尝试了解 hash(itertools.count(x, y)) 背后的基本机制。

我不习惯深入研究 CPython 实现,但我注意到在 itertoolsmodule.cstatic PyTypeObject count_type has 0 for tp_hash.

我假设这意味着它没有在 C 中实现 hash。那么,它是如何处理的呢?是否有用于实现 __hash__ 的 C 绑定 itertools.count 的 Python 对象?

另一方面,幕后发生的事情


itertools.count(0, 5) != itertools.count(0, 5)

它只是从 object.

继承了默认的基于身份的 __hash____eq__

tp_hash 引用 docs:

Inheritance:

Group: tp_hash, tp_richcompare

This field is inherited by subtypes together with tp_richcompare: a subtype inherits both of tp_richcompare and tp_hash, when the subtype’s tp_richcompare and tp_hash are both NULL.

由于 tp_hashtp_richcompare 都静态初始化为 0PyType_Ready 将从默认的基 class 中 copy those fieldsobject.