Re: BUG? function objects as dictionary keys?

Guido.van.Rossum@cwi.nl
Mon, 01 Aug 1994 01:22:07 +0200

> I want to make a dictionary whose keys are functions:
>
> def somefunction():
> print "this is a dummy function"
>
> my_dict = {somefunction : "a function"}
>
> print my_dict
>
> This code fails with the message:
>
> Traceback (innermost last):
> File "junk.py", line 7
> my_dict = {somefunction : "a function"}
> TypeError: unhashable type
>
> Very odd. The source code for funcobject.c clearly shows a hash
> function defined. Is there something I'm missing here?

Yes, it's a bug. I have fixed, but it's rather complicated, and the
fix wasn't released with 1.0.3. The reason this fails is that the
hash function for function objects requests the hash for the code
object, which in turn requests the hash of its constituent parts, and
two of these parts are lists, which don't have a hash because they are
mutable. My fix consists of changing things so that the two lists in
code objects can be tuples instead.

A work-around until I publish my fix is to use the id() of the
function as the dictionary key. You may have to maintain a mapping
from id() to functions if you need that too.

Sorry,

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>