are user defined classes hashable?

Nicolas Dandrimont Nicolas.Dandrimont at crans.org
Sun Jul 19 10:07:57 EDT 2009


* Alan G Isaac <alan.isaac at gmail.com> [2009-07-19 13:48:16 +0000]:

> Are user defined classes hashable?
> (The classes; *not* the instances!)
> 
> I want to use some classes as dictionary keys.
> Python is not objecting,
> but I'm not sure how to think about
> whether this could be dangerous.
> I'm inclined to guess it will be hashed by id
> and this is OK.

You can check for yourself:

In [1]: class Foo(object):
   ...:     pass
   ...: 

In [2]: foo = Foo()

In [3]: hash
hash

In [3]: hash(foo)
Out[3]: 15294992

In [4]: id(foo)
Out[4]: 15294992

So yes, by default, user-defined classes are hashable, by id. You can
override this behaviour by defining the __hash__ special method on
your object.

HTH,
-- 
Nicolas Dandrimont
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 204 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20090719/ca0c9da8/attachment-0001.sig>


More information about the Python-list mailing list