Strange if I show the dictionary in IPython, it seems to recount the key hashes. This behavior does not occur in regular python interpreters, and I would like to know what is the reason for this.
Example:
class Fun(object):
def __init__(self, value):
self._value = value
def __hash__(self):
print('hashing')
return hash(self._value)
def __eq__(self, other):
if isinstance(other, Fun):
return self._value == other._value
else:
return self._value == other
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self._value)
when creating a dictionary requires hash:
In [2]: dict1 = {Fun(10): 5, Fun(11): 5}
hashing
hashing
But it surprised me when I later opened the dictionary:
In [3]: dict1
Out[3]: hashing
hashing
{Fun(11): 5, Fun(10): 5}
This does not happen if I use repreither items:
In [4]: dict1.items()
Out[4]: [(Fun(10), 5), (Fun(11), 5)]
In [5]: repr(dict1)
Out[5]: '{Fun(10): 5, Fun(11): 5}'
Usually I don’t care, but I study some performance problems with a class that has a very expensive method hash, and it seems unreasonable to me why the mapping dict1(especially against repr(dict1)) should recount the hashkeys.
, ( , ), , . IPython 5.1.0.