Hashability of classes, old and new

  • Thread starter =?iso-8859-1?Q?Fran=E7ois?= Pinard
  • Start date
?

=?iso-8859-1?Q?Fran=E7ois?= Pinard

Hi, people. I observe that there is a difference in hashability between
old-style and new-style instances, when they are comparable. I wonder
what I meaning I should make out of this. Maybe the simplest is to first
show an example:

---------------------------------------------------------------------->
Python 2.3.3 (#1, Jan 24 2004, 09:01:30)
[GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information..... __metaclass__ = type
.... def __cmp__(a, b):
.... print 'C', a, b
.... return 0
.... .... import types
.... __metaclass__ = types.ClassType
.... def __cmp__(a, b):
.... print 'D', a, b
.... return 0
.... Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unhashable instance
----------------------------------------------------------------------<

As you see, `C' is new-style, `D' is old-style. (I could have written
declarations more simply, if __metaclass__ was not preset to type within
my `.pythonrc' -- in any case, the above writing is very explicit. :)

Is there a change in semantics in this area? For new-style, I have:

---------------------------------------------------------------------->
c1 = C()
c2 = C()
z = {}
z[c1] = 101
z[c2] = 102
c1 == c2
C said:
z[c1] 101
z[c2]
102
----------------------------------------------------------------------<

So, despite c1 equals c2, they create two different entries in a
dictionary. I thought that this is such an inconsistency that was the
reason behind requiring an explicit `__hash__' for old-style classes.
So, it seems I was not thinking right, there is something which escapes
my understanding. Would some kind soul help mine? :)
 
J

Josiah Carlson

So, despite c1 equals c2, they create two different entries in a
dictionary. I thought that this is such an inconsistency that was the
reason behind requiring an explicit `__hash__' for old-style classes.
So, it seems I was not thinking right, there is something which escapes
my understanding. Would some kind soul help mine? :)

When two objects have different hashes, they are not required to be
compared when inserted into a dictionary. They may be compared, if two
hashes drop the objects into the same bin.

- Josiah
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top