[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Documentation of __hash__

On Wednesday, February 5, 2020 at 7:41:13 PM UTC+1, Dieter Maurer wrote:
> Stefan Halfpap wrote at 2020-2-5 14:57 +0100:
> >I do not understand the following statement from the python (2 and 3) documentation regarding __hash__ and __eq__ methods:
> >"If a class does not define an __eq__() <https://docs.python.org/3/reference/datamodel.html#object.__eq__> method it should not define a __hash__() <https://docs.python.org/3/reference/datamodel.html#object.__hash__> operation either;?
> >(see https://docs.python.org/3/reference/datamodel.html#object.__hash__ <https://docs.python.org/3/reference/datamodel.html#object.__hash__> )
> >
> >I thought it relates to the second part (?if it defines __eq__() <https://docs.python.org/3/reference/datamodel.html#object.__eq__> but not __hash__() <https://docs.python.org/3/reference/datamodel.html#object.__hash__>, its instances will not be usable as items in hashable collections?), which is totally clear to me.
> >But then the implication should be the other way around.
> "if not A then not B" is equivalent to "if B then A".
> In your case: "__eq__ not defined, then __hash__ not defined"
> is equivalent to "__hash__ definied requires __eq__ defined".

You are right.
This is what the (first part of the) documentation says,
but I do not know why.

I thought it should be:
"if __hash__ is not defined, then __eq__ should not be defined"
which is equivalent to "__eq__ defined then __hash__ should be defined" (the second part, which is clear to me)

If not, why should a class not define __hash__, if it does not define __eq__?