[Python-Dev] Python 3.x and bytes

Ethan Furman ethan at stoneleaf.us
Fri May 20 02:40:26 CEST 2011


Nick Coghlan wrote:
> On Thu, May 19, 2011 at 6:43 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> For point 2, I'm personally +0 on the idea of having 1-element bytes
>> and bytearray objects delegate hashing and comparison operations to
>> the corresponding integer object. We have the power to make the
>> obvious code correct code, so let's do that. However, the implications
>> of the additional key collisions in value based containers may need to
>> be explored further.

Several folk have said that objects that compare equal must hash equal...

Why?  It's an honest question.  Here's what I have tried:

--> class Wierd():
...     def __init__(self, value):
...         self.value = value
...     def __eq__(self, other):
...         return self.value == other
...     def __hash__(self):
...         return hash((self.value + 13) ** 3)
...
--> one = Wierd(1)
--> two = Wierd(2)
--> three = Wierd(3)
--> one
<Wierd object at 0x00BFE710>
--> one == 1
True
--> one == 2
False
--> two == 2
True
--> three == 3
True
--> d = dict()
--> d[one] = '1'
--> d[two] = '2'
--> d[three] = '3'
--> d
{<Wierd object at 0x00BFE710>: '1',
  <Wierd object at 0x00BFE870>: '3',
  <Wierd object at 0x00BFE830>: '2'}
--> d[1] = '1.0'
--> d[2] = '2.0'
--> d[3] = '3.0'
--> d
{<Wierd object at 0x00BFE870>: '3',
  1: '1.0',
  2: '2.0',
  3: '3.0',
  <Wierd object at 0x00BFE830>: '2',
  <Wierd object at 0x00BFE710>: '1'}
--> d[2]
'2.0'
--> d[two]
'2'

This behavior matches what I was imagining for having
b'a' == 97.  They compare equal, yet remain distinct objects
for all other purposes.

If anybody has a link to or an explanation why equal values must be 
equal hashes I'm all ears.  My apologies in advance if this is an 
incredibly naive question.

~Ethan~


More information about the Python-Dev mailing list