Skip to content
Advertisement

How does Python hash itertools.count()?

I am trying to understand the underlying mechanics behind hash(itertools.count(x, y)).

I am not used to looking deeply into CPython implementations, but I noticed that in itertoolsmodule.c the static PyTypeObject count_type has 0 for tp_hash.

I am assuming that this means that it does not implement hash in C. So, how does it get taken care of? Is there a Python object for the C binding itertools.count that implements __hash__?

On another note, what happens behind the scene such that

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

Advertisement

Answer

It just inherits the default identity-based __hash__ and __eq__ from object.

Quoting the docs for tp_hash:

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.

Since tp_hash and tp_richcompare are both statically initialized to 0, PyType_Ready will copy those fields from the base class, which defaults to object.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement