Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: Any built-in ishashable method ? (http://www.velocityreviews.com/forums/t956647-re-any-built-in-ishashable-method.html)

Dave Angel 01-18-2013 11:05 AM

Re: Any built-in ishashable method ?
 
On 01/18/2013 05:36 AM, Jean-Michel Pichavant wrote:
> Hello people,
>
> Is there any built-in way to know if an object is a valid dictionary key ? From what I know, the object must be hashable, and from the python doc, an object is hashable if it has the __hash__ and (__cmp__ or __eq__) methods.
>
> http://docs.python.org/2/glossary.html#term-hashable
>
> I found this on the net, but considering the above definition, does it really check the cmp/eq existence ?
>
> def ishashable(x):
> try:
> hash(x)
> except TypeError:
> return False
> else:
> return True
>
> I was trying to know if any custom class can be used as a dict key. It looks like you can. Yet I'm a little bit concerned, because last time I used invalid objects as keys, I got a bug that was really difficult to spot.
>


Yes, one can write custom classes whose objects may be used a dict key.
The main conceptual requirement is the object be conceptually
immutable. The way the class author indicates that is to define the two
methods, __hash__() and __eq__(). (or __cmp__() I suppose)

To avoid bugs, there are obviously some constraints on the semantics of
those methods. Main ones are 1) that the hash value should not change
over time, and 2) that if two instances are equal at one moment, that
they stay so, and vice versa.



--
DaveA


All times are GMT. The time now is 10:25 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.