Pre-PEP: __hashable__

Chad Netzer cnetzer at mail.arc.nasa.gov
Tue Dec 10 21:20:59 EST 2002


On Tuesday 10 December 2002 15:00, Delaney, Timothy wrote:

> I would like to propose an alternative, prompted by the new
> `sets` module in 2.3.
[snip]
> A new builtin function `hashable(obj)` and a new magic method
> `__hashable__(self)` are added.

Wow, the can of worms you have opened...

> `hashable(obj)` takes a single object. If the object has a
> `__hashable__()` method it is called, and the result returned,
> otherwise the object itself is returned:

Why-oh-why would it return self if an object isn't hashable?  That 
alone makes the whole thing worthless.  It should throw an 
expection.

> What does this gain us? It allows a mutable type to have a
> snapshot taken an used as a dictionary key, or other place which
> requires a hashable instance.

But what happens when I want to make the object unhashable again?   
If the answer is, "You don't.  You have to create a new object.", 
then I would ask, where could this possibly be useful?

  For example, I use a dict as a key.  Later I want to retrieve 
something using that key.  But, my mutable dictionary has changed.  
So my key is lost.

  Or, suppose I use a list as a key.  Then I want to retrieve it, 
but my list has changed?  Well, perhaps I have a tuple that has all 
the same objects as a list.  Should that allow me to retrieve the 
list key?  If so, it needs to hash to the same key (and thus, I 
couldn't have BOTH a list and tuple as keys in the same dict(), and 
have them be distinct).  But lists and tuples with the same entries 
do not compare the same, so that would be wierd.  Should that be 
"fixed", changing Python semantics?

It would be nice to conceptually be able to have an immutable 
dictionary type (and perhaps someone has made one), to use as a 
key.  But there are workarounds already that can be used (id() as 
an example, thought it takes care)

That is my knee-jerk reaction.  I won't say it can't be done, or 
wouldn't be useful.  But I think you haven't yet even begun to 
think of all the ramifications.  (or else, I missed something; I'm 
quite daft)

-- 
Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer
cnetzer at mail.arc.nasa.gov




More information about the Python-list mailing list