Hashability questions

Bob Grommes bob.grommes at gmail.com
Sun May 13 15:11:21 EDT 2012


Noob alert: writing my first Python class library.

I have a straightforward class called Utility that lives in Utility.py.

I'm trying to get a handle on best practices for fleshing out a library.  As such, I've done the following for starters:

  def __str__(self):
    return str(type(self))

#  def __eq__(self,other):
#    return hash(self) == hash(other)

The commented-out method is what I'm questioning.  As-is, I can do the following from my test harness:

u = Utility()
print(str(u))
print(hash(u))
u2 = Utility()
print(hash(u2))
print(hash(u) == hash(u2))

However if I uncomment the above _eq_() implementation, I get the following output:

<class 'Utility.Utility'>
Traceback (most recent call last):
  File "/Users/bob/PycharmProjects/BGC/Tests.py", line 7, in <module>
    print(hash(u))
TypeError: unhashable type: 'Utility'

Process finished with exit code 1

Obviously there is some sort of default implementation of __hash__() at work and my implementation of _eq_() has somehow broken it.  Can anyone explain what's going on?



More information about the Python-list mailing list